text
stringlengths 54
60.6k
|
|---|
<commit_before>//==================================================================================================
//
// Copyright(c) 2013 - 2015 Naïo Technologies
//
// This program is free software: you can redistribute it and/or modify it under the terms of the
// GNU General Public License as published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with This program.
// If not, see <http://www.gnu.org/licenses/>.
//
//==================================================================================================
//==================================================================================================
// I N C L U D E F I L E S
#include "BuildVersion.hpp"
#include "EntryPoint.hpp"
#include <IO/IOBlueFoxStereo.hpp>
#include <IO/IOJsonReader.hpp>
#include "IO/IOTiffWriter.hpp"
#include "IO/IOBufferWriter.hpp"
#include "IO/IOFileWriter.hpp"
#include "Control/CTPid.hpp"
#include "VisionModule/VMConversion.hpp"
#include "VisionModule/VMStatistics.hpp"
#include "HTUtility.h"
#include "HTBitmap.hpp"
#include "CLFileSystem.h"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
//==================================================================================================
// C O N S T A N T S & L O C A L V A R I A B L E S
//==================================================================================================
// G L O B A L S
//==================================================================================================
// C O N S T R U C T O R (S) / D E S T R U C T O R C O D E S E C T I O N
//--------------------------------------------------------------------------------------------------
//
EntryPoint::EntryPoint()
: signaled_{ }
{
signalHandler_.attach_handler( ht::SignalHandler::Signal::Interrupt,
std::bind( &EntryPoint::set_signal, this ) );
signalHandler_.attach_handler( ht::SignalHandler::Signal::Termination,
std::bind( &EntryPoint::set_signal, this ) );
signalHandler_.start_watch();
// Register program info
std::string appName{ PROGRAM_NAME };
appName.append( "-" );
appName.append( PROGRAM_VERSION_STRING );
// Set logger output name for the program
HTLogger::SetExecModuleName( appName );
auto f = std::bind( &EntryPoint::handle_parameters, this, std::placeholders::_1,
std::placeholders::_2 );
handler_.AddParamHandler( "-c", f );
parser_.add_switch( "-c", "Calibrate stereo bench" );
}
//--------------------------------------------------------------------------------------------------
//
EntryPoint::~EntryPoint()
{
signalHandler_.stop_watch();
}
//==================================================================================================
// M E T H O D S C O D E S E C T I O N
//--------------------------------------------------------------------------------------------------
//
void
EntryPoint::set_signal()
{
signaled_ = true;
ht::log_warning( "signal received" );
}
//--------------------------------------------------------------------------------------------------
//
bool
EntryPoint::is_signaled() const
{
return signaled_;
}
//--------------------------------------------------------------------------------------------------
//
void
EntryPoint::print_header() const
{
using namespace cl;
print_line( "=============================================================================" );
print_line( "" );
print_line( " ", PROGRAM_NAME, " version ", PROGRAM_VERSION_STRING, " Copyright(c) 2013 ",
PROGRAM_OWNER );
print_line( " ", PROGRAM_DESCRIPTION );
print_line( "" );
print_line( " This program is free software: you can redistribute it and/or modify" );
print_line( " it under the terms of the GNU General Public License as published by" );
print_line( " the Free Software Foundation, either version 3 of the License, or" );
print_line( " (at your option) any later version." );
print_line( "" );
print_line( " This program is distributed in the hope that it will be useful," );
print_line( " but WITHOUT ANY WARRANTY; without even the implied warranty of" );
print_line( " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the" );
print_line( " GNU General Public License for more details." );
print_line( "" );
print_line( "=============================================================================" );
}
//--------------------------------------------------------------------------------------------------
//
bool
EntryPoint::handle_parameters( const std::string& paramName, const std::string& paramValue )
{
cl::ignore( paramName, paramValue );
return false;
}
//--------------------------------------------------------------------------------------------------
//
int32_t
EntryPoint::run( int32_t argc, const char** argv )
{
int32_t res{ EXIT_SUCCESS };
print_header();
if( parser_.validate_cmd_line( argc, argv, &handler_ ) )
{
std::string resourceFolder{ "resources/" };
io::JsonReader jsonReader;
jsonReader.load( resourceFolder.append( "config.json" ) );
const io::JsonElement benchConfig = jsonReader.get_root().get( "stereobench" );
const uint32_t width = benchConfig.as_uint32( "width", 752 );
const uint32_t height = benchConfig.as_uint32( "height", 480 );
const uint32_t exposure = benchConfig.as_uint32( "exposure", 10000 );
const uint32_t greyLevelTarget = benchConfig.as_uint32( "average_gray_value", 70 );
const bool autoexp = benchConfig.as_bool( "auto_exposure", false );
const uint32_t minExposure = benchConfig.as_uint32( "exposure_min", 12 );
const uint32_t maxExposure = benchConfig.as_uint32( "exposure_max", 20000 );
const bool hdr = benchConfig.as_bool( "hdr", false );
cl::ignore( exposure, autoexp );
cv::Size size( static_cast<int32_t>(width), static_cast<int32_t>(height) );
io::BlueFoxStereo stereoBench;
io::CameraInfo infoL = stereoBench.get_camera_info( io::BlueFoxStereo::Position::Left );
io::CameraInfo infoR = stereoBench.get_camera_info( io::BlueFoxStereo::Position::Right );
io::Intrinsics intrinsicsL, intrinsicsR;
io::Extrinsics extrinsics;
uint32_t serialNumL = cl::str_to_uint32( infoL.serialNum );
uint32_t serialNumR = cl::str_to_uint32( infoR.serialNum );
uint8_t mode{ 0x01 };
stereoBench.read_bench_params( intrinsicsL, intrinsicsR, extrinsics );
std::string dateStr{ };
cl::Date date;
date.get_date_and_time_mime( dateStr );
cl::filesystem::folder_create( dateStr );
cl::print_line( "Recording session in: ", dateStr );
size_t allParamSize = sizeof( mode ) + sizeof( serialNumL ) + sizeof( io::Intrinsics ) +
sizeof( serialNumR ) + sizeof( io::Intrinsics ) +
sizeof( io::Extrinsics );
cl::print_line( greyLevelTarget );
io::BufferWriter bufferWriter( allParamSize );
bufferWriter.write( mode );
bufferWriter.write( serialNumL );
io::IntrinsicsArray intrinsicsArrayL = intrinsicsL.to_array();
bufferWriter.write_array( intrinsicsArrayL.data(), intrinsicsArrayL.size() );
bufferWriter.write( serialNumR );
io::IntrinsicsArray intrinsicsArrayR = intrinsicsR.to_array();
bufferWriter.write_array( intrinsicsArrayR.data(), intrinsicsArrayR.size() );
io::ExtrinsicsArray extrinsicsArray = extrinsics.to_array();
bufferWriter.write_array( extrinsicsArray.data(), extrinsicsArray.size() );
const std::string filePathP = cl::filesystem::create_filespec( dateStr, "capture", "bin" );
io::write_buffer_to_file( filePathP, bufferWriter.get_buffer() );
stereoBench.start( ht::ColorSpace::RGB, width, height, minExposure, maxExposure, hdr );
control::Pid pid;
pid.set_pid_gains( 1, 0, 0 );
int32_t currentExposure{ static_cast<int32_t>(maxExposure) };
size_t nbr{ };
int8_t pressed{ };
while( !is_signaled() && pressed != 27 )
{
cm::BitmapPairEntryUniquePtr entry;
stereoBench.wait_entry( entry );
stereoBench.clear_entry_buffer();
ht::BitmapUPtr grayL = ht::unique_bitmap( entry->bitmap_left().width(),
entry->bitmap_left().height(),
entry->bitmap_left().bit_depth(),
ht::ColorSpace::Grayscale );
ht::BitmapUPtr grayR = ht::unique_bitmap( entry->bitmap_left().width(),
entry->bitmap_left().height(),
entry->bitmap_left().bit_depth(),
ht::ColorSpace::Grayscale );
std::string filePath = cl::filesystem::create_filespec(
dateStr, std::to_string( entry->get_id() ), io::tiff_file_extensions()[1] );
cl::print_line( filePath );
io::TiffWriter tiffWriter{ filePath };
tiffWriter.write_to_file( entry->bitmap_left(), entry->get_id(),
entry->get_framerate() );
tiffWriter.write_to_file( entry->bitmap_right(), entry->get_id(),
entry->get_framerate() );
vm::rgb_to_grey( entry->bitmap_left(), *grayL );
vm::rgb_to_grey( entry->bitmap_right(), *grayR );
double greyLevelL = vm::mean( *grayL );
double greyLevelR = vm::mean( *grayR );
const double greyLevel = ( greyLevelL + greyLevelR ) / 2;
const int32_t greyLevelDiff = static_cast<int32_t>(greyLevelTarget) - greyLevel;
const int32_t correctedExposureError =
static_cast<int32_t>(std::round(
pid.compute_correction( static_cast<double>(greyLevelDiff) ) ));
currentExposure += correctedExposureError;
if( currentExposure < 12 )
{
currentExposure = 12;
}
else if( currentExposure > 20000 )
{
currentExposure = 20000;
}
stereoBench.set_exposure( static_cast<uint32_t>(currentExposure) );
cv::Mat matL = cv::Mat( size, CV_8UC3 );
cv::Mat matR = cv::Mat( size, CV_8UC3 );
matL.data = entry->bitmap_left().data();
matR.data = entry->bitmap_right().data();
cv::Mat combine( std::max( matL.size().height, matR.size().height ),
matL.size().width + matR.size().width, CV_8UC3 );
cv::Mat left_roi( combine, cv::Rect( 0, 0, matL.size().width, matL.size().height ) );
matL.copyTo( left_roi );
cv::Mat right_roi( combine, cv::Rect( matL.size().width, 0, matR.size().width,
matR.size().height ) );
matR.copyTo( right_roi );
cv::imshow( "images", combine );
pressed = static_cast<int8_t>( cv::waitKey( 1 ) );
}
stereoBench.stop();
}
return res;
}
//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
//----------------------------------------- Main Function ------------------------------------------
//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
int32_t
main( int32_t argc, const char** argv )
{
int32_t ret{ EXIT_SUCCESS };
try
{
ret = EntryPoint().run( argc, argv );
}
catch( const cl::SystemError& e )
{
ht::log_fatal( "System Error: ", e.what(), e.where() );
throw;
}
catch( const cl::BaseException& e )
{
ht::log_fatal( "BaseException caught: ", e.what() );
throw;
}
catch( const std::exception& e )
{
ht::log_fatal( "std::exception caught: ", e.what() );
throw;
}
catch( ... )
{
ht::log_fatal( "Caught an exception of an undetermined type" );
throw;
}
return ret;
}
<commit_msg>correction coming from IO classes<commit_after>//==================================================================================================
//
// Copyright(c) 2013 - 2015 Naïo Technologies
//
// This program is free software: you can redistribute it and/or modify it under the terms of the
// GNU General Public License as published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with This program.
// If not, see <http://www.gnu.org/licenses/>.
//
//==================================================================================================
//==================================================================================================
// I N C L U D E F I L E S
#include "BuildVersion.hpp"
#include "EntryPoint.hpp"
#include "IO/IOStereoRigCalibration.hpp"
#include <IO/IOBlueFoxStereo.hpp>
#include <IO/IOJsonReader.hpp>
#include "IO/IOTiffWriter.hpp"
#include "IO/IOBufferWriter.hpp"
#include "IO/IOFileWriter.hpp"
#include "Control/CTPid.hpp"
#include "VisionModule/VMConversion.hpp"
#include "VisionModule/VMStatistics.hpp"
#include "HTUtility.h"
#include "HTBitmap.hpp"
#include "CLFileSystem.h"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
//==================================================================================================
// C O N S T A N T S & L O C A L V A R I A B L E S
//==================================================================================================
// G L O B A L S
//==================================================================================================
// C O N S T R U C T O R (S) / D E S T R U C T O R C O D E S E C T I O N
//--------------------------------------------------------------------------------------------------
//
EntryPoint::EntryPoint()
: signaled_{ }
{
signalHandler_.attach_handler( ht::SignalHandler::Signal::Interrupt,
std::bind( &EntryPoint::set_signal, this ) );
signalHandler_.attach_handler( ht::SignalHandler::Signal::Termination,
std::bind( &EntryPoint::set_signal, this ) );
signalHandler_.start_watch();
// Register program info
std::string appName{ PROGRAM_NAME };
appName.append( "-" );
appName.append( PROGRAM_VERSION_STRING );
// Set logger output name for the program
HTLogger::SetExecModuleName( appName );
auto f = std::bind( &EntryPoint::handle_parameters, this, std::placeholders::_1,
std::placeholders::_2 );
handler_.AddParamHandler( "-c", f );
parser_.add_switch( "-c", "Calibrate stereo bench" );
}
//--------------------------------------------------------------------------------------------------
//
EntryPoint::~EntryPoint()
{
signalHandler_.stop_watch();
}
//==================================================================================================
// M E T H O D S C O D E S E C T I O N
//--------------------------------------------------------------------------------------------------
//
void
EntryPoint::set_signal()
{
signaled_ = true;
ht::log_warning( "signal received" );
}
//--------------------------------------------------------------------------------------------------
//
bool
EntryPoint::is_signaled() const
{
return signaled_;
}
//--------------------------------------------------------------------------------------------------
//
void
EntryPoint::print_header() const
{
using namespace cl;
print_line( "=============================================================================" );
print_line( "" );
print_line( " ", PROGRAM_NAME, " version ", PROGRAM_VERSION_STRING, " Copyright(c) 2013 ",
PROGRAM_OWNER );
print_line( " ", PROGRAM_DESCRIPTION );
print_line( "" );
print_line( " This program is free software: you can redistribute it and/or modify" );
print_line( " it under the terms of the GNU General Public License as published by" );
print_line( " the Free Software Foundation, either version 3 of the License, or" );
print_line( " (at your option) any later version." );
print_line( "" );
print_line( " This program is distributed in the hope that it will be useful," );
print_line( " but WITHOUT ANY WARRANTY; without even the implied warranty of" );
print_line( " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the" );
print_line( " GNU General Public License for more details." );
print_line( "" );
print_line( "=============================================================================" );
}
//--------------------------------------------------------------------------------------------------
//
bool
EntryPoint::handle_parameters( const std::string& paramName, const std::string& paramValue )
{
cl::ignore( paramName, paramValue );
return false;
}
//--------------------------------------------------------------------------------------------------
//
int32_t
EntryPoint::run( int32_t argc, const char** argv )
{
int32_t res{ EXIT_SUCCESS };
print_header();
if( parser_.validate_cmd_line( argc, argv, &handler_ ) )
{
std::string resourceFolder{ "resources/" };
io::JsonReader jsonReader;
jsonReader.load( resourceFolder.append( "config.json" ) );
const io::JsonElement benchConfig = jsonReader.get_root().get( "stereobench" );
io::BlueFoxStereo stereoBench;
io::MVBlueFox::Params stereoRigParams;
stereoRigParams.width = benchConfig.as_uint32( "width", 752 );
stereoRigParams.height = benchConfig.as_uint32( "height", 480 );
stereoRigParams.exposure = benchConfig.as_uint32( "exposure", 20000 );
stereoRigParams.autoExposure = benchConfig.as_bool( "auto_exposure", false );
stereoRigParams.exposureMax = benchConfig.as_uint32( "exposure_max", 20000 );
stereoRigParams.exposureMin = benchConfig.as_uint32( "exposure_min", 12 );
stereoRigParams.hdrEnabled = benchConfig.as_bool( "hdr", true );
stereoRigParams.periodInUs = 45000;
cv::Size size( static_cast<int32_t>(stereoRigParams.width),
static_cast<int32_t>(stereoRigParams.height) );
io::CameraInfo infoL = stereoBench.get_camera_info( io::BlueFoxStereo::Position::Left );
io::CameraInfo infoR = stereoBench.get_camera_info( io::BlueFoxStereo::Position::Right );
uint32_t serialNumL = cl::str_to_uint32( infoL.serialNum );
uint32_t serialNumR = cl::str_to_uint32( infoR.serialNum );
uint8_t mode{ 0x01 };
io::StereoRigCalibration params;
params.read_from_stereo_rig( stereoBench );
io::Intrinsics intrinsicsL = params.get_intrinsics_left();
io::Intrinsics intrinsicsR = params.get_intrinsics_right();
io::Extrinsics extrinsics = params.get_extrinsics();
std::string dateStr{ };
cl::Date date;
date.get_date_and_time_mime( dateStr );
cl::filesystem::folder_create( dateStr );
cl::print_line( "Recording session in: ", dateStr );
size_t allParamSize = sizeof( mode ) + sizeof( serialNumL ) + sizeof( io::Intrinsics ) +
sizeof( serialNumR ) + sizeof( io::Intrinsics ) +
sizeof( io::Extrinsics );
io::BufferWriter bufferWriter( allParamSize );
bufferWriter.write( mode );
bufferWriter.write( serialNumL );
io::IntrinsicsArray intrinsicsArrayL = intrinsicsL.to_array();
bufferWriter.write_array( intrinsicsArrayL.data(), intrinsicsArrayL.size() );
bufferWriter.write( serialNumR );
io::IntrinsicsArray intrinsicsArrayR = intrinsicsR.to_array();
bufferWriter.write_array( intrinsicsArrayR.data(), intrinsicsArrayR.size() );
io::ExtrinsicsArray extrinsicsArray = extrinsics.to_array();
bufferWriter.write_array( extrinsicsArray.data(), extrinsicsArray.size() );
const std::string filePathP = cl::filesystem::create_filespec( dateStr, "capture", "bin" );
io::write_buffer_to_file( filePathP, bufferWriter.get_buffer() );
stereoBench.start( stereoRigParams );
control::Pid pid;
pid.set_pid_gains( 1, 0, 0 );
int32_t currentExposure{ static_cast<int32_t>(stereoRigParams.exposureMin) };
size_t nbr{ };
int8_t pressed{ };
while( !is_signaled() && pressed != 27 )
{
cm::BitmapPairEntryUniquePtr entry;
stereoBench.wait_entry( entry );
stereoBench.clear_entry_buffer();
ht::BitmapUPtr grayL = ht::unique_bitmap( entry->bitmap_left().width(),
entry->bitmap_left().height(),
entry->bitmap_left().bit_depth(),
ht::ColorSpace::Grayscale );
ht::BitmapUPtr grayR = ht::unique_bitmap( entry->bitmap_left().width(),
entry->bitmap_left().height(),
entry->bitmap_left().bit_depth(),
ht::ColorSpace::Grayscale );
std::string filePath = cl::filesystem::create_filespec(
dateStr, std::to_string( entry->get_id() ), io::tiff_file_extensions()[1] );
cl::print_line( filePath );
io::TiffWriter tiffWriter{ filePath };
tiffWriter.write_to_file( entry->bitmap_left(), entry->get_id(),
entry->get_framerate() );
tiffWriter.write_to_file( entry->bitmap_right(), entry->get_id(),
entry->get_framerate() );
vm::rgb_to_grey( entry->bitmap_left(), *grayL );
vm::rgb_to_grey( entry->bitmap_right(), *grayR );
double greyLevelL = vm::mean( *grayL );
double greyLevelR = vm::mean( *grayR );
const double greyLevel = ( greyLevelL + greyLevelR ) / 2;
const int32_t greyLevelDiff = 70 - greyLevel;
const int32_t correctedExposureError =
static_cast<int32_t>(std::round(
pid.compute_correction( static_cast<double>(greyLevelDiff) ) ));
currentExposure += correctedExposureError;
if( currentExposure < static_cast<int32_t>(stereoRigParams.exposureMin) )
{
currentExposure = static_cast<int32_t>(stereoRigParams.exposureMin);
}
else if( currentExposure > static_cast<int32_t>(stereoRigParams.exposureMax) )
{
currentExposure = static_cast<int32_t>(stereoRigParams.exposureMax);
}
stereoBench.set_exposure( static_cast<uint32_t>(currentExposure) );
cv::Mat matL = cv::Mat( size, CV_8UC3 );
cv::Mat matR = cv::Mat( size, CV_8UC3 );
matL.data = entry->bitmap_left().data();
matR.data = entry->bitmap_right().data();
cv::Mat combine( std::max( matL.size().height, matR.size().height ),
matL.size().width + matR.size().width, CV_8UC3 );
cv::Mat left_roi( combine, cv::Rect( 0, 0, matL.size().width, matL.size().height ) );
matL.copyTo( left_roi );
cv::Mat right_roi( combine, cv::Rect( matL.size().width, 0, matR.size().width,
matR.size().height ) );
matR.copyTo( right_roi );
cv::imshow( "images", combine );
pressed = static_cast<int8_t>( cv::waitKey( 1 ) );
}
stereoBench.stop();
}
return res;
}
//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
//----------------------------------------- Main Function ------------------------------------------
//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
int32_t
main( int32_t argc, const char** argv )
{
int32_t ret{ EXIT_SUCCESS };
try
{
ret = EntryPoint().run( argc, argv );
}
catch( const cl::SystemError& e )
{
ht::log_fatal( "System Error: ", e.what(), e.where() );
throw;
}
catch( const cl::BaseException& e )
{
ht::log_fatal( "BaseException caught: ", e.what() );
throw;
}
catch( const std::exception& e )
{
ht::log_fatal( "std::exception caught: ", e.what() );
throw;
}
catch( ... )
{
ht::log_fatal( "Caught an exception of an undetermined type" );
throw;
}
return ret;
}
<|endoftext|>
|
<commit_before>#include "EventAction.hh"
#include "HistoManager.hh"
#include "G4RunManager.hh"
#include "G4Event.hh"
#include "G4SDManager.hh"
#include "G4HCofThisEvent.hh"
#include "G4UnitsTable.hh"
#include "Digitizer.hh"
#include "G4DigiManager.hh"
#include "Randomize.hh"
#include <iomanip>
#include "G4VUserPrimaryGeneratorAction.hh"
EventAction::EventAction() :
G4UserEventAction(), fSensorEdepHCID(-1), fSensorTrackLengthHCID(-1), fSensorTrackAngleInHCID(-1), fSensorTrackAngleOutHCID(-1), fTriggerHCID(-1), fShieldInHCID(-1), fShieldOutHCID(-1), fPixelDetectorHCID(-1)
{
G4DigiManager::GetDMpointer()->AddNewModule(new Digitizer("PixelDigitizer"));
}
EventAction::~EventAction()
{
}
G4THitsMap<G4double>* EventAction::GetHitsCollection(G4int hcID, const G4Event* event) const
{
G4THitsMap<G4double>* hitsCollection = static_cast<G4THitsMap<G4double>*>(event->GetHCofThisEvent()->GetHC(hcID));
if (!hitsCollection)
G4Exception("EventAction::GetHitsCollection()", "Cannot access hits collection", FatalException, "");
return hitsCollection;
}
DetHitsMap* EventAction::GetPixelHitsMap(G4int hcID, const G4Event* event) const
{
DetHitsMap* hitsCollection = static_cast<DetHitsMap*>(event->GetHCofThisEvent()->GetHC(hcID));
if (!hitsCollection)
G4Exception("EventAction::GetHitsCollection()", "Cannot access pixel hits Collection", FatalException, "");
return hitsCollection;
}
G4double EventAction::GetSum(G4THitsMap<G4double>* hitsMap) const
{
G4double sumValue = 0;
for (std::map<G4int, G4double*>::iterator it = hitsMap->GetMap()->begin(); it != hitsMap->GetMap()->end(); ++it)
sumValue += *(it->second);
return sumValue;
}
void EventAction::PrintEventStatistics(G4double edep, G4double trackLength) const
{
// Print event statistics
G4cout << " Total energy in sensor: " << std::setw(7) << G4BestUnit(edep, "Energy") << " Total track length in sensor: " << G4BestUnit(trackLength, "Length") << G4endl;
}
void EventAction::BeginOfEventAction(const G4Event* /*event*/)
{
}
void EventAction::EndOfEventAction(const G4Event* event)
{
// Get hit collections IDs
if (fSensorEdepHCID == -1) {
fSensorEdepHCID = G4SDManager::GetSDMpointer()->GetCollectionID("Detector/EnergyDeposit");
fSensorTrackLengthHCID = G4SDManager::GetSDMpointer()->GetCollectionID("Detector/TrackLength");
fSensorTrackAngleInHCID = G4SDManager::GetSDMpointer()->GetCollectionID("Detector/TrackAngleIn");
fSensorTrackAngleOutHCID = G4SDManager::GetSDMpointer()->GetCollectionID("Detector/TrackAngleOut");
fTriggerHCID = G4SDManager::GetSDMpointer()->GetCollectionID("Trigger/TriggerMechanism");
fShieldInHCID = G4SDManager::GetSDMpointer()->GetCollectionID("SourceShield/MeasureEnergyIn");
fShieldOutHCID = G4SDManager::GetSDMpointer()->GetCollectionID("SourceShield/MeasureEnergyOut");
fPixelDetectorHCID = G4SDManager::GetSDMpointer()->GetCollectionID("PixelDetektor/PixelHitCollection");
}
// get analysis manager
G4AnalysisManager* analysisManager = G4AnalysisManager::Instance();
G4double edep = 0.;
G4double trackLength = 0.;
if (fSensorEdepHCID != -1) {
G4THitsMap<G4double>* hcEloss = GetHitsCollection(fSensorEdepHCID, event);
edep = GetSum(hcEloss);
analysisManager->FillH1(7, edep);
}
if (fSensorTrackLengthHCID != -1) {
G4THitsMap<G4double>* hcTLength = GetHitsCollection(fSensorTrackLengthHCID, event);
trackLength = GetSum(hcTLength);
analysisManager->FillH1(8, trackLength);
}
if (trackLength > 0. && fSensorEdepHCID != -1 && fSensorTrackLengthHCID != -1) {
analysisManager->FillH1(12, edep / trackLength);
}
if (fSensorTrackAngleInHCID != -1) {
G4THitsMap<G4double>* hcInAngle = GetHitsCollection(fSensorTrackAngleInHCID, event);
for (std::map<G4int, G4double*>::iterator it = hcInAngle->GetMap()->begin(); it != hcInAngle->GetMap()->end(); ++it)
analysisManager->FillH1(9, *(it->second));
}
if (fSensorTrackAngleOutHCID != -1) {
G4THitsMap<G4double>* hcOutAngle = GetHitsCollection(fSensorTrackAngleOutHCID, event);
for (std::map<G4int, G4double*>::iterator it = hcOutAngle->GetMap()->begin(); it != hcOutAngle->GetMap()->end(); ++it) {
G4double theta = *(it->second);
G4double dteta = analysisManager->GetH1Width(4);
G4double unit = analysisManager->GetH1Unit(4);
G4double weight = (unit * unit) / (CLHEP::twopi * std::sin(theta) * dteta);
analysisManager->FillH1(10, theta, weight);
}
}
if (fTriggerHCID != -1) {
G4THitsMap<G4double>* hcTrigger = GetHitsCollection(fTriggerHCID, event);
if (hcTrigger->GetSize() > 0) // there is at least one hit in the trigger volume
analysisManager->FillH1(11, edep);
}
if (fShieldInHCID != -1) {
G4THitsMap<G4double>* hcInEnergy = GetHitsCollection(fShieldInHCID, event);
for (std::map<G4int, G4double*>::iterator it = hcInEnergy->GetMap()->begin(); it != hcInEnergy->GetMap()->end(); ++it)
analysisManager->FillH1(5, *(it->second));
}
if (fShieldOutHCID != -1) {
G4THitsMap<G4double>* hcOutEnergy = GetHitsCollection(fShieldOutHCID, event);
for (std::map<G4int, G4double*>::iterator it = hcOutEnergy->GetMap()->begin(); it != hcOutEnergy->GetMap()->end(); ++it)
analysisManager->FillH1(6, *(it->second));
}
G4int eventID = event->GetEventID();
if (fPixelDetectorHCID != -1) {
DetHitsMap* pixelhitmap = GetPixelHitsMap(fPixelDetectorHCID, event);
// fill ntuple
for (std::map<G4int, DetHit*>::iterator it = pixelhitmap->GetMap()->begin(); it != pixelhitmap->GetMap()->end(); ++it) {
if (it->second->GetVolumeIdX() == -1) // speed up, do not loop empty DetHits
break;
analysisManager->FillNtupleIColumn(0, 0, eventID);
analysisManager->FillNtupleIColumn(0, 1, it->second->GetVolumeIdX());
analysisManager->FillNtupleIColumn(0, 2, it->second->GetVolumeIdY());
analysisManager->FillNtupleDColumn(0, 3, it->second->GetEdep());
analysisManager->FillNtupleDColumn(0, 4, it->second->GetTrackLength());
analysisManager->AddNtupleRow(0);
}
}
Digitizer* pixelDigitizer = (Digitizer*) G4DigiManager::GetDMpointer()->FindDigitizerModule("PixelDigitizer");
if (pixelDigitizer) {
pixelDigitizer->Digitize();
G4int fPixelDCID = G4DigiManager::GetDMpointer()->GetDigiCollectionID("PixelDigitizer/PixelDigitsCollection");
if (fPixelDCID != -1) {
if (G4DigiManager::GetDMpointer()->GetDigiCollection(fPixelDCID) != 0) {
PixelDigitsCollection* digitsCollection = static_cast<PixelDigitsCollection*>(event->GetDCofThisEvent()->GetDC(fPixelDCID));
for (G4int iDigits = 0; iDigits < digitsCollection->entries(); ++iDigits) {
analysisManager->FillNtupleIColumn(1, 0, eventID);
analysisManager->FillNtupleIColumn(1, 1, (*digitsCollection)[iDigits]->GetColumn());
analysisManager->FillNtupleIColumn(1, 2, (*digitsCollection)[iDigits]->GetRow());
analysisManager->FillNtupleIColumn(1, 3, G4int((*digitsCollection)[iDigits]->GetCharge()));
analysisManager->AddNtupleRow(1);
}
}
else
G4Exception("EventAction::EndOfEventAction", "Cannot access pixel digits", FatalException, "");
}
else
G4Exception("EventAction::EndOfEventAction", "Cannot access pixel digits", FatalException, "");
}
else
G4Exception("EventAction::EndOfEventAction", "Cannot find digitization module.", JustWarning, "");
//print per event (modulo n)
G4int printModulo = G4RunManager::GetRunManager()->GetPrintProgress();
if ((printModulo > 0) && (eventID % printModulo == 0)) {
G4cout << "---- End of event: " << eventID << " ----" << G4endl;
PrintEventStatistics(edep, trackLength);
}
// G4cout << "------- Event ID " << event->GetEventID() << G4endl;
// G4cout << " ----- Primary Particle " << G4endl;
// event->GetPrimaryVertex()->GetPrimary()-> Print();
// G4cout << " ----- Tracks " << event->GetTrajectoryContainer()->size() << G4endl;
// for(size_t i = 0; i < event->GetTrajectoryContainer()->size(); ++i){
//// G4TrajectoryContainer* container = event->GetTrajectoryContainer();
// G4VTrajectory* trajectory = (*event->GetTrajectoryContainer())[i];
// G4cout << "------- Track "<<i<<" ID " << trajectory->GetTrackID() << G4endl;
// G4cout << "------- Track "<<i<<" parent ID " << trajectory->GetParentID() << G4endl;
// G4cout << "------- Track "<<i<<" particle name " << trajectory->GetParticleName() << G4endl;
// }
}
<commit_msg>MAINT: comments<commit_after>#include "EventAction.hh"
#include "HistoManager.hh"
#include "G4RunManager.hh"
#include "G4Event.hh"
#include "G4SDManager.hh"
#include "G4HCofThisEvent.hh"
#include "G4UnitsTable.hh"
#include "Digitizer.hh"
#include "G4DigiManager.hh"
#include "Randomize.hh"
#include <iomanip>
#include "G4VUserPrimaryGeneratorAction.hh"
EventAction::EventAction() :
G4UserEventAction(), fSensorEdepHCID(-1), fSensorTrackLengthHCID(-1), fSensorTrackAngleInHCID(-1), fSensorTrackAngleOutHCID(-1), fTriggerHCID(-1), fShieldInHCID(-1), fShieldOutHCID(-1), fPixelDetectorHCID(-1)
{
G4DigiManager::GetDMpointer()->AddNewModule(new Digitizer("PixelDigitizer"));
}
EventAction::~EventAction()
{
}
G4THitsMap<G4double>* EventAction::GetHitsCollection(G4int hcID, const G4Event* event) const
{
G4THitsMap<G4double>* hitsCollection = static_cast<G4THitsMap<G4double>*>(event->GetHCofThisEvent()->GetHC(hcID));
if (!hitsCollection)
G4Exception("EventAction::GetHitsCollection()", "Cannot access hits collection", FatalException, "");
return hitsCollection;
}
DetHitsMap* EventAction::GetPixelHitsMap(G4int hcID, const G4Event* event) const
{
DetHitsMap* hitsCollection = static_cast<DetHitsMap*>(event->GetHCofThisEvent()->GetHC(hcID));
if (!hitsCollection)
G4Exception("EventAction::GetHitsCollection()", "Cannot access pixel hits Collection", FatalException, "");
return hitsCollection;
}
G4double EventAction::GetSum(G4THitsMap<G4double>* hitsMap) const
{
G4double sumValue = 0;
for (std::map<G4int, G4double*>::iterator it = hitsMap->GetMap()->begin(); it != hitsMap->GetMap()->end(); ++it)
sumValue += *(it->second);
return sumValue;
}
void EventAction::PrintEventStatistics(G4double edep, G4double trackLength) const
{
// Print event statistics
G4cout << " Total energy in sensor: " << std::setw(7) << G4BestUnit(edep, "Energy") << " Total track length in sensor: " << G4BestUnit(trackLength, "Length") << G4endl;
}
void EventAction::BeginOfEventAction(const G4Event* /*event*/)
{
}
void EventAction::EndOfEventAction(const G4Event* event)
{
// Get hit collections IDs
if (fSensorEdepHCID == -1) {
fSensorEdepHCID = G4SDManager::GetSDMpointer()->GetCollectionID("Detector/EnergyDeposit");
fSensorTrackLengthHCID = G4SDManager::GetSDMpointer()->GetCollectionID("Detector/TrackLength");
fSensorTrackAngleInHCID = G4SDManager::GetSDMpointer()->GetCollectionID("Detector/TrackAngleIn");
fSensorTrackAngleOutHCID = G4SDManager::GetSDMpointer()->GetCollectionID("Detector/TrackAngleOut");
fTriggerHCID = G4SDManager::GetSDMpointer()->GetCollectionID("Trigger/TriggerMechanism");
fShieldInHCID = G4SDManager::GetSDMpointer()->GetCollectionID("SourceShield/MeasureEnergyIn");
fShieldOutHCID = G4SDManager::GetSDMpointer()->GetCollectionID("SourceShield/MeasureEnergyOut");
fPixelDetectorHCID = G4SDManager::GetSDMpointer()->GetCollectionID("PixelDetektor/PixelHitCollection");
}
// get analysis manager
G4AnalysisManager* analysisManager = G4AnalysisManager::Instance();
G4double edep = 0.;
G4double trackLength = 0.;
if (fSensorEdepHCID != -1) {
G4THitsMap<G4double>* hcEloss = GetHitsCollection(fSensorEdepHCID, event);
edep = GetSum(hcEloss);
analysisManager->FillH1(7, edep);
}
if (fSensorTrackLengthHCID != -1) {
G4THitsMap<G4double>* hcTLength = GetHitsCollection(fSensorTrackLengthHCID, event);
trackLength = GetSum(hcTLength);
analysisManager->FillH1(8, trackLength);
}
if (trackLength > 0. && fSensorEdepHCID != -1 && fSensorTrackLengthHCID != -1) {
analysisManager->FillH1(12, edep / trackLength);
}
if (fSensorTrackAngleInHCID != -1) {
G4THitsMap<G4double>* hcInAngle = GetHitsCollection(fSensorTrackAngleInHCID, event);
for (std::map<G4int, G4double*>::iterator it = hcInAngle->GetMap()->begin(); it != hcInAngle->GetMap()->end(); ++it)
analysisManager->FillH1(9, *(it->second));
}
if (fSensorTrackAngleOutHCID != -1) {
G4THitsMap<G4double>* hcOutAngle = GetHitsCollection(fSensorTrackAngleOutHCID, event);
for (std::map<G4int, G4double*>::iterator it = hcOutAngle->GetMap()->begin(); it != hcOutAngle->GetMap()->end(); ++it) {
G4double theta = *(it->second);
G4double dteta = analysisManager->GetH1Width(4);
G4double unit = analysisManager->GetH1Unit(4);
G4double weight = (unit * unit) / (CLHEP::twopi * std::sin(theta) * dteta);
analysisManager->FillH1(10, theta, weight);
}
}
if (fTriggerHCID != -1) {
G4THitsMap<G4double>* hcTrigger = GetHitsCollection(fTriggerHCID, event);
if (hcTrigger->GetSize() > 0) // there is at least one hit in the trigger volume
analysisManager->FillH1(11, edep);
}
if (fShieldInHCID != -1) {
G4THitsMap<G4double>* hcInEnergy = GetHitsCollection(fShieldInHCID, event);
for (std::map<G4int, G4double*>::iterator it = hcInEnergy->GetMap()->begin(); it != hcInEnergy->GetMap()->end(); ++it)
analysisManager->FillH1(5, *(it->second));
}
if (fShieldOutHCID != -1) {
G4THitsMap<G4double>* hcOutEnergy = GetHitsCollection(fShieldOutHCID, event);
for (std::map<G4int, G4double*>::iterator it = hcOutEnergy->GetMap()->begin(); it != hcOutEnergy->GetMap()->end(); ++it)
analysisManager->FillH1(6, *(it->second));
}
G4int eventID = event->GetEventID();
// Fill detector hits array (not digitized data)
if (fPixelDetectorHCID != -1) {
DetHitsMap* pixelhitmap = GetPixelHitsMap(fPixelDetectorHCID, event);
// fill ntuple
for (std::map<G4int, DetHit*>::iterator it = pixelhitmap->GetMap()->begin(); it != pixelhitmap->GetMap()->end(); ++it) {
if (it->second->GetVolumeIdX() == -1) // speed up, do not loop empty DetHits
break;
analysisManager->FillNtupleIColumn(0, 0, eventID);
analysisManager->FillNtupleIColumn(0, 1, it->second->GetVolumeIdX());
analysisManager->FillNtupleIColumn(0, 2, it->second->GetVolumeIdY());
analysisManager->FillNtupleDColumn(0, 3, it->second->GetEdep());
analysisManager->FillNtupleDColumn(0, 4, it->second->GetTrackLength());
analysisManager->AddNtupleRow(0);
// G4cout << " Position in sensor: " << std::setw(7) << G4BestUnit(it->second->GetPosition(), "Length") << G4endl;
}
}
// Fill detector digits array (=pixel hits)
Digitizer* pixelDigitizer = (Digitizer*) G4DigiManager::GetDMpointer()->FindDigitizerModule("PixelDigitizer");
if (pixelDigitizer) {
pixelDigitizer->Digitize();
G4int fPixelDCID = G4DigiManager::GetDMpointer()->GetDigiCollectionID("PixelDigitizer/PixelDigitsCollection");
if (fPixelDCID != -1) {
if (G4DigiManager::GetDMpointer()->GetDigiCollection(fPixelDCID) != 0) {
PixelDigitsCollection* digitsCollection = static_cast<PixelDigitsCollection*>(event->GetDCofThisEvent()->GetDC(fPixelDCID));
for (G4int iDigits = 0; iDigits < digitsCollection->entries(); ++iDigits) {
analysisManager->FillNtupleIColumn(1, 0, eventID);
analysisManager->FillNtupleIColumn(1, 1, (*digitsCollection)[iDigits]->GetColumn());
analysisManager->FillNtupleIColumn(1, 2, (*digitsCollection)[iDigits]->GetRow());
analysisManager->FillNtupleIColumn(1, 3, G4int((*digitsCollection)[iDigits]->GetCharge())); // convert charge to int value; is multiple of [e]
analysisManager->AddNtupleRow(1);
}
}
else
G4Exception("EventAction::EndOfEventAction", "Cannot access pixel digits", FatalException, "");
}
else
G4Exception("EventAction::EndOfEventAction", "Cannot access pixel digits", FatalException, "");
}
else
G4Exception("EventAction::EndOfEventAction", "Cannot find digitization module.", JustWarning, "");
//print per event (modulo n)
G4int printModulo = G4RunManager::GetRunManager()->GetPrintProgress();
if ((printModulo > 0) && (eventID % printModulo == 0)) {
G4cout << "---- End of event: " << eventID << " ----" << G4endl;
PrintEventStatistics(edep, trackLength);
}
// G4cout << "------- Event ID " << event->GetEventID() << G4endl;
// G4cout << " ----- Primary Particle " << G4endl;
// event->GetPrimaryVertex()->GetPrimary()-> Print();
// G4cout << " ----- Tracks " << event->GetTrajectoryContainer()->size() << G4endl;
// for(size_t i = 0; i < event->GetTrajectoryContainer()->size(); ++i){
//// G4TrajectoryContainer* container = event->GetTrajectoryContainer();
// G4VTrajectory* trajectory = (*event->GetTrajectoryContainer())[i];
// G4cout << "------- Track "<<i<<" ID " << trajectory->GetTrackID() << G4endl;
// G4cout << "------- Track "<<i<<" parent ID " << trajectory->GetParentID() << G4endl;
// G4cout << "------- Track "<<i<<" particle name " << trajectory->GetParticleName() << G4endl;
// }
}
<|endoftext|>
|
<commit_before>/*!
@file
@author Albert Semenov
@date 08/2008
@module
*/
#include "precompiled.h"
#include "BaseManager.h"
#include <MyGUI_OgrePlatform.h>
#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
# include <windows.h>
#endif
namespace base
{
#if MYGUI_PLATFORM == MYGUI_PLATFORM_APPLE
#include <CoreFoundation/CoreFoundation.h>
// This function will locate the path to our application on OS X,
// unlike windows you can not rely on the curent working directory
// for locating your configuration files and resources.
std::string macBundlePath()
{
char path[1024];
CFBundleRef mainBundle = CFBundleGetMainBundle(); assert(mainBundle);
CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle); assert(mainBundleURL);
CFStringRef cfStringRef = CFURLCopyFileSystemPath( mainBundleURL, kCFURLPOSIXPathStyle); assert(cfStringRef);
CFStringGetCString(cfStringRef, path, 1024, kCFStringEncodingASCII);
CFRelease(mainBundleURL);
CFRelease(cfStringRef);
return std::string(path);
}
#endif
BaseManager::BaseManager() :
mGUI(nullptr),
mPlatform(nullptr),
mInfo(nullptr),
mFocusInfo(nullptr),
mRoot(nullptr),
mCamera(nullptr),
mSceneManager(nullptr),
mWindow(nullptr),
mExit(false),
mPluginCfgName("plugins.cfg"),
mResourceXMLName("resources.xml"),
mResourceFileName("core.xml"),
mNode(nullptr)
{
#if MYGUI_PLATFORM == MYGUI_PLATFORM_APPLE
mResourcePath = macBundlePath() + "/Contents/Resources/";
#else
mResourcePath = "";
#endif
}
BaseManager::~BaseManager()
{
}
bool BaseManager::create()
{
Ogre::String pluginsPath;
#ifndef OGRE_STATIC_LIB
pluginsPath = mResourcePath + mPluginCfgName;
#endif
mRoot = new Ogre::Root(pluginsPath, mResourcePath + "ogre.cfg", mResourcePath + "Ogre.log");
setupResources();
//
if (!mRoot->restoreConfig())
{
// ,
if (!mRoot->showConfigDialog()) return false;
}
mWindow = mRoot->initialise(true);
#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
//
size_t hWnd = 0;
mWindow->getCustomAttribute("WINDOW", &hWnd);
//
char buf[MAX_PATH];
::GetModuleFileNameA(0, (LPCH)&buf, MAX_PATH);
//
HINSTANCE instance = ::GetModuleHandleA(buf);
//
HICON hIcon = ::LoadIcon(instance, MAKEINTRESOURCE(1001));
if (hIcon)
{
::SendMessageA((HWND)hWnd, WM_SETICON, 1, (LPARAM)hIcon);
::SendMessageA((HWND)hWnd, WM_SETICON, 0, (LPARAM)hIcon);
}
#endif
mSceneManager = mRoot->createSceneManager(Ogre::ST_GENERIC, "BaseSceneManager");
mCamera = mSceneManager->createCamera("BaseCamera");
mCamera->setNearClipDistance(5);
mCamera->setPosition(400, 400, 400);
mCamera->lookAt(0, 150, 0);
// Create one viewport, entire window
Ogre::Viewport* vp = mWindow->addViewport(mCamera);
// Alter the camera aspect ratio to match the viewport
mCamera->setAspectRatio((float)vp->getActualWidth() / (float)vp->getActualHeight());
// Set default mipmap level (NB some APIs ignore this)
Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
mSceneManager->setAmbientLight(Ogre::ColourValue::White);
Ogre::Light* l = mSceneManager->createLight("MainLight");
l->setType(Ogre::Light::LT_DIRECTIONAL);
Ogre::Vector3 vec(-0.3, -0.3, -0.3);
vec.normalise();
l->setDirection(vec);
// Load resources
Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
mRoot->addFrameListener(this);
Ogre::WindowEventUtilities::addWindowEventListener(mWindow, this);
size_t handle = 0;
mWindow->getCustomAttribute("WINDOW", &handle);
createInput(handle);
windowResized(mWindow);
createGui();
createPointerManager(handle);
createScene();
return true;
}
void BaseManager::run()
{
//
mRoot->getRenderSystem()->_initRenderTargets();
//
while (true)
{
Ogre::WindowEventUtilities::messagePump();
if (mWindow->isActive() == false)
mWindow->setActive(true);
if (!mRoot->renderOneFrame())
break;
// ,
#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
::Sleep(0);
#endif
};
}
void BaseManager::destroy()
{
destroyScene();
destroyPointerManager();
destroyGui();
//
if (mSceneManager)
{
mSceneManager->clearScene();
mSceneManager->destroyAllCameras();
mSceneManager = nullptr;
}
destroyInput();
if (mWindow)
{
mWindow->destroy();
mWindow = nullptr;
}
if (mRoot)
{
Ogre::RenderWindow* window = mRoot->getAutoCreatedWindow();
if (window)
window->removeAllViewports();
delete mRoot;
mRoot = nullptr;
}
}
void BaseManager::createGui()
{
mPlatform = new MyGUI::OgrePlatform();
mPlatform->initialise(mWindow, mSceneManager);
mGUI = new MyGUI::Gui();
mGUI->initialise(mResourceFileName);
mInfo = new diagnostic::StatisticInfo();
}
void BaseManager::destroyGui()
{
if (mGUI)
{
if (mInfo)
{
delete mInfo;
mInfo = nullptr;
}
if (mFocusInfo)
{
delete mFocusInfo;
mFocusInfo = nullptr;
}
mGUI->shutdown();
delete mGUI;
mGUI = nullptr;
}
if (mPlatform)
{
mPlatform->shutdown();
delete mPlatform;
mPlatform = nullptr;
}
}
void BaseManager::setupResources()
{
MyGUI::xml::Document doc;
if (!doc.open(mResourceXMLName))
doc.getLastError();
MyGUI::xml::ElementPtr root = doc.getRoot();
if (root == nullptr || root->getName() != "Paths")
return;
MyGUI::xml::ElementEnumerator node = root->getElementEnumerator();
while (node.next())
{
if (node->getName() == "Path")
{
bool rootAttr = false;
if (node->findAttribute("root") != "")
{
rootAttr = MyGUI::utility::parseBool(node->findAttribute("root"));
if (rootAttr) mRootMedia = node->getContent();
}
addResourceLocation(node->getContent());
}
}
}
bool BaseManager::frameStarted(const Ogre::FrameEvent& evt)
{
if (mExit)
return false;
if (!mGUI)
return true;
captureInput();
if (mInfo)
{
static float time = 0;
time += evt.timeSinceLastFrame;
if (time > 1)
{
time -= 1;
try
{
const Ogre::RenderTarget::FrameStats& stats = mWindow->getStatistics();
mInfo->change("FPS", (int)stats.lastFPS);
mInfo->change("triangle", stats.triangleCount);
mInfo->change("batch", stats.batchCount);
//mInfo->change("batch gui", MyGUI::RenderManager::getInstance().getBatch());
mInfo->update();
}
catch (...)
{
}
}
}
//
if (mNode)
{
mNode->yaw(Ogre::Radian(Ogre::Degree(evt.timeSinceLastFrame * 10)));
}
return true;
}
bool BaseManager::frameEnded(const Ogre::FrameEvent& evt)
{
return true;
}
void BaseManager::windowResized(Ogre::RenderWindow* _rw)
{
int width = (int)_rw->getWidth();
int height = (int)_rw->getHeight();
mCamera->setAspectRatio((float)width / (float)height);
setInputViewSize(width, height);
}
void BaseManager::windowClosed(Ogre::RenderWindow* _rw)
{
mExit = true;
destroyInput();
}
void BaseManager::setWindowCaption(const std::string& _text)
{
#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
size_t handle = 0;
mWindow->getCustomAttribute("WINDOW", &handle);
::SetWindowTextA((HWND)handle, _text.c_str());
#endif
}
void BaseManager::prepare(int argc, char **argv)
{
}
void BaseManager::addResourceLocation(const std::string& _name, const std::string& _group, const std::string& _type, bool _recursive)
{
#if MYGUI_PLATFORM == MYGUI_PLATFORM_APPLE
// OS X does not set the working directory relative to the app, In order to make things portable on OS X we need to provide the loading with it's own bundle path location
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(Ogre::String(macBundlePath() + "/" + _name), _type, _group, _recursive);
#else
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(_name, _type, _group, _recursive);
#endif
}
void BaseManager::addResourceLocation(const std::string & _name, bool _recursive)
{
addResourceLocation(_name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, "FileSystem", false);
}
void BaseManager::createDefaultScene()
{
try
{
Ogre::Entity* entity = mSceneManager->createEntity("Mikki.mesh", "Mikki.mesh");
mNode = mSceneManager->getRootSceneNode()->createChildSceneNode();
mNode->attachObject(entity);
}
catch (Ogre::FileNotFoundException&)
{
return;
}
try
{
Ogre::MeshManager::getSingleton().createPlane(
"FloorPlane", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
Ogre::Plane(Ogre::Vector3::UNIT_Y, 0), 1000, 1000, 1, 1, true, 1, 1, 1, Ogre::Vector3::UNIT_Z);
Ogre::Entity* entity = getSceneManager()->createEntity("FloorPlane", "FloorPlane");
entity->setMaterialName("Ground");
mNode->attachObject(entity);
}
catch (Ogre::FileNotFoundException&)
{
return;
}
}
void BaseManager::injectMouseMove(int _absx, int _absy, int _absz)
{
if (!mGUI)
return;
mGUI->injectMouseMove(_absx, _absy, _absz);
}
void BaseManager::injectMousePress(int _absx, int _absy, MyGUI::MouseButton _id)
{
if (!mGUI)
return;
mGUI->injectMousePress(_absx, _absy, _id);
}
void BaseManager::injectMouseRelease(int _absx, int _absy, MyGUI::MouseButton _id)
{
if (!mGUI)
return;
mGUI->injectMouseRelease(_absx, _absy, _id);
}
void BaseManager::injectKeyPress(MyGUI::KeyCode _key, MyGUI::Char _text)
{
if (!mGUI)
return;
if (_key == MyGUI::KeyCode::Escape)
{
mExit = true;
return;
}
else if (_key == MyGUI::KeyCode::SysRq)
{
std::ifstream stream;
std::string file;
do
{
stream.close();
static size_t num = 0;
const size_t max_shot = 100;
if (num == max_shot)
{
MYGUI_LOG(Info, "The limit of screenshots is exceeded : " << max_shot);
return;
}
file = MyGUI::utility::toString("screenshot_", ++num, ".png");
stream.open(file.c_str());
}
while (stream.is_open());
mWindow->writeContentsToFile(file);
return;
}
else if (_key == MyGUI::KeyCode::F12)
{
if (mFocusInfo == nullptr)
mFocusInfo = new diagnostic::InputFocusInfo();
bool visible = mFocusInfo->getFocusVisible();
mFocusInfo->setFocusVisible(!visible);
}
else if (_key == MyGUI::KeyCode::F11)
{
MyGUI::LayerManager::getInstance().dumpStatisticToLog();
}
mGUI->injectKeyPress(_key, _text);
}
void BaseManager::injectKeyRelease(MyGUI::KeyCode _key)
{
if (!mGUI)
return;
mGUI->injectKeyRelease(_key);
}
} // namespace base
<commit_msg>fix crush in full screen mode<commit_after>/*!
@file
@author Albert Semenov
@date 08/2008
@module
*/
#include "precompiled.h"
#include "BaseManager.h"
#include <MyGUI_OgrePlatform.h>
#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
# include <windows.h>
#endif
namespace base
{
#if MYGUI_PLATFORM == MYGUI_PLATFORM_APPLE
#include <CoreFoundation/CoreFoundation.h>
// This function will locate the path to our application on OS X,
// unlike windows you can not rely on the curent working directory
// for locating your configuration files and resources.
std::string macBundlePath()
{
char path[1024];
CFBundleRef mainBundle = CFBundleGetMainBundle(); assert(mainBundle);
CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle); assert(mainBundleURL);
CFStringRef cfStringRef = CFURLCopyFileSystemPath( mainBundleURL, kCFURLPOSIXPathStyle); assert(cfStringRef);
CFStringGetCString(cfStringRef, path, 1024, kCFStringEncodingASCII);
CFRelease(mainBundleURL);
CFRelease(cfStringRef);
return std::string(path);
}
#endif
BaseManager::BaseManager() :
mGUI(nullptr),
mPlatform(nullptr),
mInfo(nullptr),
mFocusInfo(nullptr),
mRoot(nullptr),
mCamera(nullptr),
mSceneManager(nullptr),
mWindow(nullptr),
mExit(false),
mPluginCfgName("plugins.cfg"),
mResourceXMLName("resources.xml"),
mResourceFileName("core.xml"),
mNode(nullptr)
{
#if MYGUI_PLATFORM == MYGUI_PLATFORM_APPLE
mResourcePath = macBundlePath() + "/Contents/Resources/";
#else
mResourcePath = "";
#endif
}
BaseManager::~BaseManager()
{
}
bool BaseManager::create()
{
Ogre::String pluginsPath;
#ifndef OGRE_STATIC_LIB
pluginsPath = mResourcePath + mPluginCfgName;
#endif
mRoot = new Ogre::Root(pluginsPath, mResourcePath + "ogre.cfg", mResourcePath + "Ogre.log");
setupResources();
//
if (!mRoot->restoreConfig())
{
// ,
if (!mRoot->showConfigDialog()) return false;
}
mWindow = mRoot->initialise(true);
#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
//
size_t hWnd = 0;
mWindow->getCustomAttribute("WINDOW", &hWnd);
//
char buf[MAX_PATH];
::GetModuleFileNameA(0, (LPCH)&buf, MAX_PATH);
//
HINSTANCE instance = ::GetModuleHandleA(buf);
//
HICON hIcon = ::LoadIcon(instance, MAKEINTRESOURCE(1001));
if (hIcon)
{
::SendMessageA((HWND)hWnd, WM_SETICON, 1, (LPARAM)hIcon);
::SendMessageA((HWND)hWnd, WM_SETICON, 0, (LPARAM)hIcon);
}
#endif
mSceneManager = mRoot->createSceneManager(Ogre::ST_GENERIC, "BaseSceneManager");
mCamera = mSceneManager->createCamera("BaseCamera");
mCamera->setNearClipDistance(5);
mCamera->setPosition(400, 400, 400);
mCamera->lookAt(0, 150, 0);
// Create one viewport, entire window
Ogre::Viewport* vp = mWindow->addViewport(mCamera);
// Alter the camera aspect ratio to match the viewport
mCamera->setAspectRatio((float)vp->getActualWidth() / (float)vp->getActualHeight());
// Set default mipmap level (NB some APIs ignore this)
Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
mSceneManager->setAmbientLight(Ogre::ColourValue::White);
Ogre::Light* l = mSceneManager->createLight("MainLight");
l->setType(Ogre::Light::LT_DIRECTIONAL);
Ogre::Vector3 vec(-0.3, -0.3, -0.3);
vec.normalise();
l->setDirection(vec);
// Load resources
Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
mRoot->addFrameListener(this);
Ogre::WindowEventUtilities::addWindowEventListener(mWindow, this);
size_t handle = 0;
mWindow->getCustomAttribute("WINDOW", &handle);
createInput(handle);
windowResized(mWindow);
createGui();
createPointerManager(handle);
createScene();
return true;
}
void BaseManager::run()
{
//
mRoot->getRenderSystem()->_initRenderTargets();
//
while (true)
{
Ogre::WindowEventUtilities::messagePump();
if (mWindow->isActive() == false)
mWindow->setActive(true);
if (!mRoot->renderOneFrame())
break;
// ,
#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
::Sleep(0);
#endif
};
}
void BaseManager::destroy()
{
destroyScene();
destroyPointerManager();
destroyGui();
//
if (mSceneManager)
{
mSceneManager->clearScene();
mSceneManager->destroyAllCameras();
mSceneManager = nullptr;
mCamera = nullptr;
}
destroyInput();
if (mWindow)
{
mWindow->destroy();
mWindow = nullptr;
}
if (mRoot)
{
Ogre::RenderWindow* window = mRoot->getAutoCreatedWindow();
if (window)
window->removeAllViewports();
delete mRoot;
mRoot = nullptr;
}
}
void BaseManager::createGui()
{
mPlatform = new MyGUI::OgrePlatform();
mPlatform->initialise(mWindow, mSceneManager);
mGUI = new MyGUI::Gui();
mGUI->initialise(mResourceFileName);
mInfo = new diagnostic::StatisticInfo();
}
void BaseManager::destroyGui()
{
if (mGUI)
{
if (mInfo)
{
delete mInfo;
mInfo = nullptr;
}
if (mFocusInfo)
{
delete mFocusInfo;
mFocusInfo = nullptr;
}
mGUI->shutdown();
delete mGUI;
mGUI = nullptr;
}
if (mPlatform)
{
mPlatform->shutdown();
delete mPlatform;
mPlatform = nullptr;
}
}
void BaseManager::setupResources()
{
MyGUI::xml::Document doc;
if (!doc.open(mResourceXMLName))
doc.getLastError();
MyGUI::xml::ElementPtr root = doc.getRoot();
if (root == nullptr || root->getName() != "Paths")
return;
MyGUI::xml::ElementEnumerator node = root->getElementEnumerator();
while (node.next())
{
if (node->getName() == "Path")
{
bool rootAttr = false;
if (node->findAttribute("root") != "")
{
rootAttr = MyGUI::utility::parseBool(node->findAttribute("root"));
if (rootAttr) mRootMedia = node->getContent();
}
addResourceLocation(node->getContent());
}
}
}
bool BaseManager::frameStarted(const Ogre::FrameEvent& evt)
{
if (mExit)
return false;
if (!mGUI)
return true;
captureInput();
if (mInfo)
{
static float time = 0;
time += evt.timeSinceLastFrame;
if (time > 1)
{
time -= 1;
try
{
const Ogre::RenderTarget::FrameStats& stats = mWindow->getStatistics();
mInfo->change("FPS", (int)stats.lastFPS);
mInfo->change("triangle", stats.triangleCount);
mInfo->change("batch", stats.batchCount);
//mInfo->change("batch gui", MyGUI::RenderManager::getInstance().getBatch());
mInfo->update();
}
catch (...)
{
}
}
}
//
if (mNode)
{
mNode->yaw(Ogre::Radian(Ogre::Degree(evt.timeSinceLastFrame * 10)));
}
return true;
}
bool BaseManager::frameEnded(const Ogre::FrameEvent& evt)
{
return true;
}
void BaseManager::windowResized(Ogre::RenderWindow* _rw)
{
int width = (int)_rw->getWidth();
int height = (int)_rw->getHeight();
//
if (mCamera)
{
mCamera->setAspectRatio((float)width / (float)height);
setInputViewSize(width, height);
}
}
void BaseManager::windowClosed(Ogre::RenderWindow* _rw)
{
mExit = true;
destroyInput();
}
void BaseManager::setWindowCaption(const std::string& _text)
{
#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
size_t handle = 0;
mWindow->getCustomAttribute("WINDOW", &handle);
::SetWindowTextA((HWND)handle, _text.c_str());
#endif
}
void BaseManager::prepare(int argc, char **argv)
{
}
void BaseManager::addResourceLocation(const std::string& _name, const std::string& _group, const std::string& _type, bool _recursive)
{
#if MYGUI_PLATFORM == MYGUI_PLATFORM_APPLE
// OS X does not set the working directory relative to the app, In order to make things portable on OS X we need to provide the loading with it's own bundle path location
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(Ogre::String(macBundlePath() + "/" + _name), _type, _group, _recursive);
#else
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(_name, _type, _group, _recursive);
#endif
}
void BaseManager::addResourceLocation(const std::string & _name, bool _recursive)
{
addResourceLocation(_name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, "FileSystem", false);
}
void BaseManager::createDefaultScene()
{
try
{
Ogre::Entity* entity = mSceneManager->createEntity("Mikki.mesh", "Mikki.mesh");
mNode = mSceneManager->getRootSceneNode()->createChildSceneNode();
mNode->attachObject(entity);
}
catch (Ogre::FileNotFoundException&)
{
return;
}
try
{
Ogre::MeshManager::getSingleton().createPlane(
"FloorPlane", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
Ogre::Plane(Ogre::Vector3::UNIT_Y, 0), 1000, 1000, 1, 1, true, 1, 1, 1, Ogre::Vector3::UNIT_Z);
Ogre::Entity* entity = getSceneManager()->createEntity("FloorPlane", "FloorPlane");
entity->setMaterialName("Ground");
mNode->attachObject(entity);
}
catch (Ogre::FileNotFoundException&)
{
return;
}
}
void BaseManager::injectMouseMove(int _absx, int _absy, int _absz)
{
if (!mGUI)
return;
mGUI->injectMouseMove(_absx, _absy, _absz);
}
void BaseManager::injectMousePress(int _absx, int _absy, MyGUI::MouseButton _id)
{
if (!mGUI)
return;
mGUI->injectMousePress(_absx, _absy, _id);
}
void BaseManager::injectMouseRelease(int _absx, int _absy, MyGUI::MouseButton _id)
{
if (!mGUI)
return;
mGUI->injectMouseRelease(_absx, _absy, _id);
}
void BaseManager::injectKeyPress(MyGUI::KeyCode _key, MyGUI::Char _text)
{
if (!mGUI)
return;
if (_key == MyGUI::KeyCode::Escape)
{
mExit = true;
return;
}
else if (_key == MyGUI::KeyCode::SysRq)
{
std::ifstream stream;
std::string file;
do
{
stream.close();
static size_t num = 0;
const size_t max_shot = 100;
if (num == max_shot)
{
MYGUI_LOG(Info, "The limit of screenshots is exceeded : " << max_shot);
return;
}
file = MyGUI::utility::toString("screenshot_", ++num, ".png");
stream.open(file.c_str());
}
while (stream.is_open());
mWindow->writeContentsToFile(file);
return;
}
else if (_key == MyGUI::KeyCode::F12)
{
if (mFocusInfo == nullptr)
mFocusInfo = new diagnostic::InputFocusInfo();
bool visible = mFocusInfo->getFocusVisible();
mFocusInfo->setFocusVisible(!visible);
}
else if (_key == MyGUI::KeyCode::F11)
{
MyGUI::LayerManager::getInstance().dumpStatisticToLog();
}
mGUI->injectKeyPress(_key, _text);
}
void BaseManager::injectKeyRelease(MyGUI::KeyCode _key)
{
if (!mGUI)
return;
mGUI->injectKeyRelease(_key);
}
} // namespace base
<|endoftext|>
|
<commit_before>// FbTime.hh for FbTk - Fluxbox Toolkit
// Copyright (c) 2012 Mathias Gumz (akira at fluxbox dot org)
//
// 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 FBTK_FBTIME_HH
#define FBTK_FBTIME_HH
#ifdef HAVE_INTTYPES_H
#include <inttypes.h>
#endif // HAVE_INTTYPES_H
namespace FbTk {
// time in micro-seconds
//
// interesting links:
//
// http://www.python.org/dev/peps/pep-0418/#operating-system-time-functions
// http://en.cppreference.com/w/cpp/chrono
namespace FbTime {
const uint64_t IN_MILLISECONDS = 1000L;
const uint64_t IN_SECONDS = 1000L * IN_MILLISECONDS;
const uint64_t IN_MINUTES = 60 * IN_SECONDS;
uint64_t mono(); // point in time, always monotonic
uint64_t system(); // system time, might jump (DST, leap seconds)
// calculates the remaining microseconds from 'now' up to the
// next full 'unit'
inline uint64_t remainingNext(uint64_t now, uint64_t unit) {
return (unit - (now % unit) - 1);
}
} // namespace FbTime
} // namespace FbTk
#endif // FBTK_TIME_HH
<commit_msg>allow a timeout of a full 'unit'<commit_after>// FbTime.hh for FbTk - Fluxbox Toolkit
// Copyright (c) 2012 Mathias Gumz (akira at fluxbox dot org)
//
// 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 FBTK_FBTIME_HH
#define FBTK_FBTIME_HH
#ifdef HAVE_INTTYPES_H
#include <inttypes.h>
#endif // HAVE_INTTYPES_H
namespace FbTk {
// time in micro-seconds
//
// interesting links:
//
// http://www.python.org/dev/peps/pep-0418/#operating-system-time-functions
// http://en.cppreference.com/w/cpp/chrono
namespace FbTime {
const uint64_t IN_MILLISECONDS = 1000L;
const uint64_t IN_SECONDS = 1000L * IN_MILLISECONDS;
const uint64_t IN_MINUTES = 60 * IN_SECONDS;
uint64_t mono(); // point in time, always monotonic
uint64_t system(); // system time, might jump (DST, leap seconds)
// calculates the remaining microseconds from 'now' up to the
// next full 'unit'
inline uint64_t remainingNext(uint64_t now, uint64_t unit) {
return (unit - (now % unit));
}
} // namespace FbTime
} // namespace FbTk
#endif // FBTK_TIME_HH
<|endoftext|>
|
<commit_before>#include "GameWindow.h"
GameWindow::GameWindow(QMainWindow *parent) : QMainWindow(parent), m_fpga(this), m_game()
{
/****General setup****/
this->setWindowTitle("Scorch");
this->setStatusBar(new QStatusBar);
this->setWindowIcon(QIcon(QPixmap(":/resources/icon_big.png")));
setFocus();
setStyleSheet("QMainWindow::separator{ width:0px; height:0px;}");
m_game.getView()->setFocusPolicy(Qt::NoFocus);
/****Central widget****/
GameModeWidget * m_gameModeWidget;
AngleStatusWidget * m_currentAngle;
FirePowerWidget * m_currentPower;
this->setCentralWidget(m_game.getView());
/****Bottom Widget (Information about player)****/
QWidget* bottomWidget = new QWidget;
QDockWidget* informationPanel = new QDockWidget;
informationPanel->setAllowedAreas(Qt::BottomDockWidgetArea);
informationPanel->setFeatures(QDockWidget::NoDockWidgetFeatures);
GameBottomLayout *bottomLayout = new GameBottomLayout;
m_gameModeWidget = new GameModeWidget;
bottomLayout->addWidget(m_gameModeWidget);
//This should be an object with custom paint method to make it interesting
m_currentAngle = new AngleStatusWidget;
m_currentAngle->setAngle(0);
//This will be an object with custom paint method to make it interesting
m_currentPower = new FirePowerWidget;
m_currentPower->setPower(50);
bottomLayout->addStretch();
bottomLayout->addWidget(m_currentAngle);
bottomLayout->setAlignment(m_currentAngle, Qt::AlignRight);
bottomLayout->addWidget(m_currentPower);
bottomWidget->setLayout(bottomLayout);
informationPanel->setWidget(bottomWidget);
this->addDockWidget(Qt::BottomDockWidgetArea, informationPanel);
/****Menus****/
m_menuBar = new QMenuBar;
// File menu
m_menuFichier = new QMenu("Fichier");
m_actionQuit = new QAction("Quitter", this);
m_actionQuit->setShortcut(QKeySequence("Q"));
m_actionNewGame = new QAction("Nouvelle partie", this);
m_actionNewGame->setShortcut(QKeySequence("N"));
m_menuFichier->addAction(m_actionNewGame);
m_menuFichier->addSeparator();
m_menuFichier->addAction(m_actionQuit);
m_menuBar->addMenu(m_menuFichier);
// Game menu
m_menuJeux = new QMenu("Jeux");
m_actionPause = new QAction("Pause", this);
m_actionPause->setShortcut(QKeySequence("P"));
m_actionMuet = new QAction("Muet", this);
m_actionMuet->setShortcut(QKeySequence("M"));
m_menuJeux->addAction(m_actionPause);
m_menuJeux->addSeparator();
m_menuJeux->addAction(m_actionMuet);
m_menuBar->addMenu(m_menuJeux);
//Help menu
m_menuAide = new QMenu("Aide");
m_actionTutoriel = new QAction("Tutoriel", this);
m_actionTutoriel->setShortcut(QKeySequence("F1"));
m_actionVersion = new QAction("Version", this);
m_actionVersion->setShortcut(QKeySequence("F2"));
QAction* actionAboutQt = new QAction(QString(224)+" Propos de Qt", this);
actionAboutQt->setShortcut(QKeySequence("F3"));
m_menuAide->addAction(m_actionTutoriel);
m_menuAide->addSeparator();
m_menuAide->addAction(m_actionVersion);
m_menuAide->addSeparator();
m_menuAide->addAction(actionAboutQt);
m_menuBar->addMenu(m_menuAide);
this->setMenuBar(m_menuBar);
/****Connections****/
// Connect Menu
connect(m_actionQuit, &QAction::triggered, QApplication::instance(), &QApplication::quit);
connect(actionAboutQt, &QAction::triggered, QApplication::instance(), &QApplication::aboutQt);
connect(m_actionPause, &QAction::triggered, this, &GameWindow::pausedTriggered);
connect(m_actionNewGame, SIGNAL(triggered()), this, SLOT(openNewGame()));
connect(m_actionTutoriel, SIGNAL(triggered()), this, SLOT(openTutoriel()));
connect(m_actionVersion, SIGNAL(triggered()), this, SLOT(openVersion()));
// Connect Input
connect(&m_fpga, &FPGAReceiver::fpgaError, this, &GameWindow::displayStatusMessage);
// Connect Game
connect(&m_game, &Game::playerChanged, this, &GameWindow::playerChanged);
connect(&m_game, &Game::angleChanged, this, &GameWindow::angleChanged);
connect(&m_game, &Game::powerChanged, this, &GameWindow::powerChanged);
connect(&m_game, &Game::stateChanged, this, &GameWindow::stateChanged);
connect(&m_game, &Game::newGameGenerated, this, &GameWindow::resetPause);
// Connect Info Widgets
connect(this, &GameWindow::changeAngle, m_currentAngle, &AngleStatusWidget::setAngle);
connect(this, &GameWindow::changePlayer, m_gameModeWidget, &GameModeWidget::setCurrentPlayer);
connect(this, &GameWindow::changePower, m_currentPower, &FirePowerWidget::setPower);
connect(this, &GameWindow::changeState, m_gameModeWidget, &GameModeWidget::setCurrentMode);
/****Music****/
QMediaPlaylist* playlist = new QMediaPlaylist;
playlist->addMedia(QUrl::fromLocalFile(QDir::currentPath() + "/resources/music/Angevin_B.mp3"));
playlist->addMedia(QUrl::fromLocalFile(QDir::currentPath() + "/resources/music/Celtic_Impulse.mp3"));
playlist->addMedia(QUrl::fromLocalFile(QDir::currentPath() + "/resources/music/Pippin_the_Hunchback.mp3"));
playlist->shuffle();
playlist->setPlaybackMode(QMediaPlaylist::Loop);
m_musicPlayer.setPlaylist(playlist);
m_musicPlayer.play();
QTimer::singleShot(1, this, &GameWindow::openMainMenu);
}
GameWindow::~GameWindow()
{
}
void GameWindow::displayStatusMessage(QString message)
{
statusBar()->showMessage(message);
}
void GameWindow::playerChanged(Player p_player)
{
emit changePlayer(p_player);
}
void GameWindow::stateChanged(InputState p_state)
{
emit changeState(p_state);
}
void GameWindow::angleChanged(float p_angle)
{
emit changeAngle(p_angle);
}
void GameWindow::powerChanged(float p_power)
{
emit changePower(p_power);
}
void GameWindow::pausedTriggered()
{
if (m_game.pause()) {
m_game.setPause(false);
m_actionPause->setText("&Pause");
}
else {
m_game.setPause(true);
if(m_game.pause())
m_actionPause->setText("&Jouer");
}
}
void GameWindow::resetPause()
{
m_actionPause->setText("&Pause");
}
void GameWindow::keyPressEvent(QKeyEvent * KeyEvent)
{
//NOTE: Hack to simulate correctly the FPGA input
if (m_game.getInputState() == InputState::Fire && KeyEvent->key() == Qt::Key_Space){
QKeyEvent * key = new QKeyEvent(KeyEvent->type(), Qt::Key_Up, Qt::KeyboardModifier::NoModifier);
m_fpga.handlePressEvent(key);
}
else if (m_game.getInputState() == InputState::Fire && (KeyEvent->key() == Qt::Key_Up || KeyEvent->key() == Qt::Key_Down))
return;
else
m_fpga.handlePressEvent(KeyEvent);
}
void GameWindow::customEvent(QEvent *event)
{
if(event->type() == FPGAEvent::customFPGAEvent) {
FPGAEvent* fpgaEvent = static_cast<FPGAEvent *>(event);
QCoreApplication::postEvent(&m_game, new FPGAEvent(*fpgaEvent));
}
}
void GameWindow::openNewGame()
{
FenetreNewGame fenNewGame;
fenNewGame.exec();
if (fenNewGame.result() == QDialog::Accepted) {
m_game.newGame(fenNewGame.getChosenDifficulty(), 2);
m_game.startPlaying();
}
}
void GameWindow::openTutoriel()
{
FenetreTutoriel fenTutoriel;
fenTutoriel.exec();
}
void GameWindow::openVersion()
{
FenetreVersion fenVersion;
fenVersion.exec();
}
void GameWindow::openMainMenu()
{
FenetreNewGame fenNewGame;
fenNewGame.exec();
if (fenNewGame.result() == QDialog::Accepted) {
m_game.newGame(fenNewGame.getChosenDifficulty(), 2);
m_game.startPlaying();
}
else
this->close();
}
void GameWindow::resizeEvent(QResizeEvent *event)
{
QMainWindow::resizeEvent(event);
m_game.getView()->fitInView(m_game.getView()->sceneRect(), Qt::KeepAspectRatio);
}
void GameWindow::closeEvent(QCloseEvent *event)
{
QMessageBox *quitMessage = new QMessageBox(QMessageBox::Information, "Quitter", "Etes vous sur de vouloir quitter?", QMessageBox::Yes | QMessageBox::No);
quitMessage->setWindowIcon(QIcon(QPixmap(":/resources/icon_big.png")));
quitMessage->setFixedSize(80, 220);
if (QMessageBox::Yes == quitMessage->exec())
event->accept();
else {
event->ignore();
if (m_game.getGameState() == Menu)
QTimer::singleShot(1, this, &GameWindow::openMainMenu);
}
}
<commit_msg>Fix merges revert<commit_after>#include "GameWindow.h"
GameWindow::GameWindow(QMainWindow *parent) : QMainWindow(parent), m_fpga(this, 0), m_game()
{
/****General setup****/
this->setWindowTitle("Scorch");
this->setStatusBar(new QStatusBar);
this->setWindowIcon(QIcon(QPixmap(":/resources/icon_big.png")));
setFocus();
setStyleSheet("QMainWindow::separator{ width:0px; height:0px;}");
m_game.getView()->setFocusPolicy(Qt::NoFocus);
/****Central widget****/
GameModeWidget * m_gameModeWidget;
AngleStatusWidget * m_currentAngle;
FirePowerWidget * m_currentPower;
this->setCentralWidget(m_game.getView());
/****Bottom Widget (Information about player)****/
QWidget* bottomWidget = new QWidget;
QDockWidget* informationPanel = new QDockWidget;
informationPanel->setAllowedAreas(Qt::BottomDockWidgetArea);
informationPanel->setFeatures(QDockWidget::NoDockWidgetFeatures);
GameBottomLayout *bottomLayout = new GameBottomLayout;
m_gameModeWidget = new GameModeWidget;
bottomLayout->addWidget(m_gameModeWidget);
//This should be an object with custom paint method to make it interesting
m_currentAngle = new AngleStatusWidget;
m_currentAngle->setAngle(0);
//This will be an object with custom paint method to make it interesting
m_currentPower = new FirePowerWidget;
m_currentPower->setPower(50);
bottomLayout->addStretch();
bottomLayout->addWidget(m_currentAngle);
bottomLayout->setAlignment(m_currentAngle, Qt::AlignRight);
bottomLayout->addWidget(m_currentPower);
bottomWidget->setLayout(bottomLayout);
informationPanel->setWidget(bottomWidget);
this->addDockWidget(Qt::BottomDockWidgetArea, informationPanel);
/****Menus****/
m_menuBar = new QMenuBar;
// File menu
m_menuFichier = new QMenu("Fichier");
m_actionQuit = new QAction("Quitter", this);
m_actionQuit->setShortcut(QKeySequence("Q"));
m_actionNewGame = new QAction("Nouvelle partie", this);
m_actionNewGame->setShortcut(QKeySequence("N"));
m_menuFichier->addAction(m_actionNewGame);
m_menuFichier->addSeparator();
m_menuFichier->addAction(m_actionQuit);
m_menuBar->addMenu(m_menuFichier);
// Game menu
m_menuJeux = new QMenu("Jeu");
m_actionPause = new QAction("Pause", this);
m_actionPause->setShortcut(QKeySequence("P"));
m_actionMuet = new QAction("Muet", this);
m_actionMuet->setShortcut(QKeySequence("M"));
m_menuJeux->addAction(m_actionPause);
m_menuJeux->addSeparator();
m_menuJeux->addAction(m_actionMuet);
m_menuBar->addMenu(m_menuJeux);
//Help menu
m_menuAide = new QMenu("Aide");
m_actionTutoriel = new QAction("Tutoriel", this);
m_actionTutoriel->setShortcut(QKeySequence("F1"));
m_actionVersion = new QAction("Version", this);
m_actionVersion->setShortcut(QKeySequence("F2"));
QAction* actionAboutQt = new QAction(QString(224)+" Propos de Qt", this);
actionAboutQt->setShortcut(QKeySequence("F3"));
m_menuAide->addAction(m_actionTutoriel);
m_menuAide->addSeparator();
m_menuAide->addAction(m_actionVersion);
m_menuAide->addSeparator();
m_menuAide->addAction(actionAboutQt);
m_menuBar->addMenu(m_menuAide);
this->setMenuBar(m_menuBar);
/****Connections****/
// Connect Menu
connect(m_actionQuit, &QAction::triggered, this, &QMainWindow::close);
connect(actionAboutQt, &QAction::triggered, QApplication::instance(), &QApplication::aboutQt);
connect(m_actionPause, &QAction::triggered, this, &GameWindow::pausedTriggered);
connect(m_actionMuet, &QAction::triggered, this, &GameWindow::muteTriggered);
connect(m_actionNewGame, SIGNAL(triggered()), this, SLOT(openNewGame()));
connect(m_actionTutoriel, SIGNAL(triggered()), this, SLOT(openTutoriel()));
connect(m_actionVersion, SIGNAL(triggered()), this, SLOT(openVersion()));
// Connect Input
connect(&m_fpga, &FPGAReceiver::fpgaError, this, &GameWindow::displayStatusMessage);
// Connect Game
connect(&m_game, &Game::playerChanged, this, &GameWindow::playerChanged);
connect(&m_game, &Game::angleChanged, this, &GameWindow::angleChanged);
connect(&m_game, &Game::powerChanged, this, &GameWindow::powerChanged);
connect(&m_game, &Game::stateChanged, this, &GameWindow::stateChanged);
connect(&m_game, &Game::newGameGenerated, this, &GameWindow::resetPause);
// Connect Info Widgets
connect(this, &GameWindow::changeAngle, m_currentAngle, &AngleStatusWidget::setAngle);
connect(this, &GameWindow::changePlayer, m_gameModeWidget, &GameModeWidget::setCurrentPlayer);
connect(this, &GameWindow::changePower, m_currentPower, &FirePowerWidget::setPower);
connect(this, &GameWindow::changeState, m_gameModeWidget, &GameModeWidget::setCurrentMode);
/****Music****/
QMediaPlaylist* playlist = new QMediaPlaylist;
playlist->addMedia(QUrl::fromLocalFile(QDir::currentPath() + "/resources/music/Angevin_B.mp3"));
playlist->addMedia(QUrl::fromLocalFile(QDir::currentPath() + "/resources/music/Celtic_Impulse.mp3"));
playlist->addMedia(QUrl::fromLocalFile(QDir::currentPath() + "/resources/music/Pippin_the_Hunchback.mp3"));
playlist->shuffle();
playlist->setPlaybackMode(QMediaPlaylist::Loop);
m_musicPlayer.setPlaylist(playlist);
m_musicPlayer.play();
QTimer::singleShot(1, this, &GameWindow::openMainMenu);
}
GameWindow::~GameWindow()
{
}
void GameWindow::displayStatusMessage(QString message)
{
statusBar()->showMessage(message);
}
void GameWindow::playerChanged(Player p_player)
{
emit changePlayer(p_player);
}
void GameWindow::stateChanged(InputState p_state)
{
emit changeState(p_state);
}
void GameWindow::angleChanged(float p_angle)
{
emit changeAngle(p_angle);
}
void GameWindow::powerChanged(float p_power)
{
emit changePower(p_power);
}
void GameWindow::pausedTriggered()
{
if (m_game.pause()) {
m_game.setPause(false);
m_actionPause->setText("Pause");
}
else {
m_game.setPause(true);
if(m_game.pause())
m_actionPause->setText("Jouer");
}
}
void GameWindow::muteTriggered()
{
if(m_musicPlayer.state() == QMediaPlayer::PlayingState) {
m_musicPlayer.pause();
m_actionMuet->setText("Non Muet");
}
else if(m_musicPlayer.state() == QMediaPlayer::PausedState) {
m_musicPlayer.play();
m_actionMuet->setText("Muet");
}
}
void GameWindow::resetPause()
{
m_actionPause->setText("Pause");
}
void GameWindow::keyPressEvent(QKeyEvent * KeyEvent)
{
//NOTE: Hack to simulate correctly the FPGA input
if (m_game.getInputState() == InputState::Fire && KeyEvent->key() == Qt::Key_Space){
QKeyEvent * key = new QKeyEvent(KeyEvent->type(), Qt::Key_Up, Qt::KeyboardModifier::NoModifier);
m_fpga.handlePressEvent(key);
}
else if (m_game.getInputState() == InputState::Fire && (KeyEvent->key() == Qt::Key_Up || KeyEvent->key() == Qt::Key_Down))
return;
else
m_fpga.handlePressEvent(KeyEvent);
}
void GameWindow::customEvent(QEvent *event)
{
if(event->type() == FPGAEvent::customFPGAEvent) {
FPGAEvent* fpgaEvent = static_cast<FPGAEvent *>(event);
QCoreApplication::postEvent(&m_game, new FPGAEvent(*fpgaEvent));
}
}
void GameWindow::openNewGame()
{
FenetreNewGame fenNewGame;
fenNewGame.exec();
if (fenNewGame.result() == QDialog::Accepted) {
m_game.newGame(fenNewGame.getChosenDifficulty(), 2);
m_game.startPlaying();
}
}
void GameWindow::openTutoriel()
{
FenetreTutoriel fenTutoriel;
fenTutoriel.exec();
}
void GameWindow::openVersion()
{
FenetreVersion fenVersion;
fenVersion.exec();
}
void GameWindow::openMainMenu()
{
FenetreNewGame fenNewGame;
fenNewGame.exec();
if (fenNewGame.result() == QDialog::Accepted) {
m_game.newGame(fenNewGame.getChosenDifficulty(), 2);
m_game.startPlaying();
}
else
this->close();
}
void GameWindow::resizeEvent(QResizeEvent *event)
{
QMainWindow::resizeEvent(event);
m_game.getView()->fitInView(m_game.getView()->sceneRect(), Qt::KeepAspectRatio);
}
void GameWindow::closeEvent(QCloseEvent *event)
{
QMessageBox *quitMessage = new QMessageBox(QMessageBox::Information, "Quitter", "Etes vous sur de vouloir quitter?", QMessageBox::Yes | QMessageBox::No);
quitMessage->setWindowIcon(QIcon(QPixmap(":/resources/icon_big.png")));
quitMessage->setFixedSize(80, 220);
if (QMessageBox::Yes == quitMessage->exec())
event->accept();
else {
event->ignore();
if (m_game.getGameState() == Menu)
QTimer::singleShot(1, this, &GameWindow::openMainMenu);
}
}
<|endoftext|>
|
<commit_before>#include "Genes/Gene.h"
#include <cmath>
#include <iostream>
#include <algorithm>
#include <utility>
#include <map>
#include <fstream>
#include <numeric>
#include <iterator>
#include "Game/Board.h"
#include "Game/Color.h"
#include "Utility/Random.h"
#include "Utility/String.h"
#include "Utility/Exceptions.h"
std::map<std::string, double> Gene::list_properties() const noexcept
{
auto properties = std::map<std::string, double>{{"Priority", scoring_priority}, {"Active", double(active)}};
adjust_properties(properties);
return properties;
}
void Gene::adjust_properties(std::map<std::string, double>&) const noexcept
{
}
void Gene::load_properties(const std::map<std::string, double>& properties)
{
if(properties.count("Priority") > 0)
{
scoring_priority = properties.at("Priority");
}
if(properties.count("Active") > 0)
{
active = properties.at("Active") > 0.0;
}
load_gene_properties(properties);
}
void Gene::load_gene_properties(const std::map<std::string, double>&)
{
}
size_t Gene::mutatable_components() const noexcept
{
return list_properties().size();
}
void Gene::read_from(std::istream& is)
{
auto properties = list_properties();
std::map<std::string, bool> property_found;
std::transform(properties.begin(), properties.end(), std::inserter(property_found, property_found.begin()),
[](const auto& key_value)
{
return std::make_pair(key_value.first, false);
});
std::string line;
while(std::getline(is, line))
{
if(String::trim_outer_whitespace(line).empty())
{
break;
}
line = String::strip_comments(line, "#");
if(line.empty())
{
continue;
}
auto split_line = String::split(line, ":");
if(split_line.size() != 2)
{
throw_on_invalid_line(line, "There should be exactly one colon per gene property line.");
}
auto property_name = String::remove_extra_whitespace(split_line[0]);
auto property_data = String::remove_extra_whitespace(split_line[1]);
if(property_name == "Name")
{
if(String::remove_extra_whitespace(property_data) == name())
{
continue;
}
else
{
throw_on_invalid_line(line, "Reading data for wrong gene. Gene is " + name() + ", data is for " + property_data + ".");
}
}
try
{
properties.at(property_name) = std::stod(property_data);
property_found.at(property_name) = true;
}
catch(const std::out_of_range&)
{
throw_on_invalid_line(line, "Unrecognized parameter name.");
}
catch(const std::invalid_argument&)
{
throw_on_invalid_line(line, "Bad parameter value.");
}
}
auto missing_data = std::accumulate(property_found.begin(), property_found.end(), std::string{},
[](const auto& so_far, const auto& name_found)
{
return so_far + ( ! name_found.second ? "\n" + name_found.first : "");
});
if( ! missing_data.empty())
{
throw Genetic_AI_Creation_Error("Missing gene data for " + name() + ":" + missing_data);
}
load_properties(properties);
}
void Gene::read_from(const std::string& file_name)
{
auto ifs = std::ifstream(file_name);
if( ! ifs)
{
throw Genetic_AI_Creation_Error("Could not open " + file_name + " to read.");
}
std::string line;
while(std::getline(ifs, line))
{
if(String::starts_with(line, "Name: "))
{
auto gene_name = String::remove_extra_whitespace(String::split(line, ":", 1)[1]);
if(gene_name == name())
{
try
{
read_from(ifs);
return;
}
catch(const std::exception& e)
{
throw Genetic_AI_Creation_Error("Error in reading data for " + name() + " from " + file_name + "\n" + e.what());
}
}
}
}
throw Genetic_AI_Creation_Error(name() + " not found in " + file_name);
}
void Gene::throw_on_invalid_line(const std::string& line, const std::string& reason) const
{
throw Genetic_AI_Creation_Error("Invalid line in while reading for " + name() + ": " + line + "\n" + reason);
}
void Gene::mutate() noexcept
{
if(Random::success_probability(1, 1000))
{
active = ! active;
}
if( ! is_active())
{
return;
}
auto properties = list_properties();
if(Random::success_probability(properties.count("Priority"), properties.size()))
{
scoring_priority += Random::random_laplace(0.005);
}
else
{
gene_specific_mutation();
}
}
void Gene::gene_specific_mutation() noexcept
{
}
double Gene::evaluate(const Board& board, Piece_Color perspective, size_t depth) const noexcept
{
if(is_active())
{
return scoring_priority*score_board(board, perspective, depth);
}
else
{
return 0.0;
}
}
void Gene::print(std::ostream& os) const noexcept
{
auto properties = list_properties();
os << "Name: " << name() << "\n";
for(const auto& [name, value] : properties)
{
os << name << ": " << value << "\n";
}
os << "\n";
}
void Gene::reset_piece_strength_gene(const Piece_Strength_Gene*) noexcept
{
}
double Gene::priority() const noexcept
{
return scoring_priority;
}
void Gene::scale_priority(double k) noexcept
{
scoring_priority *= k;
}
void Gene::zero_out_priority() noexcept
{
scoring_priority = 0.0;
}
bool Gene::is_active() const noexcept
{
return active;
}
void Gene::test(bool& test_variable, const Board& board, Piece_Color perspective, double expected_score) const noexcept
{
auto result = score_board(board, perspective, board.game_length() == 0 ? 0 : 1);
if(std::abs(result - expected_score) > 1e-6)
{
std::cerr << "Error in " << name() << ": Expected " << expected_score << ", Got: " << result << '\n';
test_variable = false;
}
}
<commit_msg>Make reactivation more probable than deactivation<commit_after>#include "Genes/Gene.h"
#include <cmath>
#include <iostream>
#include <algorithm>
#include <utility>
#include <map>
#include <fstream>
#include <numeric>
#include <iterator>
#include "Game/Board.h"
#include "Game/Color.h"
#include "Utility/Random.h"
#include "Utility/String.h"
#include "Utility/Exceptions.h"
std::map<std::string, double> Gene::list_properties() const noexcept
{
auto properties = std::map<std::string, double>{{"Priority", scoring_priority}, {"Active", double(active)}};
adjust_properties(properties);
return properties;
}
void Gene::adjust_properties(std::map<std::string, double>&) const noexcept
{
}
void Gene::load_properties(const std::map<std::string, double>& properties)
{
if(properties.count("Priority") > 0)
{
scoring_priority = properties.at("Priority");
}
if(properties.count("Active") > 0)
{
active = properties.at("Active") > 0.0;
}
load_gene_properties(properties);
}
void Gene::load_gene_properties(const std::map<std::string, double>&)
{
}
size_t Gene::mutatable_components() const noexcept
{
return list_properties().size();
}
void Gene::read_from(std::istream& is)
{
auto properties = list_properties();
std::map<std::string, bool> property_found;
std::transform(properties.begin(), properties.end(), std::inserter(property_found, property_found.begin()),
[](const auto& key_value)
{
return std::make_pair(key_value.first, false);
});
std::string line;
while(std::getline(is, line))
{
if(String::trim_outer_whitespace(line).empty())
{
break;
}
line = String::strip_comments(line, "#");
if(line.empty())
{
continue;
}
auto split_line = String::split(line, ":");
if(split_line.size() != 2)
{
throw_on_invalid_line(line, "There should be exactly one colon per gene property line.");
}
auto property_name = String::remove_extra_whitespace(split_line[0]);
auto property_data = String::remove_extra_whitespace(split_line[1]);
if(property_name == "Name")
{
if(String::remove_extra_whitespace(property_data) == name())
{
continue;
}
else
{
throw_on_invalid_line(line, "Reading data for wrong gene. Gene is " + name() + ", data is for " + property_data + ".");
}
}
try
{
properties.at(property_name) = std::stod(property_data);
property_found.at(property_name) = true;
}
catch(const std::out_of_range&)
{
throw_on_invalid_line(line, "Unrecognized parameter name.");
}
catch(const std::invalid_argument&)
{
throw_on_invalid_line(line, "Bad parameter value.");
}
}
auto missing_data = std::accumulate(property_found.begin(), property_found.end(), std::string{},
[](const auto& so_far, const auto& name_found)
{
return so_far + ( ! name_found.second ? "\n" + name_found.first : "");
});
if( ! missing_data.empty())
{
throw Genetic_AI_Creation_Error("Missing gene data for " + name() + ":" + missing_data);
}
load_properties(properties);
}
void Gene::read_from(const std::string& file_name)
{
auto ifs = std::ifstream(file_name);
if( ! ifs)
{
throw Genetic_AI_Creation_Error("Could not open " + file_name + " to read.");
}
std::string line;
while(std::getline(ifs, line))
{
if(String::starts_with(line, "Name: "))
{
auto gene_name = String::remove_extra_whitespace(String::split(line, ":", 1)[1]);
if(gene_name == name())
{
try
{
read_from(ifs);
return;
}
catch(const std::exception& e)
{
throw Genetic_AI_Creation_Error("Error in reading data for " + name() + " from " + file_name + "\n" + e.what());
}
}
}
}
throw Genetic_AI_Creation_Error(name() + " not found in " + file_name);
}
void Gene::throw_on_invalid_line(const std::string& line, const std::string& reason) const
{
throw Genetic_AI_Creation_Error("Invalid line in while reading for " + name() + ": " + line + "\n" + reason);
}
void Gene::mutate() noexcept
{
if(is_active())
{
if(Random::success_probability(1, 1000))
{
active = false;
}
}
else
{
if(Random::success_probability(1, 100))
{
active = true;
}
}
if( ! is_active())
{
return;
}
auto properties = list_properties();
if(Random::success_probability(properties.count("Priority"), properties.size()))
{
scoring_priority += Random::random_laplace(0.005);
}
else
{
gene_specific_mutation();
}
}
void Gene::gene_specific_mutation() noexcept
{
}
double Gene::evaluate(const Board& board, Piece_Color perspective, size_t depth) const noexcept
{
if(is_active())
{
return scoring_priority*score_board(board, perspective, depth);
}
else
{
return 0.0;
}
}
void Gene::print(std::ostream& os) const noexcept
{
auto properties = list_properties();
os << "Name: " << name() << "\n";
for(const auto& [name, value] : properties)
{
os << name << ": " << value << "\n";
}
os << "\n";
}
void Gene::reset_piece_strength_gene(const Piece_Strength_Gene*) noexcept
{
}
double Gene::priority() const noexcept
{
return scoring_priority;
}
void Gene::scale_priority(double k) noexcept
{
scoring_priority *= k;
}
void Gene::zero_out_priority() noexcept
{
scoring_priority = 0.0;
}
bool Gene::is_active() const noexcept
{
return active;
}
void Gene::test(bool& test_variable, const Board& board, Piece_Color perspective, double expected_score) const noexcept
{
auto result = score_board(board, perspective, board.game_length() == 0 ? 0 : 1);
if(std::abs(result - expected_score) > 1e-6)
{
std::cerr << "Error in " << name() << ": Expected " << expected_score << ", Got: " << result << '\n';
test_variable = false;
}
}
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "IndexWriter.h"
#include <fnord-fts/AnalyzerAdapter.h>
using namespace fnord;
namespace cm {
RefPtr<IndexWriter> IndexWriter::openIndex(
const String& index_path,
const String& conf_path) {
if (!FileUtil::exists(index_path) || !FileUtil::isDirectory(index_path)) {
RAISEF(kIllegalArgumentError, "invalid index path: $0", index_path);
}
/* set up feature schema */
FeatureSchema feature_schema;
feature_schema.registerFeature("shop_id", 1, 1);
feature_schema.registerFeature("category1", 2, 1);
feature_schema.registerFeature("category2", 3, 1);
feature_schema.registerFeature("category3", 4, 1);
feature_schema.registerFeature("price_cents", 8, 1);
feature_schema.registerFeature("title~de", 5, 2);
feature_schema.registerFeature("description~de", 6, 2);
feature_schema.registerFeature("size_description~de", 14, 2);
feature_schema.registerFeature("material_description~de", 15, 2);
feature_schema.registerFeature("basic_attributes~de", 16, 2);
feature_schema.registerFeature("tags_as_text~de", 7, 2);
feature_schema.registerFeature("title~pl", 18, 2);
feature_schema.registerFeature("description~pl", 19, 2);
feature_schema.registerFeature("size_description~pl", 20, 2);
feature_schema.registerFeature("material_description~pl", 21, 2);
feature_schema.registerFeature("basic_attributes~pl", 22, 2);
feature_schema.registerFeature("tags_as_text~pl", 23, 2);
feature_schema.registerFeature("image_filename", 24, 2);
feature_schema.registerFeature("cm_clicked_terms", 31, 2);
feature_schema.registerFeature("shop_name", 26, 3);
feature_schema.registerFeature("shop_platform", 27, 3);
feature_schema.registerFeature("shop_country", 28, 3);
feature_schema.registerFeature("shop_rating_alt", 9, 3);
feature_schema.registerFeature("shop_rating_alt2", 15, 3);
feature_schema.registerFeature("shop_products_count", 10, 3);
feature_schema.registerFeature("shop_orders_count", 11, 3);
feature_schema.registerFeature("shop_rating_count", 12, 3);
feature_schema.registerFeature("shop_rating_avg", 13, 3);
feature_schema.registerFeature("cm_views", 29, 3);
feature_schema.registerFeature("cm_clicks", 30, 3);
feature_schema.registerFeature("cm_ctr", 32, 3);
feature_schema.registerFeature("cm_ctr_norm", 33, 3);
feature_schema.registerFeature("cm_ctr_std", 34, 3);
feature_schema.registerFeature("cm_ctr_norm_std", 35, 3);
/* open mdb */
auto db_path = FileUtil::joinPaths(index_path, "db");
FileUtil::mkdir_p(db_path);
auto db = mdb::MDB::open(db_path, false, 68719476736lu); // 64 GiB
/* open lucene */
RefPtr<fnord::fts::Analyzer> analyzer(new fnord::fts::Analyzer(conf_path));
auto adapter = std::make_shared<fnord::fts::AnalyzerAdapter>(analyzer);
auto fts_path = FileUtil::joinPaths(index_path, "fts");
bool create = false;
if (!FileUtil::exists(fts_path)) {
FileUtil::mkdir_p(fts_path);
create = true;
}
auto fts =
fts::newLucene<fts::IndexWriter>(
fts::FSDirectory::open(StringUtil::convertUTF8To16(fts_path)),
adapter,
create,
fts::IndexWriter::MaxFieldLengthLIMITED);
return RefPtr<IndexWriter>(new IndexWriter(feature_schema, db, fts));
}
IndexWriter::IndexWriter(
FeatureSchema schema,
RefPtr<mdb::MDB> db,
std::shared_ptr<fts::IndexWriter> fts) :
schema_(schema),
db_(db),
db_txn_(db_->startTransaction()),
feature_idx_(new FeatureIndexWriter(&schema_)),
fts_(fts) {}
IndexWriter::~IndexWriter() {
if (db_txn_.get()) {
db_txn_->commit();
}
fts_->close();
}
void IndexWriter::updateDocument(const IndexRequest& index_request) {
stat_documents_indexed_total_.incr(1);
auto docid = index_request.item.docID();
feature_idx_->updateDocument(index_request, db_txn_.get());
auto doc = feature_idx_->findDocument(docid, db_txn_.get());
rebuildFTS(doc);
stat_documents_indexed_success_.incr(1);
}
void IndexWriter::commit() {
db_txn_->commit();
db_txn_ = db_->startTransaction();
fts_->commit();
}
void IndexWriter::rebuildFTS(DocID docid) {
auto doc = feature_idx_->findDocument(docid, db_txn_.get());
rebuildFTS(doc);
}
void IndexWriter::rebuildFTS(RefPtr<Document> doc) {
stat_documents_indexed_fts_.incr(1);
auto fts_doc = fts::newLucene<fts::Document>();
fts_doc->add(
fts::newLucene<fts::Field>(
L"_docid",
StringUtil::convertUTF8To16(doc->docID().docid),
fts::Field::STORE_YES,
fts::Field::INDEX_NOT_ANALYZED_NO_NORMS));
double boost = 1.0;
double cm_clicks = 0;
double cm_views = 0;
double cm_ctr_norm_std = 1.0;
bool is_active = false;
HashMap<String, String> fts_fields_anal;
for (const auto& f : doc->fields()) {
/* title~LANG */
if (StringUtil::beginsWith(f.first, "title~")) {
is_active = true;
auto k = f.first;
StringUtil::replaceAll(&k, "title~","title~");
fts_fields_anal[k] += " " + f.second;
}
/* description~LANG */
else if (StringUtil::beginsWith(f.first, "description~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "description~","text~");
fts_fields_anal[k] += " " + f.second;
}
/* size_description~LANG */
else if (StringUtil::beginsWith(f.first, "size_description~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "size_description~","text~");
fts_fields_anal[k] += " " + f.second;
}
/* material_description~LANG */
else if (StringUtil::beginsWith(f.first, "material_description~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "material_description~","text~");
fts_fields_anal[k] += " " + f.second;
}
/* manufacturing_description~LANG */
else if (StringUtil::beginsWith(f.first, "manufacturing_description~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "manufacturing_description~","text~");
fts_fields_anal[k] += " " + f.second;
}
/* tags_as_text~LANG */
else if (StringUtil::beginsWith(f.first, "tags_as_text~")) {
fts_fields_anal["tags"] += " " + f.second;
}
/* shop_name */
else if (f.first == "shop_name") {
fts_fields_anal["tags"] += " " + f.second;
}
/* cm_clicked_terms */
else if (f.first == "cm_clicked_terms") {
fts_doc->add(
fts::newLucene<fts::Field>(
L"cm_clicked_terms",
StringUtil::convertUTF8To16(f.second),
fts::Field::STORE_NO,
fts::Field::INDEX_ANALYZED));
}
else if (f.first == "cm_ctr_norm_std") {
cm_ctr_norm_std = std::stod(f.second);
}
else if (f.first == "cm_clicks") {
cm_clicks = std::stod(f.second);
}
else if (f.first == "cm_views") {
cm_views = std::stod(f.second);
}
}
for (const auto& f : fts_fields_anal) {
fts_doc->add(
fts::newLucene<fts::Field>(
StringUtil::convertUTF8To16(f.first),
StringUtil::convertUTF8To16(f.second),
fts::Field::STORE_NO,
fts::Field::INDEX_ANALYZED));
}
if (cm_views > 1000 && cm_clicks > 15) {
boost = cm_ctr_norm_std;
}
fts_doc->setBoost(boost);
fnord::logDebug(
"cm.indexwriter",
"Rebuilding FTS Index for docid=$0 boost=$1 active=$2",
doc->docID().docid,
boost,
is_active);
auto del_term = fts::newLucene<fts::Term>(
L"_docid",
StringUtil::convertUTF8To16(doc->docID().docid));
if (is_active) {
fts_->updateDocument(del_term, fts_doc);
} else {
fts_->deleteDocuments(del_term);
}
}
void IndexWriter::rebuildFTS(size_t csize) {
Vector<DocID> docids;
feature_idx_->listDocuments([&docids] (const DocID& docid) -> bool {
docids.emplace_back(docid);
return true;
}, db_txn_.get());
size_t n;
for (const auto& docid : docids) {
rebuildFTS(docid);
if (++n > csize) {
commit();
n = 0;
}
}
}
RefPtr<mdb::MDBTransaction> IndexWriter::dbTransaction() {
return db_txn_;
}
void IndexWriter::exportStats(const String& prefix) {
exportStat(
StringUtil::format("$0/documents_indexed_total", prefix),
&stat_documents_indexed_total_,
fnord::stats::ExportMode::EXPORT_DELTA);
exportStat(
StringUtil::format("$0/documents_indexed_success", prefix),
&stat_documents_indexed_success_,
fnord::stats::ExportMode::EXPORT_DELTA);
exportStat(
StringUtil::format("$0/documents_indexed_error", prefix),
&stat_documents_indexed_error_,
fnord::stats::ExportMode::EXPORT_DELTA);
exportStat(
StringUtil::format("$0/documents_indexed_fts", prefix),
&stat_documents_indexed_fts_,
fnord::stats::ExportMode::EXPORT_DELTA);
}
} // namespace cm
<commit_msg>default boost 0.7<commit_after>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "IndexWriter.h"
#include <fnord-fts/AnalyzerAdapter.h>
using namespace fnord;
namespace cm {
RefPtr<IndexWriter> IndexWriter::openIndex(
const String& index_path,
const String& conf_path) {
if (!FileUtil::exists(index_path) || !FileUtil::isDirectory(index_path)) {
RAISEF(kIllegalArgumentError, "invalid index path: $0", index_path);
}
/* set up feature schema */
FeatureSchema feature_schema;
feature_schema.registerFeature("shop_id", 1, 1);
feature_schema.registerFeature("category1", 2, 1);
feature_schema.registerFeature("category2", 3, 1);
feature_schema.registerFeature("category3", 4, 1);
feature_schema.registerFeature("price_cents", 8, 1);
feature_schema.registerFeature("title~de", 5, 2);
feature_schema.registerFeature("description~de", 6, 2);
feature_schema.registerFeature("size_description~de", 14, 2);
feature_schema.registerFeature("material_description~de", 15, 2);
feature_schema.registerFeature("basic_attributes~de", 16, 2);
feature_schema.registerFeature("tags_as_text~de", 7, 2);
feature_schema.registerFeature("title~pl", 18, 2);
feature_schema.registerFeature("description~pl", 19, 2);
feature_schema.registerFeature("size_description~pl", 20, 2);
feature_schema.registerFeature("material_description~pl", 21, 2);
feature_schema.registerFeature("basic_attributes~pl", 22, 2);
feature_schema.registerFeature("tags_as_text~pl", 23, 2);
feature_schema.registerFeature("image_filename", 24, 2);
feature_schema.registerFeature("cm_clicked_terms", 31, 2);
feature_schema.registerFeature("shop_name", 26, 3);
feature_schema.registerFeature("shop_platform", 27, 3);
feature_schema.registerFeature("shop_country", 28, 3);
feature_schema.registerFeature("shop_rating_alt", 9, 3);
feature_schema.registerFeature("shop_rating_alt2", 15, 3);
feature_schema.registerFeature("shop_products_count", 10, 3);
feature_schema.registerFeature("shop_orders_count", 11, 3);
feature_schema.registerFeature("shop_rating_count", 12, 3);
feature_schema.registerFeature("shop_rating_avg", 13, 3);
feature_schema.registerFeature("cm_views", 29, 3);
feature_schema.registerFeature("cm_clicks", 30, 3);
feature_schema.registerFeature("cm_ctr", 32, 3);
feature_schema.registerFeature("cm_ctr_norm", 33, 3);
feature_schema.registerFeature("cm_ctr_std", 34, 3);
feature_schema.registerFeature("cm_ctr_norm_std", 35, 3);
/* open mdb */
auto db_path = FileUtil::joinPaths(index_path, "db");
FileUtil::mkdir_p(db_path);
auto db = mdb::MDB::open(db_path, false, 68719476736lu); // 64 GiB
/* open lucene */
RefPtr<fnord::fts::Analyzer> analyzer(new fnord::fts::Analyzer(conf_path));
auto adapter = std::make_shared<fnord::fts::AnalyzerAdapter>(analyzer);
auto fts_path = FileUtil::joinPaths(index_path, "fts");
bool create = false;
if (!FileUtil::exists(fts_path)) {
FileUtil::mkdir_p(fts_path);
create = true;
}
auto fts =
fts::newLucene<fts::IndexWriter>(
fts::FSDirectory::open(StringUtil::convertUTF8To16(fts_path)),
adapter,
create,
fts::IndexWriter::MaxFieldLengthLIMITED);
return RefPtr<IndexWriter>(new IndexWriter(feature_schema, db, fts));
}
IndexWriter::IndexWriter(
FeatureSchema schema,
RefPtr<mdb::MDB> db,
std::shared_ptr<fts::IndexWriter> fts) :
schema_(schema),
db_(db),
db_txn_(db_->startTransaction()),
feature_idx_(new FeatureIndexWriter(&schema_)),
fts_(fts) {}
IndexWriter::~IndexWriter() {
if (db_txn_.get()) {
db_txn_->commit();
}
fts_->close();
}
void IndexWriter::updateDocument(const IndexRequest& index_request) {
stat_documents_indexed_total_.incr(1);
auto docid = index_request.item.docID();
feature_idx_->updateDocument(index_request, db_txn_.get());
auto doc = feature_idx_->findDocument(docid, db_txn_.get());
rebuildFTS(doc);
stat_documents_indexed_success_.incr(1);
}
void IndexWriter::commit() {
db_txn_->commit();
db_txn_ = db_->startTransaction();
fts_->commit();
}
void IndexWriter::rebuildFTS(DocID docid) {
auto doc = feature_idx_->findDocument(docid, db_txn_.get());
rebuildFTS(doc);
}
void IndexWriter::rebuildFTS(RefPtr<Document> doc) {
stat_documents_indexed_fts_.incr(1);
auto fts_doc = fts::newLucene<fts::Document>();
fts_doc->add(
fts::newLucene<fts::Field>(
L"_docid",
StringUtil::convertUTF8To16(doc->docID().docid),
fts::Field::STORE_YES,
fts::Field::INDEX_NOT_ANALYZED_NO_NORMS));
double boost = 0.7;
double cm_clicks = 0;
double cm_views = 0;
double cm_ctr_norm_std = 1.0;
bool is_active = false;
HashMap<String, String> fts_fields_anal;
for (const auto& f : doc->fields()) {
/* title~LANG */
if (StringUtil::beginsWith(f.first, "title~")) {
is_active = true;
auto k = f.first;
StringUtil::replaceAll(&k, "title~","title~");
fts_fields_anal[k] += " " + f.second;
}
/* description~LANG */
else if (StringUtil::beginsWith(f.first, "description~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "description~","text~");
fts_fields_anal[k] += " " + f.second;
}
/* size_description~LANG */
else if (StringUtil::beginsWith(f.first, "size_description~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "size_description~","text~");
fts_fields_anal[k] += " " + f.second;
}
/* material_description~LANG */
else if (StringUtil::beginsWith(f.first, "material_description~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "material_description~","text~");
fts_fields_anal[k] += " " + f.second;
}
/* manufacturing_description~LANG */
else if (StringUtil::beginsWith(f.first, "manufacturing_description~")) {
auto k = f.first;
StringUtil::replaceAll(&k, "manufacturing_description~","text~");
fts_fields_anal[k] += " " + f.second;
}
/* tags_as_text~LANG */
else if (StringUtil::beginsWith(f.first, "tags_as_text~")) {
fts_fields_anal["tags"] += " " + f.second;
}
/* shop_name */
else if (f.first == "shop_name") {
fts_fields_anal["tags"] += " " + f.second;
}
/* cm_clicked_terms */
else if (f.first == "cm_clicked_terms") {
fts_doc->add(
fts::newLucene<fts::Field>(
L"cm_clicked_terms",
StringUtil::convertUTF8To16(f.second),
fts::Field::STORE_NO,
fts::Field::INDEX_ANALYZED));
}
else if (f.first == "cm_ctr_norm_std") {
cm_ctr_norm_std = std::stod(f.second);
}
else if (f.first == "cm_clicks") {
cm_clicks = std::stod(f.second);
}
else if (f.first == "cm_views") {
cm_views = std::stod(f.second);
}
}
for (const auto& f : fts_fields_anal) {
fts_doc->add(
fts::newLucene<fts::Field>(
StringUtil::convertUTF8To16(f.first),
StringUtil::convertUTF8To16(f.second),
fts::Field::STORE_NO,
fts::Field::INDEX_ANALYZED));
}
if (cm_views > 1000 && cm_clicks > 15) {
boost = cm_ctr_norm_std;
}
fts_doc->setBoost(boost);
fnord::logDebug(
"cm.indexwriter",
"Rebuilding FTS Index for docid=$0 boost=$1 active=$2",
doc->docID().docid,
boost,
is_active);
auto del_term = fts::newLucene<fts::Term>(
L"_docid",
StringUtil::convertUTF8To16(doc->docID().docid));
if (is_active) {
fts_->updateDocument(del_term, fts_doc);
} else {
fts_->deleteDocuments(del_term);
}
}
void IndexWriter::rebuildFTS(size_t csize) {
Vector<DocID> docids;
feature_idx_->listDocuments([&docids] (const DocID& docid) -> bool {
docids.emplace_back(docid);
return true;
}, db_txn_.get());
size_t n;
for (const auto& docid : docids) {
rebuildFTS(docid);
if (++n > csize) {
commit();
n = 0;
}
}
}
RefPtr<mdb::MDBTransaction> IndexWriter::dbTransaction() {
return db_txn_;
}
void IndexWriter::exportStats(const String& prefix) {
exportStat(
StringUtil::format("$0/documents_indexed_total", prefix),
&stat_documents_indexed_total_,
fnord::stats::ExportMode::EXPORT_DELTA);
exportStat(
StringUtil::format("$0/documents_indexed_success", prefix),
&stat_documents_indexed_success_,
fnord::stats::ExportMode::EXPORT_DELTA);
exportStat(
StringUtil::format("$0/documents_indexed_error", prefix),
&stat_documents_indexed_error_,
fnord::stats::ExportMode::EXPORT_DELTA);
exportStat(
StringUtil::format("$0/documents_indexed_fts", prefix),
&stat_documents_indexed_fts_,
fnord::stats::ExportMode::EXPORT_DELTA);
}
} // namespace cm
<|endoftext|>
|
<commit_before>// Scintilla source code edit control
/** @file LineMarker.cxx
** Defines the look of a line marker in the margin .
**/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include "Platform.h"
#include "Scintilla.h"
#include "LineMarker.h"
static void DrawBox(Surface *surface, int centreX, int centreY, int armSize) {
surface->MoveTo(centreX - armSize, centreY - armSize);
surface->LineTo(centreX + armSize, centreY - armSize);
surface->LineTo(centreX + armSize, centreY + armSize);
surface->LineTo(centreX - armSize, centreY + armSize);
surface->LineTo(centreX - armSize, centreY - armSize);
}
static void DrawCircle(Surface *surface, int centreX, int centreY, int armSize, Colour fore, Colour back) {
PRectangle rcCircle;
rcCircle.left = centreX - armSize;
rcCircle.top = centreY - armSize;
rcCircle.right = centreX + armSize + 1;
rcCircle.bottom = centreY + armSize + 1;
surface->Ellipse(rcCircle, back, fore);
}
static void DrawPlus(Surface *surface, int centreX, int centreY, int armSize) {
surface->MoveTo(centreX - armSize + 2, centreY);
surface->LineTo(centreX + armSize - 2 + 1, centreY);
surface->MoveTo(centreX, centreY - armSize + 2);
surface->LineTo(centreX, centreY + armSize - 2 + 1);
}
static void DrawMinus(Surface *surface, int centreX, int centreY, int armSize) {
surface->MoveTo(centreX - armSize + 2, centreY);
surface->LineTo(centreX + armSize - 2 + 1, centreY);
}
void LineMarker::Draw(Surface *surface, PRectangle &rcWhole) {
// Restrict most shapes a bit
PRectangle rc = rcWhole;
rc.top++;
rc.bottom--;
int minDim = Platform::Minimum(rc.Width(), rc.Height());
minDim--; // Ensure does not go beyond edge
int centreX = (rc.right + rc.left) / 2;
int centreY = (rc.bottom + rc.top) / 2;
int dimOn2 = minDim / 2;
int dimOn4 = minDim / 4;
int armSize = dimOn2-2;
if (rc.Width() > (rc.Height() * 2)) {
// Wide column is line number so move to left to try to avoid overlapping number
centreX = rc.left + dimOn2 + 1;
}
if (markType == SC_MARK_ROUNDRECT) {
PRectangle rcRounded = rc;
rcRounded.left = rc.left + 1;
rcRounded.right = rc.right - 1;
surface->RoundedRectangle(rcRounded, fore.allocated, back.allocated);
} else if (markType == SC_MARK_CIRCLE) {
PRectangle rcCircle;
rcCircle.left = centreX - dimOn2;
rcCircle.top = centreY - dimOn2;
rcCircle.right = centreX + dimOn2;
rcCircle.bottom = centreY + dimOn2;
surface->Ellipse(rcCircle, fore.allocated, back.allocated);
} else if (markType == SC_MARK_ARROW) {
Point pts[] = {
Point(centreX - dimOn4, centreY - dimOn2),
Point(centreX - dimOn4, centreY + dimOn2),
Point(centreX + dimOn2 - dimOn4, centreY),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_ARROWDOWN) {
Point pts[] = {
Point(centreX - dimOn2, centreY - dimOn4),
Point(centreX + dimOn2, centreY - dimOn4),
Point(centreX, centreY + dimOn2 - dimOn4),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_PLUS) {
Point pts[] = {
Point(centreX - armSize, centreY - 1),
Point(centreX - 1, centreY - 1),
Point(centreX - 1, centreY - armSize),
Point(centreX + 1, centreY - armSize),
Point(centreX + 1, centreY - 1),
Point(centreX + armSize, centreY -1),
Point(centreX + armSize, centreY +1),
Point(centreX + 1, centreY + 1),
Point(centreX + 1, centreY + armSize),
Point(centreX - 1, centreY + armSize),
Point(centreX - 1, centreY + 1),
Point(centreX - armSize, centreY + 1),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_MINUS) {
Point pts[] = {
Point(centreX - armSize, centreY - 1),
Point(centreX + armSize, centreY -1),
Point(centreX + armSize, centreY +1),
Point(centreX - armSize, centreY + 1),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_SMALLRECT) {
PRectangle rcSmall;
rcSmall.left = rc.left + 1;
rcSmall.top = rc.top + 2;
rcSmall.right = rc.right - 1;
rcSmall.bottom = rc.bottom - 2;
surface->RectangleDraw(rcSmall, fore.allocated, back.allocated);
} else if (markType == SC_MARK_EMPTY) {
// An invisible marker so don't draw anything
} else if (markType == SC_MARK_VLINE) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rcWhole.bottom);
} else if (markType == SC_MARK_LCORNER) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rc.top + dimOn2);
surface->LineTo(rc.right - 2, rc.top + dimOn2);
} else if (markType == SC_MARK_TCORNER) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rc.top + dimOn2);
surface->LineTo(rc.right - 2, rc.top + dimOn2);
} else if (markType == SC_MARK_LCORNERCURVE) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rc.top + dimOn2-3);
surface->LineTo(centreX+3, rc.top + dimOn2);
surface->LineTo(rc.right - 1, rc.top + dimOn2);
} else if (markType == SC_MARK_TCORNERCURVE) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rc.top + dimOn2-3);
surface->LineTo(centreX+3, rc.top + dimOn2);
surface->LineTo(rc.right - 1, rc.top + dimOn2);
} else if (markType == SC_MARK_BOXPLUS) {
surface->PenColour(back.allocated);
DrawBox(surface, centreX, centreY, armSize);
DrawPlus(surface, centreX, centreY, armSize);
} else if (markType == SC_MARK_BOXPLUSCONNECTED) {
surface->PenColour(back.allocated);
DrawBox(surface, centreX, centreY, armSize);
DrawPlus(surface, centreX, centreY, armSize);
surface->MoveTo(centreX, centreY + armSize);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, centreY - armSize);
} else if (markType == SC_MARK_BOXMINUS) {
surface->PenColour(back.allocated);
DrawBox(surface, centreX, centreY, armSize);
DrawMinus(surface, centreX, centreY, armSize);
surface->MoveTo(centreX, centreY + armSize);
surface->LineTo(centreX, rcWhole.bottom);
} else if (markType == SC_MARK_BOXMINUSCONNECTED) {
surface->PenColour(back.allocated);
DrawBox(surface, centreX, centreY, armSize);
DrawMinus(surface, centreX, centreY, armSize);
surface->MoveTo(centreX, centreY + armSize);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, centreY - armSize);
} else if (markType == SC_MARK_CIRCLEPLUS) {
DrawCircle(surface, centreX, centreY, armSize, fore.allocated, back.allocated);
surface->PenColour(back.allocated);
DrawPlus(surface, centreX, centreY, armSize);
} else if (markType == SC_MARK_CIRCLEPLUSCONNECTED) {
DrawCircle(surface, centreX, centreY, armSize, fore.allocated, back.allocated);
surface->PenColour(back.allocated);
DrawPlus(surface, centreX, centreY, armSize);
surface->MoveTo(centreX, centreY + armSize);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, centreY - armSize);
} else if (markType == SC_MARK_CIRCLEMINUS) {
DrawCircle(surface, centreX, centreY, armSize, fore.allocated, back.allocated);
surface->PenColour(back.allocated);
DrawMinus(surface, centreX, centreY, armSize);
surface->MoveTo(centreX, centreY + armSize);
surface->LineTo(centreX, rcWhole.bottom);
} else if (markType == SC_MARK_CIRCLEMINUSCONNECTED) {
DrawCircle(surface, centreX, centreY, armSize, fore.allocated, back.allocated);
surface->PenColour(back.allocated);
DrawMinus(surface, centreX, centreY, armSize);
surface->MoveTo(centreX, centreY + armSize);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, centreY - armSize);
} else { // SC_MARK_SHORTARROW
Point pts[] = {
Point(centreX, centreY + dimOn2),
Point(centreX + dimOn2, centreY),
Point(centreX, centreY - dimOn2),
Point(centreX, centreY - dimOn4),
Point(centreX - dimOn4, centreY - dimOn4),
Point(centreX - dimOn4, centreY + dimOn4),
Point(centreX, centreY + dimOn4),
Point(centreX, centreY + dimOn2),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
}
}
<commit_msg>Made header blobs larger and odd number of pixels in size so that minus and plus signs can be centred.<commit_after>// Scintilla source code edit control
/** @file LineMarker.cxx
** Defines the look of a line marker in the margin .
**/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include "Platform.h"
#include "Scintilla.h"
#include "LineMarker.h"
static void DrawBox(Surface *surface, int centreX, int centreY, int armSize, Colour fore, Colour back) {
PRectangle rc;
rc.left = centreX - armSize;
rc.top = centreY - armSize;
rc.right = centreX + armSize + 1;
rc.bottom = centreY + armSize + 1;
surface->RectangleDraw(rc, back, fore);
}
static void DrawCircle(Surface *surface, int centreX, int centreY, int armSize, Colour fore, Colour back) {
PRectangle rcCircle;
rcCircle.left = centreX - armSize;
rcCircle.top = centreY - armSize;
rcCircle.right = centreX + armSize + 1;
rcCircle.bottom = centreY + armSize + 1;
surface->Ellipse(rcCircle, back, fore);
}
static void DrawPlus(Surface *surface, int centreX, int centreY, int armSize, Colour fore) {
PRectangle rcV(centreX, centreY - armSize + 2, centreX + 1, centreY + armSize - 2 + 1);
surface->FillRectangle(rcV, fore);
PRectangle rcH(centreX - armSize + 2, centreY, centreX + armSize - 2 + 1, centreY+1);
surface->FillRectangle(rcH, fore);
}
static void DrawMinus(Surface *surface, int centreX, int centreY, int armSize, Colour fore) {
PRectangle rcH(centreX - armSize + 2, centreY, centreX + armSize - 2 + 1, centreY+1);
surface->FillRectangle(rcH, fore);
}
void LineMarker::Draw(Surface *surface, PRectangle &rcWhole) {
// Restrict most shapes a bit
PRectangle rc = rcWhole;
rc.top++;
rc.bottom--;
int minDim = Platform::Minimum(rc.Width(), rc.Height());
minDim--; // Ensure does not go beyond edge
int centreX = (rc.right + rc.left) / 2;
int centreY = (rc.bottom + rc.top) / 2;
int dimOn2 = minDim / 2;
int dimOn4 = minDim / 4;
int blobSize = dimOn2-1;
int armSize = dimOn2-2;
if (rc.Width() > (rc.Height() * 2)) {
// Wide column is line number so move to left to try to avoid overlapping number
centreX = rc.left + dimOn2 + 1;
}
if (markType == SC_MARK_ROUNDRECT) {
PRectangle rcRounded = rc;
rcRounded.left = rc.left + 1;
rcRounded.right = rc.right - 1;
surface->RoundedRectangle(rcRounded, fore.allocated, back.allocated);
} else if (markType == SC_MARK_CIRCLE) {
PRectangle rcCircle;
rcCircle.left = centreX - dimOn2;
rcCircle.top = centreY - dimOn2;
rcCircle.right = centreX + dimOn2;
rcCircle.bottom = centreY + dimOn2;
surface->Ellipse(rcCircle, fore.allocated, back.allocated);
} else if (markType == SC_MARK_ARROW) {
Point pts[] = {
Point(centreX - dimOn4, centreY - dimOn2),
Point(centreX - dimOn4, centreY + dimOn2),
Point(centreX + dimOn2 - dimOn4, centreY),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_ARROWDOWN) {
Point pts[] = {
Point(centreX - dimOn2, centreY - dimOn4),
Point(centreX + dimOn2, centreY - dimOn4),
Point(centreX, centreY + dimOn2 - dimOn4),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_PLUS) {
Point pts[] = {
Point(centreX - armSize, centreY - 1),
Point(centreX - 1, centreY - 1),
Point(centreX - 1, centreY - armSize),
Point(centreX + 1, centreY - armSize),
Point(centreX + 1, centreY - 1),
Point(centreX + armSize, centreY -1),
Point(centreX + armSize, centreY +1),
Point(centreX + 1, centreY + 1),
Point(centreX + 1, centreY + armSize),
Point(centreX - 1, centreY + armSize),
Point(centreX - 1, centreY + 1),
Point(centreX - armSize, centreY + 1),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_MINUS) {
Point pts[] = {
Point(centreX - armSize, centreY - 1),
Point(centreX + armSize, centreY -1),
Point(centreX + armSize, centreY +1),
Point(centreX - armSize, centreY + 1),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
} else if (markType == SC_MARK_SMALLRECT) {
PRectangle rcSmall;
rcSmall.left = rc.left + 1;
rcSmall.top = rc.top + 2;
rcSmall.right = rc.right - 1;
rcSmall.bottom = rc.bottom - 2;
surface->RectangleDraw(rcSmall, fore.allocated, back.allocated);
} else if (markType == SC_MARK_EMPTY) {
// An invisible marker so don't draw anything
} else if (markType == SC_MARK_VLINE) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rcWhole.bottom);
} else if (markType == SC_MARK_LCORNER) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rc.top + dimOn2);
surface->LineTo(rc.right - 2, rc.top + dimOn2);
} else if (markType == SC_MARK_TCORNER) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rc.top + dimOn2);
surface->LineTo(rc.right - 2, rc.top + dimOn2);
} else if (markType == SC_MARK_LCORNERCURVE) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rc.top + dimOn2-3);
surface->LineTo(centreX+3, rc.top + dimOn2);
surface->LineTo(rc.right - 1, rc.top + dimOn2);
} else if (markType == SC_MARK_TCORNERCURVE) {
surface->PenColour(back.allocated);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rc.top + dimOn2-3);
surface->LineTo(centreX+3, rc.top + dimOn2);
surface->LineTo(rc.right - 1, rc.top + dimOn2);
} else if (markType == SC_MARK_BOXPLUS) {
surface->PenColour(back.allocated);
DrawBox(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
DrawPlus(surface, centreX, centreY, blobSize, back.allocated);
} else if (markType == SC_MARK_BOXPLUSCONNECTED) {
surface->PenColour(back.allocated);
DrawBox(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
DrawPlus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, centreY - blobSize);
} else if (markType == SC_MARK_BOXMINUS) {
surface->PenColour(back.allocated);
DrawBox(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
DrawMinus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
} else if (markType == SC_MARK_BOXMINUSCONNECTED) {
surface->PenColour(back.allocated);
DrawBox(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
DrawMinus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, centreY - blobSize);
} else if (markType == SC_MARK_CIRCLEPLUS) {
DrawCircle(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
surface->PenColour(back.allocated);
DrawPlus(surface, centreX, centreY, blobSize, back.allocated);
} else if (markType == SC_MARK_CIRCLEPLUSCONNECTED) {
DrawCircle(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
surface->PenColour(back.allocated);
DrawPlus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, centreY - blobSize);
} else if (markType == SC_MARK_CIRCLEMINUS) {
DrawCircle(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
surface->PenColour(back.allocated);
DrawMinus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
} else if (markType == SC_MARK_CIRCLEMINUSCONNECTED) {
DrawCircle(surface, centreX, centreY, blobSize, fore.allocated, back.allocated);
surface->PenColour(back.allocated);
DrawMinus(surface, centreX, centreY, blobSize, back.allocated);
surface->MoveTo(centreX, centreY + blobSize);
surface->LineTo(centreX, rcWhole.bottom);
surface->MoveTo(centreX, rcWhole.top);
surface->LineTo(centreX, centreY - blobSize);
} else { // SC_MARK_SHORTARROW
Point pts[] = {
Point(centreX, centreY + dimOn2),
Point(centreX + dimOn2, centreY),
Point(centreX, centreY - dimOn2),
Point(centreX, centreY - dimOn4),
Point(centreX - dimOn4, centreY - dimOn4),
Point(centreX - dimOn4, centreY + dimOn4),
Point(centreX, centreY + dimOn4),
Point(centreX, centreY + dimOn2),
};
surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]),
fore.allocated, back.allocated);
}
}
<|endoftext|>
|
<commit_before>#include "MPLauncher.h"
MPLauncher::MPLauncher(void)
: BWindow(BRect(100, 100, 650, 400), "MasterPiece Launcher", B_TITLED_WINDOW, B_NOT_H_RESIZABLE | B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS, B_CURRENT_WORKSPACE)
{
mainGroup = new BGroupLayout(B_HORIZONTAL, 0.0);
newThoughtButton = new BButton(BRect(10, 10, 90, 35), NULL, "Create a New...", new BMessage(CREATE_NEW_THT), B_FOLLOW_NONE, B_WILL_DRAW);
newMasterpieceButton = new BButton(BRect(10, 10, 90, 35), NULL, "Create a New...", new BMessage(CREATE_NEW_MP), B_FOLLOW_NONE, B_WILL_DRAW);
thoughtStringView = new BStringView(BRect(10, 10, 200, 30), NULL, "Work on a Thought");
masterpieceStringView = new BStringView(BRect(10, 10, 200, 30), NULL, "Work on a Masterpiece");
openMasterpieceStringView = new BStringView(BRect(10, 10, 200, 30), NULL, "Open an Existing...");
openThoughtStringView = new BStringView(BRect(10, 10, 200, 30), NULL, "Open an Existing...");
openThoughtListView = new BListView(BRect(10, 10, 100, 30), NULL, B_SINGLE_SELECTION_LIST, B_FOLLOW_ALL, B_WILL_DRAW);
openMasterpieceListView = new BListView(BRect(10, 10, 100, 30), NULL, B_SINGLE_SELECTION_LIST, B_FOLLOW_ALL, B_WILL_DRAW);
backView = new BView(Bounds(), "backview", B_FOLLOW_ALL, B_WILL_DRAW);
backView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
AddChild(backView);
backView->SetLayout(mainGroup);
backView->AddChild(BGridLayoutBuilder()
.Add(masterpieceStringView, 0, 0)
.Add(BSpaceLayoutItem::CreateGlue(), 1, 0)
.Add(thoughtStringView, 2, 0)
.Add(BSpaceLayoutItem::CreateGlue(), 3, 0)
.Add(newMasterpieceButton, 0, 1)
.Add(BSpaceLayoutItem::CreateGlue(), 1, 0)
.Add(newThoughtButton, 2, 1)
.Add(openMasterpieceStringView, 0, 2)
.Add(BSpaceLayoutItem::CreateGlue(), 1, 2)
.Add(openThoughtStringView, 2, 2)
.Add(BSpaceLayoutItem::CreateGlue(), 3, 2)
.Add(new BScrollView("scroll_masterpiecelist", openMasterpieceListView, B_FOLLOW_ALL_SIDES, 0, false, true, B_FANCY_BORDER), 0, 3, 2, 3)
.Add(new BScrollView("scroll_thoughtlist", openThoughtListView, B_FOLLOW_ALL_SIDES, 0, false, true, B_FANCY_BORDER), 2, 3, 2, 3)
.SetInsets(5, 5, 5, 2)
);
openMasterpieceListView->SetInvocationMessage(new BMessage(OPEN_EXISTING_MP));
openThoughtListView->SetInvocationMessage(new BMessage(OPEN_EXISTING_THT));
OpenMasterpieceDB();
}
void MPLauncher::MessageReceived(BMessage* msg)
{
switch(msg->what)
{
case CREATE_NEW_MP:
mpBuilder = new MPBuilder(BMessage(SHOW_LAUNCHER), BMessenger(this), "MasterPiece Builder - untitled");
mpBuilder->Show();
this->Hide();
// do something here
break;
case CREATE_NEW_THT:
mpEditor = new MPEditor(BMessage(SHOW_LAUNCHER), BMessenger(this), "MasterPiece Editor - untitled");
mpEditor->Show();
this->Hide();
// do something here
break;
case OPEN_EXISTING_MP:
// do something here
break;
case OPEN_EXISTING_THT:
// do something here
break;
case SHOW_LAUNCHER:
// do something here
if(msg->FindInt64("showLauncher", &showLauncher) == B_OK)
{
if(showLauncher == 1)
{
this->Show();
}
else if(showLauncher == 0)
{
this->Hide();
}
else
{
eAlert = new ErrorAlert("Message is not 0 or 1");
eAlert->Launch();
// big error must display
}
}
else
{
eAlert = new ErrorAlert("Message is not right");
eAlert->Launch();
}
break;
default:
{
BWindow::MessageReceived(msg);
break;
}
}
}
bool MPLauncher::QuitRequested(void)
{
be_app->PostMessage(B_QUIT_REQUESTED);
return true;
}
void MPLauncher::OpenMasterpieceDB()
{
sqlErrMsg = 0;
app_info info;
be_app->GetAppInfo(&info);
BPath path(&info.ref);
path.GetParent(&path);
BString tmpPath = path.Path();
tmpPath += "/MasterPiece.db";
sqlValue = sqlite3_open_v2(tmpPath, &mpdb, SQLITE_OPEN_READWRITE, NULL); // open db
if(sqlite3_errcode(mpdb) == 14) // if error is SQLITE_CANTOPEN, then create db with structure
{
sqlValue = sqlite3_open_v2(tmpPath, &mpdb, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
if(sqlite3_errcode(mpdb) == 0) // sqlite_ok
{
tmpString = "CREATE TABLE ideatable(ideaid integer primary key autoincrement, ideaname text, ideatext text, ismp integer, mpid integer, ordernumber integer);";
sqlValue = sqlite3_exec(mpdb, tmpString, NULL, NULL, &sqlErrMsg);
if(sqlValue == SQLITE_OK) // if sql was successful
{
eAlert = new ErrorAlert("sql was created successfully");
eAlert->Launch();
// ladida...
}
else // sql not successful
{
eAlert = new ErrorAlert("1.1 Sql Error: ", sqlErrMsg);
eAlert->Launch();
}
}
else // some kind of failure
{
eAlert = new ErrorAlert("1.0 Sql Error: ", sqlite3_errmsg(mpdb));
eAlert->Launch();
}
}
else if(sqlite3_errcode(mpdb) == 0) // sqlite_OK, it exists
{
eAlert = new ErrorAlert("sql was found.");
eAlert->Launch();
// ladida
}
else // if error is not ok or not existing, then display error in alert
{
eAlert = new ErrorAlert("1.2 Sql Error: ", sqlite3_errmsg(mpdb));
eAlert->Launch();
}
}
<commit_msg>mplauncher functionaltiy to open editor or builder window is complete. just need to launch sql required to make it really work<commit_after>#include "MPLauncher.h"
MPLauncher::MPLauncher(void)
: BWindow(BRect(100, 100, 650, 400), "MasterPiece Launcher", B_TITLED_WINDOW, B_NOT_H_RESIZABLE | B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS, B_CURRENT_WORKSPACE)
{
mainGroup = new BGroupLayout(B_HORIZONTAL, 0.0);
newThoughtButton = new BButton(BRect(10, 10, 90, 35), NULL, "Create a New...", new BMessage(CREATE_NEW_THT), B_FOLLOW_NONE, B_WILL_DRAW);
newMasterpieceButton = new BButton(BRect(10, 10, 90, 35), NULL, "Create a New...", new BMessage(CREATE_NEW_MP), B_FOLLOW_NONE, B_WILL_DRAW);
thoughtStringView = new BStringView(BRect(10, 10, 200, 30), NULL, "Work on a Thought");
masterpieceStringView = new BStringView(BRect(10, 10, 200, 30), NULL, "Work on a Masterpiece");
openMasterpieceStringView = new BStringView(BRect(10, 10, 200, 30), NULL, "Open an Existing...");
openThoughtStringView = new BStringView(BRect(10, 10, 200, 30), NULL, "Open an Existing...");
openThoughtListView = new BListView(BRect(10, 10, 100, 30), NULL, B_SINGLE_SELECTION_LIST, B_FOLLOW_ALL, B_WILL_DRAW);
openMasterpieceListView = new BListView(BRect(10, 10, 100, 30), NULL, B_SINGLE_SELECTION_LIST, B_FOLLOW_ALL, B_WILL_DRAW);
backView = new BView(Bounds(), "backview", B_FOLLOW_ALL, B_WILL_DRAW);
backView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
AddChild(backView);
backView->SetLayout(mainGroup);
backView->AddChild(BGridLayoutBuilder()
.Add(masterpieceStringView, 0, 0)
.Add(BSpaceLayoutItem::CreateGlue(), 1, 0)
.Add(thoughtStringView, 2, 0)
.Add(BSpaceLayoutItem::CreateGlue(), 3, 0)
.Add(newMasterpieceButton, 0, 1)
.Add(BSpaceLayoutItem::CreateGlue(), 1, 0)
.Add(newThoughtButton, 2, 1)
.Add(openMasterpieceStringView, 0, 2)
.Add(BSpaceLayoutItem::CreateGlue(), 1, 2)
.Add(openThoughtStringView, 2, 2)
.Add(BSpaceLayoutItem::CreateGlue(), 3, 2)
.Add(new BScrollView("scroll_masterpiecelist", openMasterpieceListView, B_FOLLOW_ALL_SIDES, 0, false, true, B_FANCY_BORDER), 0, 3, 2, 3)
.Add(new BScrollView("scroll_thoughtlist", openThoughtListView, B_FOLLOW_ALL_SIDES, 0, false, true, B_FANCY_BORDER), 2, 3, 2, 3)
.SetInsets(5, 5, 5, 2)
);
openMasterpieceListView->SetInvocationMessage(new BMessage(OPEN_EXISTING_MP));
openThoughtListView->SetInvocationMessage(new BMessage(OPEN_EXISTING_THT));
OpenMasterpieceDB();
}
void MPLauncher::MessageReceived(BMessage* msg)
{
switch(msg->what)
{
case CREATE_NEW_MP:
mpBuilder = new MPBuilder(BMessage(SHOW_LAUNCHER), BMessenger(this), "MasterPiece Builder - untitled");
mpBuilder->Show();
this->Hide();
// do something here
break;
case CREATE_NEW_THT:
mpEditor = new MPEditor(BMessage(SHOW_LAUNCHER), BMessenger(this), "MasterPiece Editor - untitled");
mpEditor->Show();
this->Hide();
// do something here
break;
case OPEN_EXISTING_MP:
mpBuilder = new MPBuilder(BMessage(SHOW_LAUNCHER), BMessenger(this), "MasterPiece Builder - untitled");
mpBuilder->Show();
this->Hide();
// do something here
break;
case OPEN_EXISTING_THT:
mpEditor = new MPEditor(BMessage(SHOW_LAUNCHER), BMessenger(this), "MasterPiece Editor - untitled");
mpEditor->Show();
this->Hide();
// do something here
break;
case SHOW_LAUNCHER:
// do something here
if(msg->FindInt64("showLauncher", &showLauncher) == B_OK)
{
if(showLauncher == 1)
{
this->Show();
}
else if(showLauncher == 0)
{
this->Hide();
}
else
{
eAlert = new ErrorAlert("Message is not 0 or 1");
eAlert->Launch();
// big error must display
}
}
else
{
eAlert = new ErrorAlert("Message is not right");
eAlert->Launch();
}
break;
default:
{
BWindow::MessageReceived(msg);
break;
}
}
}
bool MPLauncher::QuitRequested(void)
{
be_app->PostMessage(B_QUIT_REQUESTED);
return true;
}
void MPLauncher::OpenMasterpieceDB()
{
sqlErrMsg = 0;
app_info info;
be_app->GetAppInfo(&info);
BPath path(&info.ref);
path.GetParent(&path);
BString tmpPath = path.Path();
tmpPath += "/MasterPiece.db";
sqlValue = sqlite3_open_v2(tmpPath, &mpdb, SQLITE_OPEN_READWRITE, NULL); // open db
if(sqlite3_errcode(mpdb) == 14) // if error is SQLITE_CANTOPEN, then create db with structure
{
sqlValue = sqlite3_open_v2(tmpPath, &mpdb, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
if(sqlite3_errcode(mpdb) == 0) // sqlite_ok
{
tmpString = "CREATE TABLE ideatable(ideaid integer primary key autoincrement, ideaname text, ideatext text, ismp integer, mpid integer, ordernumber integer);";
sqlValue = sqlite3_exec(mpdb, tmpString, NULL, NULL, &sqlErrMsg);
if(sqlValue == SQLITE_OK) // if sql was successful
{
eAlert = new ErrorAlert("sql was created successfully");
eAlert->Launch();
// ladida...
}
else // sql not successful
{
eAlert = new ErrorAlert("1.1 Sql Error: ", sqlErrMsg);
eAlert->Launch();
}
}
else // some kind of failure
{
eAlert = new ErrorAlert("1.0 Sql Error: ", sqlite3_errmsg(mpdb));
eAlert->Launch();
}
}
else if(sqlite3_errcode(mpdb) == 0) // sqlite_OK, it exists
{
eAlert = new ErrorAlert("sql was found.");
eAlert->Launch();
// ladida
}
else // if error is not ok or not existing, then display error in alert
{
eAlert = new ErrorAlert("1.2 Sql Error: ", sqlite3_errmsg(mpdb));
eAlert->Launch();
}
}
<|endoftext|>
|
<commit_before>#include <MQTTClient.h>
void messageArrived(MQTT::MessageData& messageData) {
MQTT::Message &message = messageData.message;
char * topic = messageData.topicName.lenstring.data;
messageReceived(String(topic), (char*)message.payload, message.payloadlen);
}
MQTTClient::MQTTClient(const char * _hostname, int _port, Client& _client) {
this->network.setClient(&_client);
//TODO: find a way to use dynamic allocation
this->client = new MQTT::Client<Network, Timer, MQTT_BUFFER_SIZE>(this->network);
this->hostname = _hostname;
this->port = _port;
}
boolean MQTTClient::connect(const char * clientId) {
return this->connect(clientId, "", "");
}
boolean MQTTClient::connect(const char * clientId, const char * username, const char * password) {
if(!this->network.connect((char*)this->hostname, this->port)) {
return false;
}
MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
data.clientID.cstring = (char*)clientId;
if(username && password) {
data.username.cstring = (char*)username;
data.password.cstring = (char*)password;
}
return this->client->connect(data) == 0;
}
boolean MQTTClient::publish(const char * topic, String payload) {
return this->publish(topic, payload.c_str());
}
boolean MQTTClient::publish(const char * topic, const char * payload) {
MQTT::Message message;
message.qos = MQTT::QOS0;
message.retained = false;
message.dup = false;
message.payload = (char*)payload;
message.payloadlen = strlen(payload);
return client->publish(topic, message) == 0;
}
boolean MQTTClient::subscribe(const char * topic) {
return client->subscribe(topic, MQTT::QOS0, messageArrived) == 0;
}
boolean MQTTClient::unsubscribe(const char * topic) {
return client->unsubscribe(topic) == 0;
}
boolean MQTTClient::loop() {
this->client->yield();
}
boolean MQTTClient::connected() {
return this->client->isConnected();
}
void MQTTClient::disconnect() {
this->client->disconnect();
}
<commit_msg>fixed topic string bug<commit_after>#include <MQTTClient.h>
void messageArrived(MQTT::MessageData& messageData) {
MQTT::Message &message = messageData.message;
int len = messageData.topicName.lenstring.len;
char topic[len+1];
memcpy(topic, messageData.topicName.lenstring.data, len);
topic[len] = '\0';
messageReceived(String(topic), (char*)message.payload, message.payloadlen);
}
MQTTClient::MQTTClient(const char * _hostname, int _port, Client& _client) {
this->client = new MQTT::Client<Network, Timer, MQTT_BUFFER_SIZE>(this->network);
this->network.setClient(&_client);
this->hostname = _hostname;
this->port = _port;
}
boolean MQTTClient::connect(const char * clientId) {
return this->connect(clientId, "", "");
}
boolean MQTTClient::connect(const char * clientId, const char * username, const char * password) {
if(!this->network.connect((char*)this->hostname, this->port)) {
return false;
}
MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
data.clientID.cstring = (char*)clientId;
if(username && password) {
data.username.cstring = (char*)username;
data.password.cstring = (char*)password;
}
return this->client->connect(data) == 0;
}
boolean MQTTClient::publish(const char * topic, String payload) {
return this->publish(topic, payload.c_str());
}
boolean MQTTClient::publish(const char * topic, const char * payload) {
MQTT::Message message;
message.qos = MQTT::QOS0;
message.retained = false;
message.dup = false;
message.payload = (char*)payload;
message.payloadlen = strlen(payload);
return client->publish(topic, message) == 0;
}
boolean MQTTClient::subscribe(const char * topic) {
return client->subscribe(topic, MQTT::QOS0, messageArrived) == 0;
}
boolean MQTTClient::unsubscribe(const char * topic) {
return client->unsubscribe(topic) == 0;
}
boolean MQTTClient::loop() {
this->client->yield();
}
boolean MQTTClient::connected() {
return this->client->isConnected();
}
void MQTTClient::disconnect() {
this->client->disconnect();
}
<|endoftext|>
|
<commit_before>#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QSettings>
#include <QMessageBox>
#include <QDesktopServices>
#include "version.h"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);
QCoreApplication::setOrganizationName("Chainsawkitten");
QCoreApplication::setOrganizationDomain("chainsawkitten.net");
QCoreApplication::setApplicationName("Mute Exceptions");
createStatusBar();
connect(ui->addExceptionButton, SIGNAL(released()), SLOT(addException()));
connect(ui->removeExceptionButton, SIGNAL(released()), SLOT(removeException()));
connect(ui->applyButton, SIGNAL(released()), SLOT(apply()));
connect(ui->actionSettings, SIGNAL(triggered()), SLOT(settings()));
connect(ui->actionCheckUpdates, SIGNAL(triggered()), SLOT(checkUpdates()));
connect(ui->actionAbout, SIGNAL(triggered()), SLOT(about()));
settingsDialog = new SettingsDialog(this);
aboutDialog = new AboutDialog(this);
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
initAudio();
getAudioSessions();
readSettings();
QUrl url("http://muteexceptions.chainsawkitten.net/getVersion.php");
fileDownloader = new FileDownloader(url, this);
connect(fileDownloader, SIGNAL(downloaded()), this, SLOT(versionDownloaded()));
QSettings settings;
settings.beginGroup("Updates");
if (settings.value("checkOnStart", true).toBool())
fileDownloader->start();
settings.endGroup();
}
MainWindow::~MainWindow() {
writeSettings();
delete ui;
delete statusLabel;
delete settingsDialog;
delete aboutDialog;
for (AudioSession* audioSession : mutedSessions) {
delete audioSession;
}
for (AudioSession* audioSession : exceptedSessions) {
delete audioSession;
}
audioSessionManager->Release();
speakers->Release();
deviceEnumerator->Release();
CoUninitialize();
delete fileDownloader;
}
void MainWindow::addException() {
if (!mutedSessions.empty()) {
int index = ui->mutedListWidget->currentRow();
if (index >= 0) {
AudioSession* session = mutedSessions.at(index);
exceptedSessions.push_back(session);
ui->exceptionsListWidget->addItem(session->displayName());
mutedSessions.removeAt(index);
delete ui->mutedListWidget->currentItem();
statusLabel->setText("Added exception.");
}
}
}
void MainWindow::removeException() {
if (!exceptedSessions.empty()) {
int index = ui->exceptionsListWidget->currentRow();
if (index >= 0) {
AudioSession* session = exceptedSessions.at(index);
mutedSessions.push_back(session);
ui->mutedListWidget->addItem(session->displayName());
exceptedSessions.removeAt(index);
delete ui->exceptionsListWidget->currentItem();
statusLabel->setText("Removed exception.");
}
}
}
void MainWindow::apply() {
// Mute all muted.
for (AudioSession* session : mutedSessions) {
session->mute();
}
// Unmute all exceptions.
for (AudioSession* session : exceptedSessions) {
session->unmute();
}
statusLabel->setText("Muting applied.");
}
void MainWindow::settings() {
settingsDialog->readSettings();
int result = settingsDialog->exec();
if (result == QDialog::Accepted)
settingsDialog->writeSettings();
}
void MainWindow::checkUpdates() {
fileDownloader->start();
}
void MainWindow::about() {
aboutDialog->show();
}
void MainWindow::versionDownloaded() {
QString newVersion(fileDownloader->downloadedData());
QString oldVersion(VERSION);
if (oldVersion != newVersion) {
QMessageBox::StandardButton reply = QMessageBox::question(this, "New version available", "A new version is available. Go to website?", QMessageBox::Yes | QMessageBox::No);
if (reply == QMessageBox::Yes) {
QDesktopServices::openUrl(QUrl("http://muteexceptions.chainsawkitten.net/"));
QApplication::quit();
}
}
}
void MainWindow::createStatusBar() {
statusLabel = new QLabel("Started.");
statusBar()->addWidget(statusLabel);
}
void MainWindow::initAudio() {
// Create device enumerator.
HRESULT result = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void**)&deviceEnumerator);
if (result != S_OK) {
statusLabel->setText("Couldn't create device enumerator.");
return;
}
// Get speakers.
result = deviceEnumerator->GetDefaultAudioEndpoint(eRender, eMultimedia, &speakers);
if (result != S_OK) {
statusLabel->setText("Couldn't get default audio endpoint.");
return;
}
// Get session manager.
result = speakers->Activate(__uuidof(IAudioSessionManager2), CLSCTX_ALL, nullptr, (void**)&audioSessionManager);
if (result != S_OK) {
statusLabel->setText("Couldn't activate audio session manager.");
return;
}
}
void MainWindow::getAudioSessions() {
// Get session enumerator.
IAudioSessionEnumerator* sessionEnumerator = nullptr;
HRESULT result = audioSessionManager->GetSessionEnumerator(&sessionEnumerator);
if (result != S_OK) {
statusLabel->setText("Couldn't get audio session enumerator.");
return;
}
// Get sessions.
int sessionCount;
sessionEnumerator->GetCount(&sessionCount);
for (int i=0; i<sessionCount; i++) {
IAudioSessionControl* sessionControl = nullptr;
sessionEnumerator->GetSession(i, &sessionControl);
AudioSession* audioSession = new AudioSession(sessionControl);
mutedSessions.push_back(audioSession);
ui->mutedListWidget->addItem(audioSession->displayName());
sessionControl->Release();
}
sessionEnumerator->Release();
}
void MainWindow::writeSettings() {
QSettings settings;
settings.beginGroup("MainWindow");
settings.setValue("size", size());
settings.setValue("pos", pos());
settings.endGroup();
}
void MainWindow::readSettings() {
QSettings settings;
settings.beginGroup("MainWindow");
resize(settings.value("size", QSize(640, 480)).toSize());
if (settings.contains("pos"))
move(settings.value("pos").toPoint());
settings.endGroup();
}
<commit_msg>More descriptive version message<commit_after>#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QSettings>
#include <QMessageBox>
#include <QDesktopServices>
#include "version.h"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);
QCoreApplication::setOrganizationName("Chainsawkitten");
QCoreApplication::setOrganizationDomain("chainsawkitten.net");
QCoreApplication::setApplicationName("Mute Exceptions");
createStatusBar();
connect(ui->addExceptionButton, SIGNAL(released()), SLOT(addException()));
connect(ui->removeExceptionButton, SIGNAL(released()), SLOT(removeException()));
connect(ui->applyButton, SIGNAL(released()), SLOT(apply()));
connect(ui->actionSettings, SIGNAL(triggered()), SLOT(settings()));
connect(ui->actionCheckUpdates, SIGNAL(triggered()), SLOT(checkUpdates()));
connect(ui->actionAbout, SIGNAL(triggered()), SLOT(about()));
settingsDialog = new SettingsDialog(this);
aboutDialog = new AboutDialog(this);
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
initAudio();
getAudioSessions();
readSettings();
QUrl url("http://muteexceptions.chainsawkitten.net/getVersion.php");
fileDownloader = new FileDownloader(url, this);
connect(fileDownloader, SIGNAL(downloaded()), this, SLOT(versionDownloaded()));
QSettings settings;
settings.beginGroup("Updates");
if (settings.value("checkOnStart", true).toBool())
fileDownloader->start();
settings.endGroup();
}
MainWindow::~MainWindow() {
writeSettings();
delete ui;
delete statusLabel;
delete settingsDialog;
delete aboutDialog;
for (AudioSession* audioSession : mutedSessions) {
delete audioSession;
}
for (AudioSession* audioSession : exceptedSessions) {
delete audioSession;
}
audioSessionManager->Release();
speakers->Release();
deviceEnumerator->Release();
CoUninitialize();
delete fileDownloader;
}
void MainWindow::addException() {
if (!mutedSessions.empty()) {
int index = ui->mutedListWidget->currentRow();
if (index >= 0) {
AudioSession* session = mutedSessions.at(index);
exceptedSessions.push_back(session);
ui->exceptionsListWidget->addItem(session->displayName());
mutedSessions.removeAt(index);
delete ui->mutedListWidget->currentItem();
statusLabel->setText("Added exception.");
}
}
}
void MainWindow::removeException() {
if (!exceptedSessions.empty()) {
int index = ui->exceptionsListWidget->currentRow();
if (index >= 0) {
AudioSession* session = exceptedSessions.at(index);
mutedSessions.push_back(session);
ui->mutedListWidget->addItem(session->displayName());
exceptedSessions.removeAt(index);
delete ui->exceptionsListWidget->currentItem();
statusLabel->setText("Removed exception.");
}
}
}
void MainWindow::apply() {
// Mute all muted.
for (AudioSession* session : mutedSessions) {
session->mute();
}
// Unmute all exceptions.
for (AudioSession* session : exceptedSessions) {
session->unmute();
}
statusLabel->setText("Muting applied.");
}
void MainWindow::settings() {
settingsDialog->readSettings();
int result = settingsDialog->exec();
if (result == QDialog::Accepted)
settingsDialog->writeSettings();
}
void MainWindow::checkUpdates() {
fileDownloader->start();
}
void MainWindow::about() {
aboutDialog->show();
}
void MainWindow::versionDownloaded() {
QString newVersion(fileDownloader->downloadedData());
QString oldVersion(VERSION);
if (oldVersion != newVersion) {
QString message = "A new version is available.\n\nCurrent version: " + oldVersion + "\nNew version: " + newVersion + "\n\nGo to website?";
QMessageBox::StandardButton reply = QMessageBox::question(this, "New version available", message, QMessageBox::Yes | QMessageBox::No);
if (reply == QMessageBox::Yes) {
QDesktopServices::openUrl(QUrl("http://muteexceptions.chainsawkitten.net/"));
QApplication::quit();
}
}
}
void MainWindow::createStatusBar() {
statusLabel = new QLabel("Started.");
statusBar()->addWidget(statusLabel);
}
void MainWindow::initAudio() {
// Create device enumerator.
HRESULT result = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void**)&deviceEnumerator);
if (result != S_OK) {
statusLabel->setText("Couldn't create device enumerator.");
return;
}
// Get speakers.
result = deviceEnumerator->GetDefaultAudioEndpoint(eRender, eMultimedia, &speakers);
if (result != S_OK) {
statusLabel->setText("Couldn't get default audio endpoint.");
return;
}
// Get session manager.
result = speakers->Activate(__uuidof(IAudioSessionManager2), CLSCTX_ALL, nullptr, (void**)&audioSessionManager);
if (result != S_OK) {
statusLabel->setText("Couldn't activate audio session manager.");
return;
}
}
void MainWindow::getAudioSessions() {
// Get session enumerator.
IAudioSessionEnumerator* sessionEnumerator = nullptr;
HRESULT result = audioSessionManager->GetSessionEnumerator(&sessionEnumerator);
if (result != S_OK) {
statusLabel->setText("Couldn't get audio session enumerator.");
return;
}
// Get sessions.
int sessionCount;
sessionEnumerator->GetCount(&sessionCount);
for (int i=0; i<sessionCount; i++) {
IAudioSessionControl* sessionControl = nullptr;
sessionEnumerator->GetSession(i, &sessionControl);
AudioSession* audioSession = new AudioSession(sessionControl);
mutedSessions.push_back(audioSession);
ui->mutedListWidget->addItem(audioSession->displayName());
sessionControl->Release();
}
sessionEnumerator->Release();
}
void MainWindow::writeSettings() {
QSettings settings;
settings.beginGroup("MainWindow");
settings.setValue("size", size());
settings.setValue("pos", pos());
settings.endGroup();
}
void MainWindow::readSettings() {
QSettings settings;
settings.beginGroup("MainWindow");
resize(settings.value("size", QSize(640, 480)).toSize());
if (settings.contains("pos"))
move(settings.value("pos").toPoint());
settings.endGroup();
}
<|endoftext|>
|
<commit_before>#include <babylon/loading/scene_loader_progress_event.h>
#include <babylon/loading/progress_event.h>
namespace BABYLON {
SceneLoaderProgressEvent::SceneLoaderProgressEvent(bool lengthComputable,
size_t loaded, size_t total)
: lengthComputable{this, &SceneLoaderProgressEvent::get_lengthComputable}
, loaded{this, &SceneLoaderProgressEvent::get_loaded}
, total{this, &SceneLoaderProgressEvent::get_total}
, _lengthComputable{lengthComputable}
, _loaded{loaded}
, _total{total}
{
}
SceneLoaderProgressEvent::SceneLoaderProgressEvent(
const SceneLoaderProgressEvent& other)
: lengthComputable{this, &SceneLoaderProgressEvent::get_lengthComputable}
, loaded{this, &SceneLoaderProgressEvent::get_loaded}
, total{this, &SceneLoaderProgressEvent::get_total}
, _lengthComputable{other.lengthComputable}
, _loaded{other.loaded}
, _total{other.total}
{
}
SceneLoaderProgressEvent::SceneLoaderProgressEvent(
SceneLoaderProgressEvent&& other)
: lengthComputable{this, &SceneLoaderProgressEvent::get_lengthComputable}
, loaded{this, &SceneLoaderProgressEvent::get_loaded}
, total{this, &SceneLoaderProgressEvent::get_total}
, _lengthComputable{std::move(other.lengthComputable)}
, _loaded{std::move(other.loaded)}
, _total{std::move(other.total)}
{
}
SceneLoaderProgressEvent& SceneLoaderProgressEvent::
operator=(const SceneLoaderProgressEvent& other)
{
if (&other != this) {
_lengthComputable = other.lengthComputable;
_loaded = other.loaded;
_total = other.total;
}
return *this;
}
SceneLoaderProgressEvent& SceneLoaderProgressEvent::
operator=(SceneLoaderProgressEvent&& other)
{
if (&other != this) {
_lengthComputable = std::move(other.lengthComputable);
_loaded = std::move(other.loaded);
_total = std::move(other.total);
}
return *this;
}
SceneLoaderProgressEvent::~SceneLoaderProgressEvent() = default;
bool SceneLoaderProgressEvent::get_lengthComputable() const
{
return _lengthComputable;
}
size_t SceneLoaderProgressEvent::get_loaded() const
{
return _loaded;
}
size_t SceneLoaderProgressEvent::get_total() const
{
return _total;
}
SceneLoaderProgressEvent
SceneLoaderProgressEvent::FromProgressEvent(const ProgressEvent& event)
{
return SceneLoaderProgressEvent(event.lengthComputable, event.loaded,
event.total);
}
} // end of namespace BABYLON
<commit_msg>Formatting<commit_after>#include <babylon/loading/scene_loader_progress_event.h>
#include <babylon/loading/progress_event.h>
namespace BABYLON {
SceneLoaderProgressEvent::SceneLoaderProgressEvent(bool lengthComputable, size_t loaded,
size_t total)
: lengthComputable{this, &SceneLoaderProgressEvent::get_lengthComputable}
, loaded{this, &SceneLoaderProgressEvent::get_loaded}
, total{this, &SceneLoaderProgressEvent::get_total}
, _lengthComputable{lengthComputable}
, _loaded{loaded}
, _total{total}
{
}
SceneLoaderProgressEvent::SceneLoaderProgressEvent(const SceneLoaderProgressEvent& other)
: lengthComputable{this, &SceneLoaderProgressEvent::get_lengthComputable}
, loaded{this, &SceneLoaderProgressEvent::get_loaded}
, total{this, &SceneLoaderProgressEvent::get_total}
, _lengthComputable{other.lengthComputable}
, _loaded{other.loaded}
, _total{other.total}
{
}
SceneLoaderProgressEvent::SceneLoaderProgressEvent(SceneLoaderProgressEvent&& other)
: lengthComputable{this, &SceneLoaderProgressEvent::get_lengthComputable}
, loaded{this, &SceneLoaderProgressEvent::get_loaded}
, total{this, &SceneLoaderProgressEvent::get_total}
, _lengthComputable{std::move(other.lengthComputable)}
, _loaded{std::move(other.loaded)}
, _total{std::move(other.total)}
{
}
SceneLoaderProgressEvent& SceneLoaderProgressEvent::operator=(const SceneLoaderProgressEvent& other)
{
if (&other != this) {
_lengthComputable = other.lengthComputable;
_loaded = other.loaded;
_total = other.total;
}
return *this;
}
SceneLoaderProgressEvent& SceneLoaderProgressEvent::operator=(SceneLoaderProgressEvent&& other)
{
if (&other != this) {
_lengthComputable = std::move(other.lengthComputable);
_loaded = std::move(other.loaded);
_total = std::move(other.total);
}
return *this;
}
SceneLoaderProgressEvent::~SceneLoaderProgressEvent() = default;
bool SceneLoaderProgressEvent::get_lengthComputable() const
{
return _lengthComputable;
}
size_t SceneLoaderProgressEvent::get_loaded() const
{
return _loaded;
}
size_t SceneLoaderProgressEvent::get_total() const
{
return _total;
}
SceneLoaderProgressEvent SceneLoaderProgressEvent::FromProgressEvent(const ProgressEvent& event)
{
return SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
}
} // end of namespace BABYLON
<|endoftext|>
|
<commit_before>//Copyright (c) 2018 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include <algorithm>
#include <limits>
#include "Application.h" //To get settings.
#include "ExtruderTrain.h"
#include "gcodeExport.h"
#include "infill.h"
#include "LayerPlan.h"
#include "PrimeTower.h"
#include "PrintFeature.h"
#include "raft.h"
#include "sliceDataStorage.h"
#define CIRCLE_RESOLUTION 32 //The number of vertices in each circle.
namespace cura
{
PrimeTower::PrimeTower()
: wipe_from_middle(false)
{
const Scene& scene = Application::getInstance().current_slice->scene;
enabled = scene.current_mesh_group->settings.get<bool>("prime_tower_enable")
&& scene.current_mesh_group->settings.get<coord_t>("prime_tower_min_volume") > 10
&& scene.current_mesh_group->settings.get<coord_t>("prime_tower_size") > 10;
extruder_count = scene.extruders.size();
extruder_order.resize(extruder_count);
for (unsigned int extruder_nr = 0; extruder_nr < extruder_count; extruder_nr++)
{
extruder_order[extruder_nr] = extruder_nr; //Start with default order, then sort.
}
//Sort from high adhesion to low adhesion.
const Scene* scene_pointer = &scene; //Communicate to lambda via pointer to prevent copy.
std::stable_sort(extruder_order.begin(), extruder_order.end(), [scene_pointer](const unsigned int& extruder_nr_a, const unsigned int& extruder_nr_b) -> bool
{
const Ratio adhesion_a = scene_pointer->extruders[extruder_nr_a].settings.get<Ratio>("material_adhesion_tendency");
const Ratio adhesion_b = scene_pointer->extruders[extruder_nr_b].settings.get<Ratio>("material_adhesion_tendency");
return adhesion_a < adhesion_b;
});
}
void PrimeTower::generateGroundpoly()
{
if (!enabled)
{
return;
}
const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings;
const coord_t tower_size = mesh_group_settings.get<coord_t>("prime_tower_size");
const bool circular_prime_tower = mesh_group_settings.get<bool>("prime_tower_circular");
const Settings& brim_extruder_settings = mesh_group_settings.get<ExtruderTrain&>("adhesion_extruder_nr").settings;
const coord_t offset = (! mesh_group_settings.get<bool>("prime_tower_brim_enable")) ? 0 :
brim_extruder_settings.get<size_t>("brim_line_count") *
brim_extruder_settings.get<coord_t>("skirt_brim_line_width") *
brim_extruder_settings.get<Ratio>("initial_layer_line_width_factor");
PolygonRef p = outer_poly.newPoly();
int tower_distance = 0;
const coord_t x = mesh_group_settings.get<coord_t>("prime_tower_position_x") - offset;
const coord_t y = mesh_group_settings.get<coord_t>("prime_tower_position_y") - offset;
if (circular_prime_tower)
{
const coord_t tower_radius = tower_size / 2;
for (unsigned int i = 0; i < CIRCLE_RESOLUTION; i++)
{
const double angle = (double) i / CIRCLE_RESOLUTION * 2 * M_PI; //In radians.
p.add(Point(x - tower_radius + tower_distance + cos(angle) * tower_radius,
y + tower_radius + tower_distance + sin(angle) * tower_radius));
}
}
else
{
p.add(Point(x + tower_distance, y + tower_distance));
p.add(Point(x + tower_distance, y + tower_distance + tower_size));
p.add(Point(x + tower_distance - tower_size, y + tower_distance + tower_size));
p.add(Point(x + tower_distance - tower_size, y + tower_distance));
}
middle = Point(x - tower_size / 2, y + tower_size / 2);
post_wipe_point = Point(x + tower_distance - tower_size / 2, y + tower_distance + tower_size / 2);
outer_poly_first_layer = outer_poly.offset(offset);
}
void PrimeTower::generatePaths(const SliceDataStorage& storage)
{
enabled &= storage.max_print_height_second_to_last_extruder >= 0; //Maybe it turns out that we don't need a prime tower after all because there are no layer switches.
if (enabled)
{
generatePaths_denseInfill();
generateStartLocations();
}
}
void PrimeTower::generatePaths_denseInfill()
{
const Scene& scene = Application::getInstance().current_slice->scene;
const Settings& mesh_group_settings = scene.current_mesh_group->settings;
const coord_t layer_height = mesh_group_settings.get<coord_t>("layer_height");
pattern_per_extruder.resize(extruder_count);
coord_t cumulative_inset = 0; //Each tower shape is going to be printed inside the other. This is the inset we're doing for each extruder.
for (size_t extruder_nr : extruder_order)
{
const coord_t line_width = scene.extruders[extruder_nr].settings.get<coord_t>("prime_tower_line_width");
const coord_t required_volume = scene.extruders[extruder_nr].settings.get<double>("prime_tower_min_volume") * 1000000000; //To cubic microns.
const Ratio flow = scene.extruders[extruder_nr].settings.get<Ratio>("prime_tower_flow");
coord_t current_volume = 0;
ExtrusionMoves& pattern = pattern_per_extruder[extruder_nr];
//Create the walls of the prime tower.
unsigned int wall_nr = 0;
for (; current_volume < required_volume; wall_nr++)
{
//Create a new polygon with an offset from the outer polygon.
Polygons polygons = outer_poly.offset(-cumulative_inset - wall_nr * line_width - line_width / 2);
pattern.polygons.add(polygons);
current_volume += polygons.polygonLength() * line_width * layer_height * flow;
if (polygons.empty()) //Don't continue. We won't ever reach the required volume because it doesn't fit.
{
break;
}
}
cumulative_inset += wall_nr * line_width;
//Generate the pattern for the first layer.
coord_t line_width_layer0 = line_width;
if (mesh_group_settings.get<EPlatformAdhesion>("adhesion_type") != EPlatformAdhesion::RAFT)
{
line_width_layer0 *= scene.extruders[extruder_nr].settings.get<Ratio>("initial_layer_line_width_factor");
}
pattern_per_extruder_layer0.emplace_back();
ExtrusionMoves& pattern_layer0 = pattern_per_extruder_layer0.back();
// Generate a concentric infill pattern in the form insets for the prime tower's first layer instead of using
// the infill pattern because the infill pattern tries to connect polygons in different insets which causes the
// first layer of the prime tower to not stick well.
Polygons inset = outer_poly.offset(-line_width_layer0 / 2);
while (!inset.empty())
{
pattern_layer0.polygons.add(inset);
inset = inset.offset(-line_width_layer0);
}
}
}
void PrimeTower::generateStartLocations()
{
// Evenly spread out a number of dots along the prime tower's outline. This is done for the complete outline,
// so use the same start and end segments for this.
PolygonsPointIndex segment_start = PolygonsPointIndex(&outer_poly, 0, 0);
PolygonsPointIndex segment_end = segment_start;
PolygonUtils::spreadDots(segment_start, segment_end, number_of_prime_tower_start_locations, prime_tower_start_locations);
}
void PrimeTower::addToGcode(const SliceDataStorage& storage, LayerPlan& gcode_layer, const int prev_extruder, const int new_extruder) const
{
if (!enabled)
{
return;
}
if (gcode_layer.getPrimeTowerIsPlanned(new_extruder))
{ // don't print the prime tower if it has been printed already with this extruder.
return;
}
const LayerIndex layer_nr = gcode_layer.getLayerNr();
if (layer_nr > storage.max_print_height_second_to_last_extruder + 1)
{
return;
}
bool post_wipe = Application::getInstance().current_slice->scene.extruders[prev_extruder].settings.get<bool>("prime_tower_wipe_enabled");
// Do not wipe on the first layer, we will generate non-hollow prime tower there for better bed adhesion.
if (prev_extruder == new_extruder || layer_nr == 0)
{
post_wipe = false;
}
// Go to the start location if it's not the first layer
if (layer_nr != 0)
{
gotoStartLocation(gcode_layer, new_extruder);
}
addToGcode_denseInfill(gcode_layer, new_extruder);
// post-wipe:
if (post_wipe)
{
//Make sure we wipe the old extruder on the prime tower.
const Settings& previous_settings = Application::getInstance().current_slice->scene.extruders[prev_extruder].settings;
const Point previous_nozzle_offset = Point(previous_settings.get<coord_t>("machine_nozzle_offset_x"), previous_settings.get<coord_t>("machine_nozzle_offset_y"));
const Settings& new_settings = Application::getInstance().current_slice->scene.extruders[new_extruder].settings;
const Point new_nozzle_offset = Point(new_settings.get<coord_t>("machine_nozzle_offset_x"), new_settings.get<coord_t>("machine_nozzle_offset_y"));
gcode_layer.addTravel(post_wipe_point - previous_nozzle_offset + new_nozzle_offset);
}
gcode_layer.setPrimeTowerIsPlanned(new_extruder);
}
void PrimeTower::addToGcode_denseInfill(LayerPlan& gcode_layer, const size_t extruder_nr) const
{
const ExtrusionMoves& pattern = (gcode_layer.getLayerNr() == -static_cast<LayerIndex>(Raft::getFillerLayerCount()))
? pattern_per_extruder_layer0[extruder_nr]
: pattern_per_extruder[extruder_nr];
const GCodePathConfig& config = gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr];
gcode_layer.addPolygonsByOptimizer(pattern.polygons, config);
gcode_layer.addLinesByOptimizer(pattern.lines, config, SpaceFillType::Lines);
}
void PrimeTower::subtractFromSupport(SliceDataStorage& storage)
{
const Polygons outside_polygon = outer_poly.getOutsidePolygons();
AABB outside_polygon_boundary_box(outside_polygon);
for(size_t layer = 0; layer <= (size_t)storage.max_print_height_second_to_last_extruder + 1 && layer < storage.support.supportLayers.size(); layer++)
{
SupportLayer& support_layer = storage.support.supportLayers[layer];
// take the differences of the support infill parts and the prime tower area
support_layer.excludeAreasFromSupportInfillAreas(outside_polygon, outside_polygon_boundary_box);
}
}
void PrimeTower::gotoStartLocation(LayerPlan& gcode_layer, const int extruder_nr) const
{
int current_start_location_idx = ((((extruder_nr + 1) * gcode_layer.getLayerNr()) % number_of_prime_tower_start_locations)
+ number_of_prime_tower_start_locations) % number_of_prime_tower_start_locations;
const ClosestPolygonPoint wipe_location = prime_tower_start_locations[current_start_location_idx];
const ExtruderTrain& train = Application::getInstance().current_slice->scene.extruders[extruder_nr];
const coord_t inward_dist = train.settings.get<coord_t>("machine_nozzle_size") * 3 / 2 ;
const coord_t start_dist = train.settings.get<coord_t>("machine_nozzle_size") * 2;
const Point prime_end = PolygonUtils::moveInsideDiagonally(wipe_location, inward_dist);
const Point outward_dir = wipe_location.location - prime_end;
const Point prime_start = wipe_location.location + normal(outward_dir, start_dist);
gcode_layer.addTravel(prime_start);
}
}//namespace cura
<commit_msg>Explicitly check for raft on prime-tower-brim. [CURA-5864]<commit_after>//Copyright (c) 2018 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include <algorithm>
#include <limits>
#include "Application.h" //To get settings.
#include "ExtruderTrain.h"
#include "gcodeExport.h"
#include "infill.h"
#include "LayerPlan.h"
#include "PrimeTower.h"
#include "PrintFeature.h"
#include "raft.h"
#include "sliceDataStorage.h"
#define CIRCLE_RESOLUTION 32 //The number of vertices in each circle.
namespace cura
{
PrimeTower::PrimeTower()
: wipe_from_middle(false)
{
const Scene& scene = Application::getInstance().current_slice->scene;
enabled = scene.current_mesh_group->settings.get<bool>("prime_tower_enable")
&& scene.current_mesh_group->settings.get<coord_t>("prime_tower_min_volume") > 10
&& scene.current_mesh_group->settings.get<coord_t>("prime_tower_size") > 10;
extruder_count = scene.extruders.size();
extruder_order.resize(extruder_count);
for (unsigned int extruder_nr = 0; extruder_nr < extruder_count; extruder_nr++)
{
extruder_order[extruder_nr] = extruder_nr; //Start with default order, then sort.
}
//Sort from high adhesion to low adhesion.
const Scene* scene_pointer = &scene; //Communicate to lambda via pointer to prevent copy.
std::stable_sort(extruder_order.begin(), extruder_order.end(), [scene_pointer](const unsigned int& extruder_nr_a, const unsigned int& extruder_nr_b) -> bool
{
const Ratio adhesion_a = scene_pointer->extruders[extruder_nr_a].settings.get<Ratio>("material_adhesion_tendency");
const Ratio adhesion_b = scene_pointer->extruders[extruder_nr_b].settings.get<Ratio>("material_adhesion_tendency");
return adhesion_a < adhesion_b;
});
}
void PrimeTower::generateGroundpoly()
{
if (!enabled)
{
return;
}
const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings;
const coord_t tower_size = mesh_group_settings.get<coord_t>("prime_tower_size");
const bool circular_prime_tower = mesh_group_settings.get<bool>("prime_tower_circular");
const Settings& brim_extruder_settings = mesh_group_settings.get<ExtruderTrain&>("adhesion_extruder_nr").settings;
const bool has_raft = (mesh_group_settings.get<EPlatformAdhesion>("adhesion_type") == EPlatformAdhesion::RAFT);
const bool has_prime_brim = mesh_group_settings.get<bool>("prime_tower_brim_enable");
const coord_t offset = (has_raft || ! has_prime_brim) ? 0 :
brim_extruder_settings.get<size_t>("brim_line_count") *
brim_extruder_settings.get<coord_t>("skirt_brim_line_width") *
brim_extruder_settings.get<Ratio>("initial_layer_line_width_factor");
PolygonRef p = outer_poly.newPoly();
int tower_distance = 0;
const coord_t x = mesh_group_settings.get<coord_t>("prime_tower_position_x") - offset;
const coord_t y = mesh_group_settings.get<coord_t>("prime_tower_position_y") - offset;
if (circular_prime_tower)
{
const coord_t tower_radius = tower_size / 2;
for (unsigned int i = 0; i < CIRCLE_RESOLUTION; i++)
{
const double angle = (double) i / CIRCLE_RESOLUTION * 2 * M_PI; //In radians.
p.add(Point(x - tower_radius + tower_distance + cos(angle) * tower_radius,
y + tower_radius + tower_distance + sin(angle) * tower_radius));
}
}
else
{
p.add(Point(x + tower_distance, y + tower_distance));
p.add(Point(x + tower_distance, y + tower_distance + tower_size));
p.add(Point(x + tower_distance - tower_size, y + tower_distance + tower_size));
p.add(Point(x + tower_distance - tower_size, y + tower_distance));
}
middle = Point(x - tower_size / 2, y + tower_size / 2);
post_wipe_point = Point(x + tower_distance - tower_size / 2, y + tower_distance + tower_size / 2);
outer_poly_first_layer = outer_poly.offset(offset);
}
void PrimeTower::generatePaths(const SliceDataStorage& storage)
{
enabled &= storage.max_print_height_second_to_last_extruder >= 0; //Maybe it turns out that we don't need a prime tower after all because there are no layer switches.
if (enabled)
{
generatePaths_denseInfill();
generateStartLocations();
}
}
void PrimeTower::generatePaths_denseInfill()
{
const Scene& scene = Application::getInstance().current_slice->scene;
const Settings& mesh_group_settings = scene.current_mesh_group->settings;
const coord_t layer_height = mesh_group_settings.get<coord_t>("layer_height");
pattern_per_extruder.resize(extruder_count);
coord_t cumulative_inset = 0; //Each tower shape is going to be printed inside the other. This is the inset we're doing for each extruder.
for (size_t extruder_nr : extruder_order)
{
const coord_t line_width = scene.extruders[extruder_nr].settings.get<coord_t>("prime_tower_line_width");
const coord_t required_volume = scene.extruders[extruder_nr].settings.get<double>("prime_tower_min_volume") * 1000000000; //To cubic microns.
const Ratio flow = scene.extruders[extruder_nr].settings.get<Ratio>("prime_tower_flow");
coord_t current_volume = 0;
ExtrusionMoves& pattern = pattern_per_extruder[extruder_nr];
//Create the walls of the prime tower.
unsigned int wall_nr = 0;
for (; current_volume < required_volume; wall_nr++)
{
//Create a new polygon with an offset from the outer polygon.
Polygons polygons = outer_poly.offset(-cumulative_inset - wall_nr * line_width - line_width / 2);
pattern.polygons.add(polygons);
current_volume += polygons.polygonLength() * line_width * layer_height * flow;
if (polygons.empty()) //Don't continue. We won't ever reach the required volume because it doesn't fit.
{
break;
}
}
cumulative_inset += wall_nr * line_width;
//Generate the pattern for the first layer.
coord_t line_width_layer0 = line_width;
if (mesh_group_settings.get<EPlatformAdhesion>("adhesion_type") != EPlatformAdhesion::RAFT)
{
line_width_layer0 *= scene.extruders[extruder_nr].settings.get<Ratio>("initial_layer_line_width_factor");
}
pattern_per_extruder_layer0.emplace_back();
ExtrusionMoves& pattern_layer0 = pattern_per_extruder_layer0.back();
// Generate a concentric infill pattern in the form insets for the prime tower's first layer instead of using
// the infill pattern because the infill pattern tries to connect polygons in different insets which causes the
// first layer of the prime tower to not stick well.
Polygons inset = outer_poly.offset(-line_width_layer0 / 2);
while (!inset.empty())
{
pattern_layer0.polygons.add(inset);
inset = inset.offset(-line_width_layer0);
}
}
}
void PrimeTower::generateStartLocations()
{
// Evenly spread out a number of dots along the prime tower's outline. This is done for the complete outline,
// so use the same start and end segments for this.
PolygonsPointIndex segment_start = PolygonsPointIndex(&outer_poly, 0, 0);
PolygonsPointIndex segment_end = segment_start;
PolygonUtils::spreadDots(segment_start, segment_end, number_of_prime_tower_start_locations, prime_tower_start_locations);
}
void PrimeTower::addToGcode(const SliceDataStorage& storage, LayerPlan& gcode_layer, const int prev_extruder, const int new_extruder) const
{
if (!enabled)
{
return;
}
if (gcode_layer.getPrimeTowerIsPlanned(new_extruder))
{ // don't print the prime tower if it has been printed already with this extruder.
return;
}
const LayerIndex layer_nr = gcode_layer.getLayerNr();
if (layer_nr > storage.max_print_height_second_to_last_extruder + 1)
{
return;
}
bool post_wipe = Application::getInstance().current_slice->scene.extruders[prev_extruder].settings.get<bool>("prime_tower_wipe_enabled");
// Do not wipe on the first layer, we will generate non-hollow prime tower there for better bed adhesion.
if (prev_extruder == new_extruder || layer_nr == 0)
{
post_wipe = false;
}
// Go to the start location if it's not the first layer
if (layer_nr != 0)
{
gotoStartLocation(gcode_layer, new_extruder);
}
addToGcode_denseInfill(gcode_layer, new_extruder);
// post-wipe:
if (post_wipe)
{
//Make sure we wipe the old extruder on the prime tower.
const Settings& previous_settings = Application::getInstance().current_slice->scene.extruders[prev_extruder].settings;
const Point previous_nozzle_offset = Point(previous_settings.get<coord_t>("machine_nozzle_offset_x"), previous_settings.get<coord_t>("machine_nozzle_offset_y"));
const Settings& new_settings = Application::getInstance().current_slice->scene.extruders[new_extruder].settings;
const Point new_nozzle_offset = Point(new_settings.get<coord_t>("machine_nozzle_offset_x"), new_settings.get<coord_t>("machine_nozzle_offset_y"));
gcode_layer.addTravel(post_wipe_point - previous_nozzle_offset + new_nozzle_offset);
}
gcode_layer.setPrimeTowerIsPlanned(new_extruder);
}
void PrimeTower::addToGcode_denseInfill(LayerPlan& gcode_layer, const size_t extruder_nr) const
{
const ExtrusionMoves& pattern = (gcode_layer.getLayerNr() == -static_cast<LayerIndex>(Raft::getFillerLayerCount()))
? pattern_per_extruder_layer0[extruder_nr]
: pattern_per_extruder[extruder_nr];
const GCodePathConfig& config = gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr];
gcode_layer.addPolygonsByOptimizer(pattern.polygons, config);
gcode_layer.addLinesByOptimizer(pattern.lines, config, SpaceFillType::Lines);
}
void PrimeTower::subtractFromSupport(SliceDataStorage& storage)
{
const Polygons outside_polygon = outer_poly.getOutsidePolygons();
AABB outside_polygon_boundary_box(outside_polygon);
for(size_t layer = 0; layer <= (size_t)storage.max_print_height_second_to_last_extruder + 1 && layer < storage.support.supportLayers.size(); layer++)
{
SupportLayer& support_layer = storage.support.supportLayers[layer];
// take the differences of the support infill parts and the prime tower area
support_layer.excludeAreasFromSupportInfillAreas(outside_polygon, outside_polygon_boundary_box);
}
}
void PrimeTower::gotoStartLocation(LayerPlan& gcode_layer, const int extruder_nr) const
{
int current_start_location_idx = ((((extruder_nr + 1) * gcode_layer.getLayerNr()) % number_of_prime_tower_start_locations)
+ number_of_prime_tower_start_locations) % number_of_prime_tower_start_locations;
const ClosestPolygonPoint wipe_location = prime_tower_start_locations[current_start_location_idx];
const ExtruderTrain& train = Application::getInstance().current_slice->scene.extruders[extruder_nr];
const coord_t inward_dist = train.settings.get<coord_t>("machine_nozzle_size") * 3 / 2 ;
const coord_t start_dist = train.settings.get<coord_t>("machine_nozzle_size") * 2;
const Point prime_end = PolygonUtils::moveInsideDiagonally(wipe_location, inward_dist);
const Point outward_dir = wipe_location.location - prime_end;
const Point prime_start = wipe_location.location + normal(outward_dir, start_dist);
gcode_layer.addTravel(prime_start);
}
}//namespace cura
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: gconfbecdef.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-07 19:47:01 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef GCONFBACKEND_HXX_
#include "gconfbackend.hxx"
#endif // GCONFBACKEND_HXX_
#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif
#ifndef _CPPUHELPER_IMPLEMENTATIONENTRY_HXX_
#include <cppuhelper/implementationentry.hxx>
#endif // _CPPUHELPER_IMPLEMENTATIONENTRY_HXX_
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif // _RTL_USTRBUF_HXX_
#include "uno/current_context.hxx"
#include <stdio.h>
#include <orbit/orbit.h>
namespace css = com::sun::star ;
namespace uno = css::uno ;
namespace lang = css::lang ;
namespace backend = css::configuration::backend ;
//==============================================================================
static uno::Reference<uno::XInterface> SAL_CALL createGconfBackend(const uno::Reference<uno::XComponentContext>& xContext)
{
try {
uno::Reference< uno::XCurrentContext > xCurrentContext(uno::getCurrentContext());
if (xCurrentContext.is())
{
uno::Any aValue = xCurrentContext->getValueByName(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "system.desktop-environment" ) ) );
rtl::OUString aDesktopEnvironment;
if ( (aValue >>= aDesktopEnvironment) && (aDesktopEnvironment.equalsAscii("GNOME")) )
{
// ORBit-2 versions < 2.8 cause a deadlock with the gtk+ VCL plugin
if ( (orbit_major_version >= 2) && (orbit_minor_version >= 8) )
{
return * GconfBackend::createInstance(xContext);
}
}
}
return uno::Reference<uno::XInterface>();
} catch (uno::RuntimeException e) {
return uno::Reference<uno::XInterface>();
}
}
//==============================================================================
static const cppu::ImplementationEntry kImplementations_entries[] =
{
{
createGconfBackend,
GconfBackend::getBackendName,
GconfBackend::getBackendServiceNames,
cppu::createSingleComponentFactory,
NULL,
0
},
{ NULL }
} ;
//------------------------------------------------------------------------------
extern "C" void SAL_CALL component_getImplementationEnvironment(
const sal_Char **aEnvTypeName,
uno_Environment **aEnvironment) {
*aEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ;
}
//------------------------------------------------------------------------------
extern "C" sal_Bool SAL_CALL component_writeInfo(void *pServiceManager,
void *pRegistryKey) {
using namespace ::com::sun::star::registry;
if (pRegistryKey)
{
try
{
uno::Reference< XRegistryKey > xImplKey = static_cast< XRegistryKey* >( pRegistryKey )->createKey(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/") ) + GconfBackend::getBackendName()
);
// Register associated service names
uno::Reference< XRegistryKey > xServicesKey = xImplKey->createKey(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/UNO/SERVICES") )
);
uno::Sequence<rtl::OUString> sServiceNames = GconfBackend::getBackendServiceNames();
for (sal_Int32 i = 0 ; i < sServiceNames.getLength() ; ++ i)
xServicesKey->createKey(sServiceNames[i]);
// Register supported components
uno::Reference<XRegistryKey> xComponentKey = xImplKey->createKey(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/DATA/SupportedComponents") )
);
xComponentKey->setAsciiListValue( GconfBackend::getSupportedComponents() );
return sal_True;
}
catch( InvalidRegistryException& )
{
OSL_ENSURE(sal_False, "InvalidRegistryException caught");
}
}
return sal_False;
}
//------------------------------------------------------------------------------
extern "C" void *component_getFactory(const sal_Char *aImplementationName,
void *aServiceManager,
void *aRegistryKey) {
return cppu::component_getFactoryHelper(
aImplementationName,
aServiceManager,
aRegistryKey,
kImplementations_entries) ;
}
//------------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS printsetting (1.4.40); FILE MERGED 2006/03/08 13:35:59 obr 1.4.40.1: #i50817# patch applied with minor modifications<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: gconfbecdef.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-03-22 09:34:51 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef GCONFBACKEND_HXX_
#include "gconfbackend.hxx"
#endif // GCONFBACKEND_HXX_
#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif
#ifndef _CPPUHELPER_IMPLEMENTATIONENTRY_HXX_
#include <cppuhelper/implementationentry.hxx>
#endif // _CPPUHELPER_IMPLEMENTATIONENTRY_HXX_
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif // _RTL_USTRBUF_HXX_
#include "uno/current_context.hxx"
#include <stdio.h>
#include <orbit/orbit.h>
namespace css = com::sun::star ;
namespace uno = css::uno ;
namespace lang = css::lang ;
namespace backend = css::configuration::backend ;
//==============================================================================
static uno::Reference<uno::XInterface> SAL_CALL createGconfBackend(const uno::Reference<uno::XComponentContext>& xContext)
{
try {
uno::Reference< uno::XCurrentContext > xCurrentContext(uno::getCurrentContext());
if (xCurrentContext.is())
{
#ifndef ENABLE_LOCKDOWN
uno::Any aValue = xCurrentContext->getValueByName(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "system.desktop-environment" ) ) );
rtl::OUString aDesktopEnvironment;
if ( (aValue >>= aDesktopEnvironment) && (aDesktopEnvironment.equalsAscii("GNOME")) )
{
#endif // ! ENABLE_LOCKDOWN
// ORBit-2 versions < 2.8 cause a deadlock with the gtk+ VCL plugin
if ( (orbit_major_version >= 2) && (orbit_minor_version >= 8) )
{
return * GconfBackend::createInstance(xContext);
}
#ifndef ENABLE_LOCKDOWN
}
#endif // ! ENABLE_LOCKDOWN
}
return uno::Reference<uno::XInterface>();
} catch (uno::RuntimeException e) {
return uno::Reference<uno::XInterface>();
}
}
//==============================================================================
static const cppu::ImplementationEntry kImplementations_entries[] =
{
{
createGconfBackend,
GconfBackend::getBackendName,
GconfBackend::getBackendServiceNames,
cppu::createSingleComponentFactory,
NULL,
0
},
{ NULL }
} ;
//------------------------------------------------------------------------------
extern "C" void SAL_CALL component_getImplementationEnvironment(
const sal_Char **aEnvTypeName,
uno_Environment **aEnvironment) {
*aEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ;
}
//------------------------------------------------------------------------------
extern "C" sal_Bool SAL_CALL component_writeInfo(void *pServiceManager,
void *pRegistryKey) {
using namespace ::com::sun::star::registry;
if (pRegistryKey)
{
try
{
uno::Reference< XRegistryKey > xImplKey = static_cast< XRegistryKey* >( pRegistryKey )->createKey(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/") ) + GconfBackend::getBackendName()
);
// Register associated service names
uno::Reference< XRegistryKey > xServicesKey = xImplKey->createKey(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/UNO/SERVICES") )
);
uno::Sequence<rtl::OUString> sServiceNames = GconfBackend::getBackendServiceNames();
for (sal_Int32 i = 0 ; i < sServiceNames.getLength() ; ++ i)
xServicesKey->createKey(sServiceNames[i]);
// Register supported components
uno::Reference<XRegistryKey> xComponentKey = xImplKey->createKey(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/DATA/SupportedComponents") )
);
xComponentKey->setAsciiListValue( GconfBackend::getSupportedComponents() );
return sal_True;
}
catch( InvalidRegistryException& )
{
OSL_ENSURE(sal_False, "InvalidRegistryException caught");
}
}
return sal_False;
}
//------------------------------------------------------------------------------
extern "C" void *component_getFactory(const sal_Char *aImplementationName,
void *aServiceManager,
void *aRegistryKey) {
return cppu::component_getFactoryHelper(
aImplementationName,
aServiceManager,
aRegistryKey,
kImplementations_entries) ;
}
//------------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>//---------------------- tensor_product_polynomials.cc ------------
// $Id$
// Version: $Name$
//
// Copyright (C) 2000 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------- tensor_product_polynomials.cc ------------
#include <base/exceptions.h>
#include <base/tensor_product_polynomials.h>
template <int dim>
TensorProductPolynomials<dim>::TensorProductPolynomials(
const vector<SmartPointer<Polynomial> > &pols):
polynomials(pols)
{}
template <int dim>
void TensorProductPolynomials<dim>::compute(
const Point<dim> &p,
vector<double> &values,
vector<Tensor<1,dim> > &grads,
vector<Tensor<2,dim> > &grad_grads) const
{
unsigned int n_pols=polynomials.size();
vector<unsigned int> n_pols_to(dim+1);
n_pols_to[0]=1;
for (unsigned int i=0; i<dim; ++i)
n_pols_to[i+1]=n_pols_to[i]*n_pols;
unsigned int n_tensor_pols=n_pols_to[dim];
Assert(values.size()==n_tensor_pols || values.size()==0,
ExcDimensionMismatch2(values.size(), n_tensor_pols, 0));
Assert(grads.size()==n_tensor_pols|| grads.size()==0,
ExcDimensionMismatch2(grads.size(), n_tensor_pols, 0));
Assert(grad_grads.size()==n_tensor_pols|| grad_grads.size()==0,
ExcDimensionMismatch2(grad_grads.size(), n_tensor_pols, 0));
unsigned int v_size=0;
bool update_values=false, update_grads=false, update_grad_grads=false;
if (values.size()==n_tensor_pols)
{
update_values=true;
v_size=1;
}
if (grads.size()==n_tensor_pols)
{
update_grads=true;
v_size=2;
}
if (grad_grads.size()==n_tensor_pols)
{
update_grad_grads=true;
v_size=3;
}
vector<vector<vector<double> > > v(
dim, vector<vector<double> > (n_pols, vector<double> (v_size)));
for (unsigned int d=0; d<dim; ++d)
{
vector<vector<double> > &v_d=v[d];
Assert(v_d.size()==n_pols, ExcInternalError());
for (unsigned int i=0; i<n_pols; ++i)
polynomials[i]->value(p(d), v_d[i]);
}
if (update_values)
{
for (unsigned int i=0; i<n_tensor_pols; ++i)
values[i]=1;
for (unsigned int x=0; x<dim; ++x)
for (unsigned int i=0; i<n_tensor_pols; ++i)
values[i]*=v[x][(i/n_pols_to[x])%n_pols][0];
}
if (update_grads)
{
for (unsigned int i=0; i<n_tensor_pols; ++i)
for (unsigned int d=0; d<dim; ++d)
grads[i][d]=1.;
for (unsigned int x=0; x<dim; ++x)
for (unsigned int i=0; i<n_tensor_pols; ++i)
for (unsigned int d=0; d<dim; ++d)
grads[i][d]*=v[x][(i/n_pols_to[x])%n_pols][d==x];
}
if (update_grad_grads)
{
for (unsigned int i=0; i<n_tensor_pols; ++i)
for (unsigned int d1=0; d1<dim; ++d1)
for (unsigned int d2=0; d2<dim; ++d2)
grad_grads[i][d1][d2]=1.;
for (unsigned int x=0; x<dim; ++x)
for (unsigned int i=0; i<n_tensor_pols; ++i)
for (unsigned int d1=0; d1<dim; ++d1)
for (unsigned int d2=0; d2<dim; ++d2)
{
unsigned int derivative=0;
if (d1==x || d2==x)
{
if (d1==d2)
derivative=2;
else
derivative=1;
}
grad_grads[i][d1][d2]*=
v[x][(i/n_pols_to[x])%n_pols][derivative];
}
}
}
template class TensorProductPolynomials<1>;
template class TensorProductPolynomials<2>;
template class TensorProductPolynomials<3>;
<commit_msg>New n_tensor_product_polynomials function. Small changes.<commit_after>//---------------------- tensor_product_polynomials.cc ------------
// $Id$
// Version: $Name$
//
// Copyright (C) 2000 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------- tensor_product_polynomials.cc ------------
#include <base/exceptions.h>
#include <base/tensor_product_polynomials.h>
template<typename number> static
number power(number x, unsigned int y)
{
number value=1;
for (unsigned int i=0; i<y; ++i)
value*=x;
return value;
}
template <int dim>
TensorProductPolynomials<dim>::TensorProductPolynomials(
const vector<SmartPointer<Polynomial> > &pols):
polynomials(pols),
n_tensor_pols(power(polynomials.size(), dim))
{}
template <int dim>
void TensorProductPolynomials<dim>::compute(
const Point<dim> &p,
vector<double> &values,
vector<Tensor<1,dim> > &grads,
vector<Tensor<2,dim> > &grad_grads) const
{
unsigned int n_pols=polynomials.size();
vector<unsigned int> n_pols_to(dim+1);
n_pols_to[0]=1;
for (unsigned int i=0; i<dim; ++i)
n_pols_to[i+1]=n_pols_to[i]*n_pols;
Assert(n_pols_to[dim]==n_tensor_pols, ExcInternalError());
Assert(values.size()==n_tensor_pols || values.size()==0,
ExcDimensionMismatch2(values.size(), n_tensor_pols, 0));
Assert(grads.size()==n_tensor_pols|| grads.size()==0,
ExcDimensionMismatch2(grads.size(), n_tensor_pols, 0));
Assert(grad_grads.size()==n_tensor_pols|| grad_grads.size()==0,
ExcDimensionMismatch2(grad_grads.size(), n_tensor_pols, 0));
unsigned int v_size=0;
bool update_values=false, update_grads=false, update_grad_grads=false;
if (values.size()==n_tensor_pols)
{
update_values=true;
v_size=1;
}
if (grads.size()==n_tensor_pols)
{
update_grads=true;
v_size=2;
}
if (grad_grads.size()==n_tensor_pols)
{
update_grad_grads=true;
v_size=3;
}
vector<vector<vector<double> > > v(
dim, vector<vector<double> > (n_pols, vector<double> (v_size)));
for (unsigned int d=0; d<dim; ++d)
{
vector<vector<double> > &v_d=v[d];
Assert(v_d.size()==n_pols, ExcInternalError());
for (unsigned int i=0; i<n_pols; ++i)
polynomials[i]->value(p(d), v_d[i]);
}
if (update_values)
{
for (unsigned int i=0; i<n_tensor_pols; ++i)
values[i]=1;
for (unsigned int x=0; x<dim; ++x)
for (unsigned int i=0; i<n_tensor_pols; ++i)
values[i]*=v[x][(i/n_pols_to[x])%n_pols][0];
}
if (update_grads)
{
for (unsigned int i=0; i<n_tensor_pols; ++i)
for (unsigned int d=0; d<dim; ++d)
grads[i][d]=1.;
for (unsigned int x=0; x<dim; ++x)
for (unsigned int i=0; i<n_tensor_pols; ++i)
for (unsigned int d=0; d<dim; ++d)
grads[i][d]*=v[x][(i/n_pols_to[x])%n_pols][d==x];
}
if (update_grad_grads)
{
for (unsigned int i=0; i<n_tensor_pols; ++i)
for (unsigned int d1=0; d1<dim; ++d1)
for (unsigned int d2=0; d2<dim; ++d2)
grad_grads[i][d1][d2]=1.;
for (unsigned int x=0; x<dim; ++x)
for (unsigned int i=0; i<n_tensor_pols; ++i)
for (unsigned int d1=0; d1<dim; ++d1)
for (unsigned int d2=0; d2<dim; ++d2)
{
unsigned int derivative=0;
if (d1==x || d2==x)
{
if (d1==d2)
derivative=2;
else
derivative=1;
}
grad_grads[i][d1][d2]*=
v[x][(i/n_pols_to[x])%n_pols][derivative];
}
}
}
template<int dim> inline
unsigned int
TensorProductPolynomials<dim>::n_tensor_product_polynomials() const
{
return n_tensor_pols;
}
template class TensorProductPolynomials<1>;
template class TensorProductPolynomials<2>;
template class TensorProductPolynomials<3>;
<|endoftext|>
|
<commit_before>/*
* Copyright Andrey Semashev 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)
*/
/*!
* \file uuid/detail/uuid_x86.hpp
*
* \brief This header contains optimized SSE implementation of \c boost::uuid operations.
*/
#ifndef BOOST_UUID_DETAIL_UUID_X86_HPP_INCLUDED_
#define BOOST_UUID_DETAIL_UUID_X86_HPP_INCLUDED_
// MSVC does not always have immintrin.h (at least, not up to MSVC 10), so include the appropriate header for each instruction set
#if defined(BOOST_UUID_USE_SSE41)
#include <smmintrin.h>
#elif defined(BOOST_UUID_USE_SSE3)
#include <pmmintrin.h>
#else
#include <emmintrin.h>
#endif
namespace boost {
namespace uuids {
namespace detail {
BOOST_FORCEINLINE __m128i load_unaligned_si128(const uint8_t* p) BOOST_NOEXCEPT
{
#if defined(BOOST_UUID_USE_SSE3)
return _mm_lddqu_si128(reinterpret_cast< const __m128i* >(p));
#else
return _mm_loadu_si128(reinterpret_cast< const __m128i* >(p));
#endif
}
} // namespace detail
inline bool uuid::is_nil() const BOOST_NOEXCEPT
{
register __m128i mm = uuids::detail::load_unaligned_si128(data);
#if defined(BOOST_UUID_USE_SSE41)
return _mm_test_all_zeros(mm, mm) != 0;
#else
mm = _mm_cmpeq_epi8(mm, _mm_setzero_si128());
return _mm_movemask_epi8(mm) == 0xFFFF;
#endif
}
inline void uuid::swap(uuid& rhs) BOOST_NOEXCEPT
{
register __m128i mm_this = uuids::detail::load_unaligned_si128(data);
register __m128i mm_rhs = uuids::detail::load_unaligned_si128(rhs.data);
_mm_storeu_si128(reinterpret_cast< __m128i* >(rhs.data), mm_this);
_mm_storeu_si128(reinterpret_cast< __m128i* >(data), mm_rhs);
}
inline bool operator== (uuid const& lhs, uuid const& rhs) BOOST_NOEXCEPT
{
register __m128i mm_left = uuids::detail::load_unaligned_si128(lhs.data);
register __m128i mm_right = uuids::detail::load_unaligned_si128(rhs.data);
register __m128i mm_cmp = _mm_cmpeq_epi32(mm_left, mm_right);
#if defined(BOOST_UUID_USE_SSE41)
return _mm_test_all_ones(mm_cmp);
#else
return _mm_movemask_epi8(mm_cmp) == 0xFFFF;
#endif
}
inline bool operator< (uuid const& lhs, uuid const& rhs) BOOST_NOEXCEPT
{
register __m128i mm_left = uuids::detail::load_unaligned_si128(lhs.data);
register __m128i mm_right = uuids::detail::load_unaligned_si128(rhs.data);
// To emulate lexicographical_compare behavior we have to perform two comparisons - the forward and reverse one.
// Then we know which bytes are equivalent and which ones are different, and for those different the comparison results
// will be opposite. Then we'll be able to find the first differing comparison result (for both forward and reverse ways),
// and depending on which way it is for, this will be the result of the operation. There are a few notes to consider:
//
// 1. Due to little endian byte order the first bytes go into the lower part of the xmm registers,
// so the comparison results in the least significant bits will actually be the most signigicant for the final operation result.
// This means we have to determine which of the comparison results have the least significant bit on, and this is achieved with
// the "(x - 1) ^ x" trick.
// 2. Because there is only signed comparison in SSE/AVX, we have to invert byte comparison results whenever signs of the corresponding
// bytes are different. I.e. in signed comparison it's -1 < 1, but in unsigned it is the opposite (255 > 1). To do that we XOR left and right,
// making the most significant bit of each byte 1 if the signs are different, and later apply this mask with another XOR to the comparison results.
// 3. pcmpgtw compares for "greater" relation, so we swap the arguments to get what we need.
const __m128i mm_signs_mask = _mm_xor_si128(mm_left, mm_right);
__m128i mm_cmp = _mm_cmpgt_epi8(mm_right, mm_left), mm_rcmp = _mm_cmpgt_epi8(mm_left, mm_right);
mm_cmp = _mm_xor_si128(mm_signs_mask, mm_cmp);
mm_rcmp = _mm_xor_si128(mm_signs_mask, mm_rcmp);
uint32_t cmp = static_cast< uint32_t >(_mm_movemask_epi8(mm_cmp)), rcmp = static_cast< uint32_t >(_mm_movemask_epi8(mm_rcmp));
cmp = (cmp - 1u) ^ cmp;
rcmp = (rcmp - 1u) ^ rcmp;
return static_cast< uint16_t >(cmp) < static_cast< uint16_t >(rcmp);
}
} // namespace uuids
} // namespace boost
#endif // BOOST_UUID_DETAIL_UUID_X86_HPP_INCLUDED_
<commit_msg>Don't use 'register' in boost's uuid_x86.hpp<commit_after>/*
* Copyright Andrey Semashev 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)
*/
/*!
* \file uuid/detail/uuid_x86.hpp
*
* \brief This header contains optimized SSE implementation of \c boost::uuid operations.
*/
#ifndef BOOST_UUID_DETAIL_UUID_X86_HPP_INCLUDED_
#define BOOST_UUID_DETAIL_UUID_X86_HPP_INCLUDED_
// MSVC does not always have immintrin.h (at least, not up to MSVC 10), so include the appropriate header for each instruction set
#if defined(BOOST_UUID_USE_SSE41)
#include <smmintrin.h>
#elif defined(BOOST_UUID_USE_SSE3)
#include <pmmintrin.h>
#else
#include <emmintrin.h>
#endif
namespace boost {
namespace uuids {
namespace detail {
BOOST_FORCEINLINE __m128i load_unaligned_si128(const uint8_t* p) BOOST_NOEXCEPT
{
#if defined(BOOST_UUID_USE_SSE3)
return _mm_lddqu_si128(reinterpret_cast< const __m128i* >(p));
#else
return _mm_loadu_si128(reinterpret_cast< const __m128i* >(p));
#endif
}
} // namespace detail
inline bool uuid::is_nil() const BOOST_NOEXCEPT
{
__m128i mm = uuids::detail::load_unaligned_si128(data);
#if defined(BOOST_UUID_USE_SSE41)
return _mm_test_all_zeros(mm, mm) != 0;
#else
mm = _mm_cmpeq_epi8(mm, _mm_setzero_si128());
return _mm_movemask_epi8(mm) == 0xFFFF;
#endif
}
inline void uuid::swap(uuid& rhs) BOOST_NOEXCEPT
{
__m128i mm_this = uuids::detail::load_unaligned_si128(data);
__m128i mm_rhs = uuids::detail::load_unaligned_si128(rhs.data);
_mm_storeu_si128(reinterpret_cast< __m128i* >(rhs.data), mm_this);
_mm_storeu_si128(reinterpret_cast< __m128i* >(data), mm_rhs);
}
inline bool operator== (uuid const& lhs, uuid const& rhs) BOOST_NOEXCEPT
{
__m128i mm_left = uuids::detail::load_unaligned_si128(lhs.data);
__m128i mm_right = uuids::detail::load_unaligned_si128(rhs.data);
__m128i mm_cmp = _mm_cmpeq_epi32(mm_left, mm_right);
#if defined(BOOST_UUID_USE_SSE41)
return _mm_test_all_ones(mm_cmp);
#else
return _mm_movemask_epi8(mm_cmp) == 0xFFFF;
#endif
}
inline bool operator< (uuid const& lhs, uuid const& rhs) BOOST_NOEXCEPT
{
__m128i mm_left = uuids::detail::load_unaligned_si128(lhs.data);
__m128i mm_right = uuids::detail::load_unaligned_si128(rhs.data);
// To emulate lexicographical_compare behavior we have to perform two comparisons - the forward and reverse one.
// Then we know which bytes are equivalent and which ones are different, and for those different the comparison results
// will be opposite. Then we'll be able to find the first differing comparison result (for both forward and reverse ways),
// and depending on which way it is for, this will be the result of the operation. There are a few notes to consider:
//
// 1. Due to little endian byte order the first bytes go into the lower part of the xmm registers,
// so the comparison results in the least significant bits will actually be the most signigicant for the final operation result.
// This means we have to determine which of the comparison results have the least significant bit on, and this is achieved with
// the "(x - 1) ^ x" trick.
// 2. Because there is only signed comparison in SSE/AVX, we have to invert byte comparison results whenever signs of the corresponding
// bytes are different. I.e. in signed comparison it's -1 < 1, but in unsigned it is the opposite (255 > 1). To do that we XOR left and right,
// making the most significant bit of each byte 1 if the signs are different, and later apply this mask with another XOR to the comparison results.
// 3. pcmpgtw compares for "greater" relation, so we swap the arguments to get what we need.
const __m128i mm_signs_mask = _mm_xor_si128(mm_left, mm_right);
__m128i mm_cmp = _mm_cmpgt_epi8(mm_right, mm_left), mm_rcmp = _mm_cmpgt_epi8(mm_left, mm_right);
mm_cmp = _mm_xor_si128(mm_signs_mask, mm_cmp);
mm_rcmp = _mm_xor_si128(mm_signs_mask, mm_rcmp);
uint32_t cmp = static_cast< uint32_t >(_mm_movemask_epi8(mm_cmp)), rcmp = static_cast< uint32_t >(_mm_movemask_epi8(mm_rcmp));
cmp = (cmp - 1u) ^ cmp;
rcmp = (rcmp - 1u) ^ rcmp;
return static_cast< uint16_t >(cmp) < static_cast< uint16_t >(rcmp);
}
} // namespace uuids
} // namespace boost
#endif // BOOST_UUID_DETAIL_UUID_X86_HPP_INCLUDED_
<|endoftext|>
|
<commit_before>#include <assert.h>
#include <QDateTime>
#include <QDebug>
#include <QStringList>
#include <QtConcurrentRun>
#include <QTimer>
#include <algorithm>
#include <AlpinoCorpus/Error.hh>
#include "QueryModel.hh"
QString const QueryModel::MISSING_ATTRIBUTE("[missing attribute]");
QueryModel::HitsCompare::HitsCompare(QueryModel const &parent)
:
d_parent(parent)
{}
inline bool QueryModel::HitsCompare::operator()(int one_idx, int other_idx)
{
int oneHits = d_parent.d_results[one_idx].second;
int twoHits = d_parent.d_results[other_idx].second;
if (oneHits == twoHits)
return d_parent.d_results[one_idx].first <
d_parent.d_results[other_idx].first;
else
return oneHits > twoHits;
}
QueryModel::QueryModel(CorpusPtr corpus, QObject *parent)
:
QAbstractTableModel(parent),
d_corpus(corpus),
d_entryCache(new EntryCache()),
d_timer(new QTimer)
{
connect(this, SIGNAL(queryEntryFound(QString)),
SLOT(mapperEntryFound(QString)));
connect(this, SIGNAL(queryFinished(int, int, bool)),
SLOT(finalizeQuery(int, int, bool)));
// Timer for progress updates.
connect(d_timer.data(), SIGNAL(timeout()),
SLOT(updateProgress()));
connect(this, SIGNAL(queryStopped(int, int)),
SLOT(stopProgress()));
connect(this, SIGNAL(queryFinished(int, int, bool)),
SLOT(stopProgress()));
connect(this, SIGNAL(queryFailed(QString)),
SLOT(stopProgress()));
}
QueryModel::~QueryModel()
{
cancelQuery();
}
QString QueryModel::asXML() const
{
int rows = rowCount(QModelIndex());
// TODO: Remove selected attribute from the filter...
QStringList outList;
outList.append("<statistics>");
outList.append("<statisticsinfo>");
outList.append(QString("<corpus>%1</corpus>")
.arg(QString::fromUtf8(d_corpus->name().c_str())));
outList.append(QString("<filter>%1</filter>")
.arg(d_query));
outList.append(QString("<attribute>%1</attribute>")
.arg(d_attribute));
outList.append(QString("<variants>%1</variants>")
.arg(rows));
outList.append(QString("<hits>%1</hits>")
.arg(totalHits()));
QString date(QDateTime::currentDateTime().toLocalTime().toString());
outList.append(QString("<date>%1</date>")
.arg(date));
outList.append("</statisticsinfo>");
for (int i = 0; i < rows; ++i) {
outList.append("<statistic>");
outList.append(QString("<value>%1</value>")
.arg(data(index(i, 0)).toString()));
outList.append(QString("<frequency>%1</frequency>")
.arg(data(index(i, 1)).toString()));
outList.append(QString("<percentage>%1</percentage>")
.arg(data(index(i, 2)).toDouble() * 100.0, 0, 'f', 1));
outList.append("</statistic>");
}
outList.append("</statistics>");
return outList.join("\n");
}
int QueryModel::columnCount(QModelIndex const &index) const
{
return 3;
}
int QueryModel::rowCount(QModelIndex const &index) const
{
return d_results.size();
}
QVariant QueryModel::data(QModelIndex const &index, int role) const
{
if (!index.isValid()
|| (role != Qt::DisplayRole && role != Qt::UserRole)
|| index.row() >= d_results.size()
|| index.row() < 0
|| index.column() > 2
|| index.column() < 0)
return QVariant();
switch (index.column())
{
case 0:
// map positions of the hits index to the positions in d_results
return d_results[d_hitsIndex[index.row()]].first;
case 1:
return d_results[d_hitsIndex[index.row()]].second;
case 2:
return static_cast<double>(d_results[d_hitsIndex[index.row()]].second)
/ static_cast<double>(d_totalHits);
default:
return QVariant();
}
}
QString QueryModel::expandQuery(QString const &query,
QString const &attribute) const
{
QString expandedQuery = QString("%1/(@%2/string(), '%3')[1]")
.arg(query)
.arg(attribute)
.arg(MISSING_ATTRIBUTE);
// Not all corpus readers support this styntax.
if (!validQuery(expandedQuery))
expandedQuery = QString("%1/@%2")
.arg(query)
.arg(attribute);
return expandedQuery;
}
void QueryModel::updateProgress()
{
emit progressChanged(d_entryIterator.progress());
}
QVariant QueryModel::headerData(int column, Qt::Orientation orientation, int role) const
{
if (role != Qt::DisplayRole)
return QVariant();
if (orientation == Qt::Vertical)
return QVariant();
switch (column)
{
case 0:
return tr("Value");
case 1:
return tr("Nodes");
case 2:
return tr("Percentage");
default:
return QVariant();
}
}
void QueryModel::mapperEntryFound(QString entry)
{
if (d_cancelled)
return;
// find position in d_results using the word index
int idx = d_valueIndex.value(entry, -1);
if (idx == -1)
{
idx = d_results.size();
d_results.append(QPair<QString,int>(entry, 1));
d_valueIndex[entry] = idx;
HitsCompare compare(*this);
// find new position, just above the result with less hits.
QList<int>::iterator insertPos = qLowerBound(
d_hitsIndex.begin(), d_hitsIndex.end(), idx, compare);
// insert at new position
d_hitsIndex.insert(insertPos, idx);
emit layoutChanged(); // notify tableview that we have new rows
}
else
{
HitsCompare compare(*this);
// Find the current position to remove
// Binary search: does not work? Why not? :(
QList<int>::iterator current_pos = qBinaryFind(
d_hitsIndex.begin(), d_hitsIndex.end(), idx,
compare);
// It is already in the words index, it has to be in the hits index as well!
assert(current_pos != d_hitsIndex.end());
// remove from current position in the index
d_hitsIndex.erase(current_pos);
// Update hits index
int hits = d_results[idx].second;
d_results[idx].second = hits + 1;
// find new position, just above the result with less hits.
QList<int>::iterator insertPos = qLowerBound(
d_hitsIndex.begin(), d_hitsIndex.end(), idx, compare);
// insert at new position
d_hitsIndex.insert(insertPos, idx);
}
++d_totalHits;
emit dataChanged(index(idx, 0), index(idx + 1, 2));
}
void QueryModel::runQuery(QString const &query, QString const &attribute)
{
cancelQuery(); // just in case
// clean results cache and notify the table of the loss of rows
//int size = d_results.size();
d_results.clear();
d_hitsIndex.clear();
emit layoutChanged();
// clear cache and counter
d_valueIndex.clear();
d_totalHits = 0;
d_query = query;
d_attribute = attribute;
// Do nothing if we where given a null-pointer
if (!d_corpus)
return;
if (!query.isEmpty())
{
d_timer->setInterval(100);
d_timer->setSingleShot(false);
d_timer->start();
d_entriesFuture = QtConcurrent::run(this, &QueryModel::getEntriesWithQuery,
expandQuery(query, attribute));
}
// If the query is empty, QueryModel is not supposed to do anything.
}
bool QueryModel::validQuery(QString const &query) const
{
return d_corpus->isValidQuery(alpinocorpus::CorpusReader::XPATH,
false, query.toUtf8().constData());
}
void QueryModel::cancelQuery()
{
d_cancelled = true;
d_entryIterator.interrupt();
d_entriesFuture.waitForFinished();
d_timer->stop();
}
void QueryModel::finalizeQuery(int n, int totalEntries, bool cached)
{
// Just to make shure, otherwise data() will go completely crazy
Q_ASSERT(d_hitsIndex.size() == d_results.size());
layoutChanged(); // Please, don't do this. Let's copy FilterModel's implementation.
if (!cached)
{
d_entryCache->insert(d_query, new CacheItem(d_totalHits, d_hitsIndex, d_results));
// this index is no longer needed, as it is only used for constructing d_hitsIndex
d_valueIndex.clear();
}
}
// run async, because query() starts searching immediately
void QueryModel::getEntriesWithQuery(QString const &query)
{
try {
if (d_entryCache->contains(query))
{
{
QMutexLocker locker(&d_resultsMutex);
CacheItem *cachedResult = d_entryCache->object(query);
d_totalHits = cachedResult->hits;
d_hitsIndex = cachedResult->index;
d_results = cachedResult->entries;
}
emit queryFinished(d_results.size(), d_results.size(), true);
return;
}
QueryModel::getEntries(
d_corpus->query(alpinocorpus::CorpusReader::XPATH, query.toUtf8().constData()));
} catch (std::exception const &e) {
qDebug() << "Error in QueryModel::getEntries: " << e.what();
emit queryFailed(e.what());
}
}
// run async
void QueryModel::getEntries(EntryIterator const &i)
{
if (i.hasProgress())
emit queryStarted(100);
else
emit queryStarted(0);
try {
d_cancelled = false;
d_entryIterator = i;
while (!d_cancelled && d_entryIterator.hasNext())
{
alpinocorpus::Entry e = d_entryIterator.next(*d_corpus);
emit queryEntryFound(QString::fromUtf8(e.contents.c_str()));
}
if (d_cancelled)
emit queryStopped(d_results.size(), d_results.size());
else
emit queryFinished(d_results.size(), d_results.size(), false);
}
// Catch d_entryIterator.interrupt()'s shockwaves of terror
catch (alpinocorpus::IterationInterrupted const &e) {
emit queryStopped(d_results.size(), d_results.size());
}
catch (alpinocorpus::Error const &e) {
qDebug() << "Error in QueryModel::getEntries: " << e.what();
emit queryFailed(e.what());
}
}
void QueryModel::stopProgress()
{
d_timer->stop();
}
<commit_msg>Align number of hits to the right in Statistics Window. This fixes issue #108.<commit_after>#include <assert.h>
#include <QDateTime>
#include <QDebug>
#include <QStringList>
#include <QtConcurrentRun>
#include <QTimer>
#include <algorithm>
#include <AlpinoCorpus/Error.hh>
#include "QueryModel.hh"
QString const QueryModel::MISSING_ATTRIBUTE("[missing attribute]");
QueryModel::HitsCompare::HitsCompare(QueryModel const &parent)
:
d_parent(parent)
{}
inline bool QueryModel::HitsCompare::operator()(int one_idx, int other_idx)
{
int oneHits = d_parent.d_results[one_idx].second;
int twoHits = d_parent.d_results[other_idx].second;
if (oneHits == twoHits)
return d_parent.d_results[one_idx].first <
d_parent.d_results[other_idx].first;
else
return oneHits > twoHits;
}
QueryModel::QueryModel(CorpusPtr corpus, QObject *parent)
:
QAbstractTableModel(parent),
d_corpus(corpus),
d_entryCache(new EntryCache()),
d_timer(new QTimer)
{
connect(this, SIGNAL(queryEntryFound(QString)),
SLOT(mapperEntryFound(QString)));
connect(this, SIGNAL(queryFinished(int, int, bool)),
SLOT(finalizeQuery(int, int, bool)));
// Timer for progress updates.
connect(d_timer.data(), SIGNAL(timeout()),
SLOT(updateProgress()));
connect(this, SIGNAL(queryStopped(int, int)),
SLOT(stopProgress()));
connect(this, SIGNAL(queryFinished(int, int, bool)),
SLOT(stopProgress()));
connect(this, SIGNAL(queryFailed(QString)),
SLOT(stopProgress()));
}
QueryModel::~QueryModel()
{
cancelQuery();
}
QString QueryModel::asXML() const
{
int rows = rowCount(QModelIndex());
// TODO: Remove selected attribute from the filter...
QStringList outList;
outList.append("<statistics>");
outList.append("<statisticsinfo>");
outList.append(QString("<corpus>%1</corpus>")
.arg(QString::fromUtf8(d_corpus->name().c_str())));
outList.append(QString("<filter>%1</filter>")
.arg(d_query));
outList.append(QString("<attribute>%1</attribute>")
.arg(d_attribute));
outList.append(QString("<variants>%1</variants>")
.arg(rows));
outList.append(QString("<hits>%1</hits>")
.arg(totalHits()));
QString date(QDateTime::currentDateTime().toLocalTime().toString());
outList.append(QString("<date>%1</date>")
.arg(date));
outList.append("</statisticsinfo>");
for (int i = 0; i < rows; ++i) {
outList.append("<statistic>");
outList.append(QString("<value>%1</value>")
.arg(data(index(i, 0)).toString()));
outList.append(QString("<frequency>%1</frequency>")
.arg(data(index(i, 1)).toString()));
outList.append(QString("<percentage>%1</percentage>")
.arg(data(index(i, 2)).toDouble() * 100.0, 0, 'f', 1));
outList.append("</statistic>");
}
outList.append("</statistics>");
return outList.join("\n");
}
int QueryModel::columnCount(QModelIndex const &index) const
{
return 3;
}
int QueryModel::rowCount(QModelIndex const &index) const
{
return d_results.size();
}
QVariant QueryModel::data(QModelIndex const &index, int role) const
{
if (!index.isValid()
|| index.row() >= d_results.size()
|| index.row() < 0
|| index.column() > 2
|| index.column() < 0)
return QVariant();
switch (role)
{
case Qt::UserRole:
case Qt::DisplayRole:
switch (index.column())
{
case 0:
// map positions of the hits index to the positions in d_results
return d_results[d_hitsIndex[index.row()]].first;
case 1:
return d_results[d_hitsIndex[index.row()]].second;
case 2:
return static_cast<double>(d_results[d_hitsIndex[index.row()]].second)
/ static_cast<double>(d_totalHits);
default:
return QVariant();
}
case Qt::TextAlignmentRole:
switch (index.column())
{
case 1:
case 2:
return Qt::AlignRight;
default:
return Qt::AlignLeft;
}
default:
return QVariant();
}
}
QString QueryModel::expandQuery(QString const &query,
QString const &attribute) const
{
QString expandedQuery = QString("%1/(@%2/string(), '%3')[1]")
.arg(query)
.arg(attribute)
.arg(MISSING_ATTRIBUTE);
// Not all corpus readers support this styntax.
if (!validQuery(expandedQuery))
expandedQuery = QString("%1/@%2")
.arg(query)
.arg(attribute);
return expandedQuery;
}
void QueryModel::updateProgress()
{
emit progressChanged(d_entryIterator.progress());
}
QVariant QueryModel::headerData(int column, Qt::Orientation orientation, int role) const
{
if (role != Qt::DisplayRole)
return QVariant();
if (orientation == Qt::Vertical)
return QVariant();
switch (column)
{
case 0:
return tr("Value");
case 1:
return tr("Nodes");
case 2:
return tr("Percentage");
default:
return QVariant();
}
}
void QueryModel::mapperEntryFound(QString entry)
{
if (d_cancelled)
return;
// find position in d_results using the word index
int idx = d_valueIndex.value(entry, -1);
if (idx == -1)
{
idx = d_results.size();
d_results.append(QPair<QString,int>(entry, 1));
d_valueIndex[entry] = idx;
HitsCompare compare(*this);
// find new position, just above the result with less hits.
QList<int>::iterator insertPos = qLowerBound(
d_hitsIndex.begin(), d_hitsIndex.end(), idx, compare);
// insert at new position
d_hitsIndex.insert(insertPos, idx);
emit layoutChanged(); // notify tableview that we have new rows
}
else
{
HitsCompare compare(*this);
// Find the current position to remove
// Binary search: does not work? Why not? :(
QList<int>::iterator current_pos = qBinaryFind(
d_hitsIndex.begin(), d_hitsIndex.end(), idx,
compare);
// It is already in the words index, it has to be in the hits index as well!
assert(current_pos != d_hitsIndex.end());
// remove from current position in the index
d_hitsIndex.erase(current_pos);
// Update hits index
int hits = d_results[idx].second;
d_results[idx].second = hits + 1;
// find new position, just above the result with less hits.
QList<int>::iterator insertPos = qLowerBound(
d_hitsIndex.begin(), d_hitsIndex.end(), idx, compare);
// insert at new position
d_hitsIndex.insert(insertPos, idx);
}
++d_totalHits;
emit dataChanged(index(idx, 0), index(idx + 1, 2));
}
void QueryModel::runQuery(QString const &query, QString const &attribute)
{
cancelQuery(); // just in case
// clean results cache and notify the table of the loss of rows
//int size = d_results.size();
d_results.clear();
d_hitsIndex.clear();
emit layoutChanged();
// clear cache and counter
d_valueIndex.clear();
d_totalHits = 0;
d_query = query;
d_attribute = attribute;
// Do nothing if we where given a null-pointer
if (!d_corpus)
return;
if (!query.isEmpty())
{
d_timer->setInterval(100);
d_timer->setSingleShot(false);
d_timer->start();
d_entriesFuture = QtConcurrent::run(this, &QueryModel::getEntriesWithQuery,
expandQuery(query, attribute));
}
// If the query is empty, QueryModel is not supposed to do anything.
}
bool QueryModel::validQuery(QString const &query) const
{
return d_corpus->isValidQuery(alpinocorpus::CorpusReader::XPATH,
false, query.toUtf8().constData());
}
void QueryModel::cancelQuery()
{
d_cancelled = true;
d_entryIterator.interrupt();
d_entriesFuture.waitForFinished();
d_timer->stop();
}
void QueryModel::finalizeQuery(int n, int totalEntries, bool cached)
{
// Just to make shure, otherwise data() will go completely crazy
Q_ASSERT(d_hitsIndex.size() == d_results.size());
layoutChanged(); // Please, don't do this. Let's copy FilterModel's implementation.
if (!cached)
{
d_entryCache->insert(d_query, new CacheItem(d_totalHits, d_hitsIndex, d_results));
// this index is no longer needed, as it is only used for constructing d_hitsIndex
d_valueIndex.clear();
}
}
// run async, because query() starts searching immediately
void QueryModel::getEntriesWithQuery(QString const &query)
{
try {
if (d_entryCache->contains(query))
{
{
QMutexLocker locker(&d_resultsMutex);
CacheItem *cachedResult = d_entryCache->object(query);
d_totalHits = cachedResult->hits;
d_hitsIndex = cachedResult->index;
d_results = cachedResult->entries;
}
emit queryFinished(d_results.size(), d_results.size(), true);
return;
}
QueryModel::getEntries(
d_corpus->query(alpinocorpus::CorpusReader::XPATH, query.toUtf8().constData()));
} catch (std::exception const &e) {
qDebug() << "Error in QueryModel::getEntries: " << e.what();
emit queryFailed(e.what());
}
}
// run async
void QueryModel::getEntries(EntryIterator const &i)
{
if (i.hasProgress())
emit queryStarted(100);
else
emit queryStarted(0);
try {
d_cancelled = false;
d_entryIterator = i;
while (!d_cancelled && d_entryIterator.hasNext())
{
alpinocorpus::Entry e = d_entryIterator.next(*d_corpus);
emit queryEntryFound(QString::fromUtf8(e.contents.c_str()));
}
if (d_cancelled)
emit queryStopped(d_results.size(), d_results.size());
else
emit queryFinished(d_results.size(), d_results.size(), false);
}
// Catch d_entryIterator.interrupt()'s shockwaves of terror
catch (alpinocorpus::IterationInterrupted const &e) {
emit queryStopped(d_results.size(), d_results.size());
}
catch (alpinocorpus::Error const &e) {
qDebug() << "Error in QueryModel::getEntries: " << e.what();
emit queryFailed(e.what());
}
}
void QueryModel::stopProgress()
{
d_timer->stop();
}
<|endoftext|>
|
<commit_before>/****************************************************************************
*
* Copyright (C) 2013 PX4 Development Team. All rights reserved.
* Author: Pavel Kirienko <pavel.kirienko@gmail.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
// TODO: rewrite in C++
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ch.h>
#include <hal.h>
#include <shell.h>
#include <unistd.h>
#include <board/board.hpp>
#include <motor/motor.h>
#include "console.hpp"
#pragma GCC diagnostic ignored "-Wunused-parameter"
static void cmd_cfg(BaseSequentialStream *, int argc, char *argv[])
{
// TODO: refuse to save/erase while the motor is running
os::config::executeCLICommand(argc, argv);
}
static void cmd_reset(BaseSequentialStream *chp, int argc, char *argv[])
{
::usleep(10000); // Flush serial
board::reboot();
}
static void cmd_beep(BaseSequentialStream *chp, int argc, char *argv[])
{
if (argc > 0 && !strcmp(argv[0], "help")) {
puts("beep [freq_hz [duration_msec]]");
return;
}
int freq = 500;
if (argc > 0) {
freq = atoi(argv[0]);
}
int duration = 300;
if (argc > 1) {
duration = atoi(argv[1]);
}
motor_beep(freq, duration);
}
static void cmd_stat(BaseSequentialStream *chp, int argc, char *argv[])
{
float voltage = 0, current = 0;
motor_get_input_voltage_current(&voltage, ¤t);
std::printf("Power V/A %-9f %f\n", voltage, current);
std::printf("RPM/DC %-9u %f\n", motor_get_rpm(), motor_get_duty_cycle());
std::printf("Active limits %i\n", motor_get_limit_mask());
std::printf("ZC failures %lu\n", (unsigned long)motor_get_zc_failures_since_start());
}
static void cmd_test(BaseSequentialStream *chp, int argc, char *argv[])
{
puts("Hardware test...");
int res = motor_test_hardware();
if (res) {
std::printf("FAILED %i\n", res);
} else {
puts("OK");
}
puts("Motor test...");
res = motor_test_motor();
puts(res ? "Not connected" : "Connected");
}
static void cmd_dc(BaseSequentialStream *chp, int argc, char *argv[])
{
static const int TTL_MS = 30000;
if (argc == 0) {
motor_stop();
puts("Usage:\n"
" dc <duty cycle>\n"
" dc arm");
return;
}
// Safety check
static bool _armed = false;
if (!strcmp(argv[0], "arm")) {
_armed = true;
puts("OK");
return;
}
if (!_armed) {
puts("Error: Not armed");
return;
}
const float value = atoff(argv[0]);
std::printf("Duty cycle %f\n", value);
motor_set_duty_cycle(value, TTL_MS);
}
static void cmd_rpm(BaseSequentialStream *chp, int argc, char *argv[])
{
static const int TTL_MS = 30000;
if (argc == 0) {
motor_stop();
puts("Usage:\n"
" rpm <RPM>\n"
" rpm arm");
return;
}
// Safety check
static bool _armed = false;
if (!strcmp(argv[0], "arm")) {
_armed = true;
puts("OK");
return;
}
if (!_armed) {
puts("Error: Not armed");
return;
}
long value = (long)atoff(argv[0]);
value = (value < 0) ? 0 : value;
value = (value > 65535) ? 65535 : value;
std::printf("RPM %li\n", value);
motor_set_rpm((unsigned)value, TTL_MS);
}
static void cmd_md(BaseSequentialStream *chp, int argc, char *argv[])
{
motor_print_debug_info();
}
static void cmd_m(BaseSequentialStream *chp, int argc, char *argv[])
{
motor_execute_cli_command(argc, (const char**)argv);
}
#define COMMAND(cmd) {#cmd, cmd_##cmd},
static const ShellCommand _commands[] =
{
COMMAND(cfg)
COMMAND(reset)
COMMAND(beep)
COMMAND(stat)
COMMAND(test)
COMMAND(dc)
COMMAND(rpm)
COMMAND(md)
COMMAND(m)
{NULL, NULL}
};
// --------------------------
static const ShellConfig _config = {(BaseSequentialStream*)&STDOUT_SD, _commands};
static THD_WORKING_AREA(_wa_shell, 1024);
void console_init(void)
{
shellInit();
ASSERT_ALWAYS(shellCreateStatic(&_config, _wa_shell, sizeof(_wa_shell), LOWPRIO));
}
<commit_msg>CLI reboot command<commit_after>/****************************************************************************
*
* Copyright (C) 2013 PX4 Development Team. All rights reserved.
* Author: Pavel Kirienko <pavel.kirienko@gmail.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
// TODO: rewrite in C++
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ch.h>
#include <hal.h>
#include <shell.h>
#include <unistd.h>
#include <board/board.hpp>
#include <motor/motor.h>
#include "console.hpp"
#pragma GCC diagnostic ignored "-Wunused-parameter"
static void cmd_cfg(BaseSequentialStream *, int argc, char *argv[])
{
// TODO: refuse to save/erase while the motor is running
os::config::executeCLICommand(argc, argv);
}
static void cmd_reboot(BaseSequentialStream *chp, int argc, char *argv[])
{
::usleep(10000); // Flush serial
board::reboot();
}
static void cmd_beep(BaseSequentialStream *chp, int argc, char *argv[])
{
if (argc > 0 && !strcmp(argv[0], "help")) {
puts("beep [freq_hz [duration_msec]]");
return;
}
int freq = 500;
if (argc > 0) {
freq = atoi(argv[0]);
}
int duration = 300;
if (argc > 1) {
duration = atoi(argv[1]);
}
motor_beep(freq, duration);
}
static void cmd_stat(BaseSequentialStream *chp, int argc, char *argv[])
{
float voltage = 0, current = 0;
motor_get_input_voltage_current(&voltage, ¤t);
std::printf("Power V/A %-9f %f\n", voltage, current);
std::printf("RPM/DC %-9u %f\n", motor_get_rpm(), motor_get_duty_cycle());
std::printf("Active limits %i\n", motor_get_limit_mask());
std::printf("ZC failures %lu\n", (unsigned long)motor_get_zc_failures_since_start());
}
static void cmd_test(BaseSequentialStream *chp, int argc, char *argv[])
{
puts("Hardware test...");
int res = motor_test_hardware();
if (res) {
std::printf("FAILED %i\n", res);
} else {
puts("OK");
}
puts("Motor test...");
res = motor_test_motor();
puts(res ? "Not connected" : "Connected");
}
static void cmd_dc(BaseSequentialStream *chp, int argc, char *argv[])
{
static const int TTL_MS = 30000;
if (argc == 0) {
motor_stop();
puts("Usage:\n"
" dc <duty cycle>\n"
" dc arm");
return;
}
// Safety check
static bool _armed = false;
if (!strcmp(argv[0], "arm")) {
_armed = true;
puts("OK");
return;
}
if (!_armed) {
puts("Error: Not armed");
return;
}
const float value = atoff(argv[0]);
std::printf("Duty cycle %f\n", value);
motor_set_duty_cycle(value, TTL_MS);
}
static void cmd_rpm(BaseSequentialStream *chp, int argc, char *argv[])
{
static const int TTL_MS = 30000;
if (argc == 0) {
motor_stop();
puts("Usage:\n"
" rpm <RPM>\n"
" rpm arm");
return;
}
// Safety check
static bool _armed = false;
if (!strcmp(argv[0], "arm")) {
_armed = true;
puts("OK");
return;
}
if (!_armed) {
puts("Error: Not armed");
return;
}
long value = (long)atoff(argv[0]);
value = (value < 0) ? 0 : value;
value = (value > 65535) ? 65535 : value;
std::printf("RPM %li\n", value);
motor_set_rpm((unsigned)value, TTL_MS);
}
static void cmd_md(BaseSequentialStream *chp, int argc, char *argv[])
{
motor_print_debug_info();
}
static void cmd_m(BaseSequentialStream *chp, int argc, char *argv[])
{
motor_execute_cli_command(argc, (const char**)argv);
}
#define COMMAND(cmd) {#cmd, cmd_##cmd},
static const ShellCommand _commands[] =
{
COMMAND(cfg)
COMMAND(reboot)
COMMAND(beep)
COMMAND(stat)
COMMAND(test)
COMMAND(dc)
COMMAND(rpm)
COMMAND(md)
COMMAND(m)
{NULL, NULL}
};
// --------------------------
static const ShellConfig _config = {(BaseSequentialStream*)&STDOUT_SD, _commands};
static THD_WORKING_AREA(_wa_shell, 1024);
void console_init(void)
{
shellInit();
ASSERT_ALWAYS(shellCreateStatic(&_config, _wa_shell, sizeof(_wa_shell), LOWPRIO));
}
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "FunctionContext.hpp"
#include "Labels.hpp"
#include "asm/Registers.hpp"
#include "ltac/Compiler.hpp"
#include "mtac/Utils.hpp" //TODO Perhaps this should be moved to ltac ?
using namespace eddic;
void add_instruction(std::shared_ptr<ltac::Function> function, ltac::Operator op, ltac::Argument arg1){
function->add(std::make_shared<ltac::Instruction>(op, arg1));
}
void add_instruction(std::shared_ptr<ltac::Function> function, ltac::Operator op, ltac::Argument arg1, ltac::Argument arg2){
function->add(std::make_shared<ltac::Instruction>(op, arg1, arg2));
}
void ltac::Compiler::compile(std::shared_ptr<mtac::Program> source, std::shared_ptr<ltac::Program> target){
for(auto& src_function : source->functions){
auto target_function = std::make_shared<ltac::Function>(src_function->context, src_function->getName());
target->functions.push_back(target_function);
compile(src_function, target_function);
}
}
void ltac::Compiler::compile(std::shared_ptr<mtac::Function> src_function, std::shared_ptr<ltac::Function> target_function){
auto size = src_function->context->size();
//Only if necessary, allocates size on the stack for the local variables
if(size > 0){
add_instruction(target_function, ltac::Operator::ALLOC_STACK, size);
}
auto iter = src_function->context->begin();
auto end = src_function->context->end();
for(; iter != end; iter++){
auto var = iter->second;
if(var->type().isArray() && var->position().isStack()){
int position = -var->position().offset();
add_instruction(target_function, ltac::Operator::MOV, ltac::Address(ltac::BP, position), var->type().size());
if(var->type().base() == BaseType::INT){
add_instruction(target_function, ltac::Operator::MEMSET, ltac::Address(ltac::BP, position, -8), var->type().size());
} else if(var->type().base() == BaseType::STRING){
add_instruction(target_function, ltac::Operator::MEMSET, ltac::Address(ltac::BP, position, -8), 2 * var->type().size());
}
}
}
//Compute the block usage (in order to know if we have to output the label)
mtac::computeBlockUsage(src_function, block_usage);
resetNumbering();
//First we computes a label for each basic block
for(auto block : src_function->getBasicBlocks()){
block->label = newLabel();
}
//Then we compile each of them
for(auto block : src_function->getBasicBlocks()){
compile(block, target_function);
}
//TODO Return optimization
//Only if necessary, deallocates size on the stack for the local variables
if(size > 0){
add_instruction(target_function, ltac::Operator::FREE_STACK, size);
}
}
namespace {
struct StatementCompiler : public boost::static_visitor<> {
//The registers
as::Registers<ltac::Register> registers;
as::Registers<ltac::FloatRegister> float_registers;
StatementCompiler(std::vector<ltac::Register> registers, std::vector<ltac::FloatRegister> float_registers) :
registers(registers, std::make_shared<Variable>("__fake_int__", newSimpleType(BaseType::INT), Position(PositionType::TEMPORARY))),
float_registers(float_registers, std::make_shared<Variable>("__fake_float__", newSimpleType(BaseType::FLOAT), Position(PositionType::TEMPORARY))){
//Nothing else to init
}
};
} //end of anonymous namespace
void ltac::Compiler::compile(std::shared_ptr<mtac::BasicBlock> block, std::shared_ptr<ltac::Function> target_function){
//Handle parameters
//If necessary add a label for the block
if(block_usage.find(block) != block_usage.end()){
target_function->add(block->label);
}
//TODO Fill the registers
StatementCompiler compiler({}, {});
//statements
//end basic block
}
<commit_msg>Prepare the visitor<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "FunctionContext.hpp"
#include "Labels.hpp"
#include "VisitorUtils.hpp"
#include "asm/Registers.hpp"
#include "ltac/Compiler.hpp"
#include "mtac/Utils.hpp" //TODO Perhaps part of this should be moved to ltac ?
using namespace eddic;
void add_instruction(std::shared_ptr<ltac::Function> function, ltac::Operator op, ltac::Argument arg1){
function->add(std::make_shared<ltac::Instruction>(op, arg1));
}
void add_instruction(std::shared_ptr<ltac::Function> function, ltac::Operator op, ltac::Argument arg1, ltac::Argument arg2){
function->add(std::make_shared<ltac::Instruction>(op, arg1, arg2));
}
void ltac::Compiler::compile(std::shared_ptr<mtac::Program> source, std::shared_ptr<ltac::Program> target){
for(auto& src_function : source->functions){
auto target_function = std::make_shared<ltac::Function>(src_function->context, src_function->getName());
target->functions.push_back(target_function);
compile(src_function, target_function);
}
}
void ltac::Compiler::compile(std::shared_ptr<mtac::Function> src_function, std::shared_ptr<ltac::Function> target_function){
auto size = src_function->context->size();
//Only if necessary, allocates size on the stack for the local variables
if(size > 0){
add_instruction(target_function, ltac::Operator::ALLOC_STACK, size);
}
auto iter = src_function->context->begin();
auto end = src_function->context->end();
for(; iter != end; iter++){
auto var = iter->second;
if(var->type().isArray() && var->position().isStack()){
int position = -var->position().offset();
add_instruction(target_function, ltac::Operator::MOV, ltac::Address(ltac::BP, position), var->type().size());
if(var->type().base() == BaseType::INT){
add_instruction(target_function, ltac::Operator::MEMSET, ltac::Address(ltac::BP, position, -8), var->type().size());
} else if(var->type().base() == BaseType::STRING){
add_instruction(target_function, ltac::Operator::MEMSET, ltac::Address(ltac::BP, position, -8), 2 * var->type().size());
}
}
}
//Compute the block usage (in order to know if we have to output the label)
mtac::computeBlockUsage(src_function, block_usage);
resetNumbering();
//First we computes a label for each basic block
for(auto block : src_function->getBasicBlocks()){
block->label = newLabel();
}
//Then we compile each of them
for(auto block : src_function->getBasicBlocks()){
compile(block, target_function);
}
//TODO Return optimization
//Only if necessary, deallocates size on the stack for the local variables
if(size > 0){
add_instruction(target_function, ltac::Operator::FREE_STACK, size);
}
}
namespace {
struct StatementCompiler : public boost::static_visitor<> {
//The registers
as::Registers<ltac::Register> registers;
as::Registers<ltac::FloatRegister> float_registers;
bool last = false;
mtac::Statement next;
StatementCompiler(std::vector<ltac::Register> registers, std::vector<ltac::FloatRegister> float_registers) :
registers(registers, std::make_shared<Variable>("__fake_int__", newSimpleType(BaseType::INT), Position(PositionType::TEMPORARY))),
float_registers(float_registers, std::make_shared<Variable>("__fake_float__", newSimpleType(BaseType::FLOAT), Position(PositionType::TEMPORARY))){
//Nothing else to init
}
};
} //end of anonymous namespace
void ltac::Compiler::compile(std::shared_ptr<mtac::BasicBlock> block, std::shared_ptr<ltac::Function> target_function){
//Handle parameters
//If necessary add a label for the block
if(block_usage.find(block) != block_usage.end()){
target_function->add(block->label);
}
//TODO Fill the registers
StatementCompiler compiler({}, {});
for(unsigned int i = 0; i < block->statements.size(); ++i){
auto& statement = block->statements[i];
if(i == block->statements.size() - 1){
compiler.last = true;
} else {
compiler.next = block->statements[i+1];
}
visit(compiler, statement);
}
//end basic block
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <fstream>
#include <ios>
#include <string.h>
#include <stdio.h>
#include <errno.h>
/* include */
#include "lzma2_wrapper.h"
#include "log.h"
/* extern */
#include "Lzma2Encoder.h"
#include "C/LzmaLib.h"
#include "C/7zTypes.h"
#include "C/Alloc.h"
/* function implementation for struct ISzAlloc
* see examples in LzmaUtil.c and C/alloc.c
*/
static void *SzAlloc(void *p, size_t size)
{
p = p;
return MyAlloc(size); // just a malloc call...
}
/* function implementation for struct ISzAlloc
* see examples in LzmaUtil.c and C/alloc.c
*/
static void SzFree(void *p, void *address)
{
p = p;
MyFree(address); // just a free call ...
}
const ISzAlloc g_Alloc = {szAlloc, szFree};
/* Read raw data from a filedescriptor
* INPUT:
* FILE *fd - file descriptor
* unsigned char *data - buffer that will hold the read
* data
* size_t *data_len - the size of the read data, this will
* also indicate when we have reached the end of the file
* OUTPUT:
* 2 - more data
* 1 - last chunk of data
* 0 - end of file
* -1 failure
*/
static int read_data(FILE *fd, unsigned char *data, size_t *data_len)
{
*data_len = fread(data, sizeof(unsigned char),
buffer_cread_size, fd);
if (*data_len == buffer_cread_size)
return 2;
else if (*data_len > 0)
return 1;
else
return 0;
}
/* write raw data to a filedescriptor
* INPUT:
* FILE *fd - file descriptor
* unsigned char *data - buffer holds the data
* size_t *data_len - the size of the data buffer
* OUTPUT:
* 1 - success
* 0 - failure
*/
static int write_data(FILE *fd, unsigned char *data, size_t data_len)
{
data_len = fwrite(data, sizeof(unsigned char),
data_len, fd);
if (data_len == buffer_cread_size)
return 1;
else
return 0;
}
static int open_io_files(const char *in_path, const char*out_path,
FILE *fd[])
{
fd[0] = fopen(in_path, "r");
if (fd[0] == NULL) {
log_msg("Error opening input file for compression: %s\n",
strerror(errno));
goto cleanup;
}
fd[1] = fopen(out_path, "w");
if (fd[0] == NULL) {
log_msg("Error opening output file for compression: %s\n",
strerror(errno));
goto cleanup;
}
return 1;
cleanup:
if (fd[0] != NULL)
fclose(fd[0]);
if (fd[1] != NULL)
fclose(fd[1]);
return 0;
}
int compress_file(const char *in_path, const char *out_path)
{
FILE *fd[2]; /* i/o file descriptors */
unsigned char input[buffer_cread_size]; /* i/o buffers */
unsigned char output[buffer_cread_size];
int count = 1;
size_t input_len = buffer_cread_size; /* buffer sizes */
size_t output_len = buffer_cread_size;
/* open i/o files, return fail if this failes */
if (!open_io_files(in_path, out_path, fd))
return 0;
/* read the file */
while(read_data(fd[0], input, &input_len)) {
/* this is not accurate at the end,
* a good approximate though */
printf("%d bytes compressesd\n",
count * buffer_cread_size);
count++;
/* compress data and write to output */
compress_data(input, input_len,
output, &output_len);
write_data(fd[1], output, output_len);
}
if (fd[0] != NULL)
fclose(fd[0]);
if (fd[1] != NULL)
fclose(fd[1]);
return 1;
}
int compress_data(unsigned char *input, size_t input_len,
unsigned char *output, size_t *output_len)
{
size_t props_size = LZMA_PROPS_SIZE;
/* &output[LZMA_PROPS_SIZE] specifies where to store the data
* &output_len stores the size of the output data
* input specifies the input data
* input_len specifies the size of the input data
* &output[0] specifies where to store prop info
* &props_size specifies the size of the prop info
*/
int rt = LzmaCompress(&output[LZMA_PROPS_SIZE], output_len,
input, input_len,
&output[0], &props_size,
-1, // level
0, // dictSize
-1, // lc (literal context bits)
-1, // lp (literal position bits)
-1, // pb (position bits)
-1, // fb (word size)
-1); // numThreads (number of threads)
if (rt != SZ_OK) {
log_msg ("Failed to compress data: error %d", rt);
return 0;
}
return 1;
}
int decompress_data(unsigned char *input, size_t input_len,
unsigned char *output, size_t *output_len)
{
/* output - specifies where to store uncompressed data
* output_len - stores the length of the uncompressed data
* input[LZMA_PROPS_SIZE] - position of the data in the input buffer
* &input_len - length of the input buffer
* &input[0] - position of the prop info
* LZMA_PROPS_SIZE - prop size
*/
int rt = LzmaUncompress(output, output_len,
&input[LZMA_PROPS_SIZE], &input_len,
&input[0], LZMA_PROPS_SIZE);
if (rt != SZ_OK) {
log_msg ("Failed to decompress data: error %d", rt);
return 0;
}
return 1;
}
int in_stream_read(void *p, void *buf, size_t *size)
{
/* CLzmaEncHandle is just a pointer */
CLzmaEncHandle enc_hand = LzmaEnc_Create(g_Alloc);
if (enc_hand == NULL) {
log_msg ("Error allocating mem when reading stream");
return SZ_ERROR_MEM;
}
/* create the prop, note the prop is the header of the
* compressed file
*/
CLzmaEncProps prop_info;
int rt = LzmaEncProps_Init(&prop_info);
/* if prop wasnt initialized correctly return fail */
if (rt != SZ_OK)
goto end;
end:
LzmaEnc_Destroy(enc, &g_Alloc, g_Alloc);
return rt;
}
<commit_msg>fixing compile errors<commit_after>#include <iostream>
#include <fstream>
#include <ios>
#include <string.h>
#include <stdio.h>
#include <errno.h>
/* include */
#include "lzma2_wrapper.h"
#include "log.h"
/* extern */
#include "Lzma2Encoder.h"
#include "C/LzmaLib.h"
#include "C/7zTypes.h"
#include "C/Alloc.h"
/* function implementation for struct ISzAlloc
* see examples in LzmaUtil.c and C/alloc.c
*/
static void *szAlloc(void *p, size_t size)
{
p = p;
return MyAlloc(size); // just a malloc call...
}
/* function implementation for struct ISzAlloc
* see examples in LzmaUtil.c and C/alloc.c
*/
static void szFree(void *p, void *address)
{
p = p;
MyFree(address); // just a free call ...
}
static const ISzAlloc g_Alloc = {szAlloc, szFree};
/* Read raw data from a filedescriptor
* INPUT:
* FILE *fd - file descriptor
* unsigned char *data - buffer that will hold the read
* data
* size_t *data_len - the size of the read data, this will
* also indicate when we have reached the end of the file
* OUTPUT:
* 2 - more data
* 1 - last chunk of data
* 0 - end of file
* -1 failure
*/
static int read_data(FILE *fd, unsigned char *data, size_t *data_len)
{
*data_len = fread(data, sizeof(unsigned char),
buffer_cread_size, fd);
if (*data_len == buffer_cread_size)
return 2;
else if (*data_len > 0)
return 1;
else
return 0;
}
/* write raw data to a filedescriptor
* INPUT:
* FILE *fd - file descriptor
* unsigned char *data - buffer holds the data
* size_t *data_len - the size of the data buffer
* OUTPUT:
* 1 - success
* 0 - failure
*/
static int write_data(FILE *fd, unsigned char *data, size_t data_len)
{
data_len = fwrite(data, sizeof(unsigned char),
data_len, fd);
if (data_len == buffer_cread_size)
return 1;
else
return 0;
}
static int open_io_files(const char *in_path, const char*out_path,
FILE *fd[])
{
fd[0] = fopen(in_path, "r");
if (fd[0] == NULL) {
log_msg("Error opening input file for compression: %s\n",
strerror(errno));
goto cleanup;
}
fd[1] = fopen(out_path, "w");
if (fd[0] == NULL) {
log_msg("Error opening output file for compression: %s\n",
strerror(errno));
goto cleanup;
}
return 1;
cleanup:
if (fd[0] != NULL)
fclose(fd[0]);
if (fd[1] != NULL)
fclose(fd[1]);
return 0;
}
int compress_file(const char *in_path, const char *out_path)
{
FILE *fd[2]; /* i/o file descriptors */
unsigned char input[buffer_cread_size]; /* i/o buffers */
unsigned char output[buffer_cread_size];
int count = 1;
size_t input_len = buffer_cread_size; /* buffer sizes */
size_t output_len = buffer_cread_size;
/* open i/o files, return fail if this failes */
if (!open_io_files(in_path, out_path, fd))
return 0;
/* read the file */
while(read_data(fd[0], input, &input_len)) {
/* this is not accurate at the end,
* a good approximate though */
printf("%d bytes compressesd\n",
count * buffer_cread_size);
count++;
/* compress data and write to output */
compress_data(input, input_len,
output, &output_len);
write_data(fd[1], output, output_len);
}
if (fd[0] != NULL)
fclose(fd[0]);
if (fd[1] != NULL)
fclose(fd[1]);
return 1;
}
int compress_data(unsigned char *input, size_t input_len,
unsigned char *output, size_t *output_len)
{
size_t props_size = LZMA_PROPS_SIZE;
/* &output[LZMA_PROPS_SIZE] specifies where to store the data
* &output_len stores the size of the output data
* input specifies the input data
* input_len specifies the size of the input data
* &output[0] specifies where to store prop info
* &props_size specifies the size of the prop info
*/
int rt = LzmaCompress(&output[LZMA_PROPS_SIZE], output_len,
input, input_len,
&output[0], &props_size,
-1, // level
0, // dictSize
-1, // lc (literal context bits)
-1, // lp (literal position bits)
-1, // pb (position bits)
-1, // fb (word size)
-1); // numThreads (number of threads)
if (rt != SZ_OK) {
log_msg ("Failed to compress data: error %d", rt);
return 0;
}
return 1;
}
int decompress_data(unsigned char *input, size_t input_len,
unsigned char *output, size_t *output_len)
{
/* output - specifies where to store uncompressed data
* output_len - stores the length of the uncompressed data
* input[LZMA_PROPS_SIZE] - position of the data in the input buffer
* &input_len - length of the input buffer
* &input[0] - position of the prop info
* LZMA_PROPS_SIZE - prop size
*/
int rt = LzmaUncompress(output, output_len,
&input[LZMA_PROPS_SIZE], &input_len,
&input[0], LZMA_PROPS_SIZE);
if (rt != SZ_OK) {
log_msg ("Failed to decompress data: error %d", rt);
return 0;
}
return 1;
}
int in_stream_read(void *p, void *buf, size_t *size)
{
/* CLzmaEncHandle is just a pointer */
CLzmaEncHandle enc_hand = LzmaEnc_Create(g_Alloc);
if (enc_hand == NULL) {
log_msg ("Error allocating mem when reading stream");
return SZ_ERROR_MEM;
}
/* create the prop, note the prop is the header of the
* compressed file
*/
CLzmaEncProps prop_info;
int rt = LzmaEncProps_Init(&prop_info);
/* if prop wasnt initialized correctly return fail */
if (rt != SZ_OK)
goto end;
end:
LzmaEnc_Destroy(enc, &g_Alloc, g_Alloc);
return rt;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <wait.h>
#include <string.h>
#include <string>
#include <vector>
#include <cstdlib>
#include <stdlib.h>
#include <stdio.h>
#include <boost/tokenizer.hpp>
#include <boost/token_iterator.hpp>
#include <fcntl.h>
#include <errno.h>
#include <dirent.h>
#include <set>
#include <pwd.h>
#include <grp.h>
#include <time.h>
using namespace boost;
using namespace std;
int main(int argc, char ** argv){
if(argc<3){
cerr << "mv: missing destination file operand" << endl;
return -1;
}
vector<string> holder;
for(unsigned int i = 1; i<argc; i++){
holder.push_back(string(argv[i]));
}
DIR *dirp;
struct stat s;
if(stat(holder[0].c_str(), &s) == -1){
perror("stat");
exit(1);
}
if( NULL == (dirp = opendir(holder[1].c_str()))){
cerr << holder[1] << "does not exist" << endl;
}
else{
if(stat(holder[1].c_str(), &s)==-1){
perror("stat");
exit(1);
}
if(S_IFDIR & s.st_mode){
if(-1 == link(holder[0].c_str(), (holder[1] + '/' + holder[0]).c_str())){
perror("link");
exit(1);
}
if(-1 == unlink(holder[0].c_str())){
perror("unlink");
exit(1);
}
}
}
return 0;
}
<commit_msg>updated mv.cpp<commit_after>#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <wait.h>
#include <string.h>
#include <string>
#include <vector>
#include <cstdlib>
#include <stdlib.h>
#include <stdio.h>
#include <boost/tokenizer.hpp>
#include <boost/token_iterator.hpp>
#include <fcntl.h>
#include <errno.h>
#include <dirent.h>
#include <set>
#include <pwd.h>
#include <grp.h>
#include <time.h>
using namespace boost;
using namespace std;
int main(int argc, char ** argv){
if(argc<3){
cerr << "mv: missing destination file operand" << endl;
return -1;
}
vector<string> holder;
for(unsigned int i = 1; i<argc; i++){
holder.push_back(string(argv[i]));
}
DIR *dirp;
struct stat s;
if(stat(holder[0].c_str(), &s) == -1){
perror("stat");
exit(1);
}
if(stat(holder[1].c_str(), &s)!=-1){ // if exists
if(S_IFDIR & s.st_mode){ //is a dir
if( NULL == (dirp = opendir(holder[1].c_str()))){
cerr << holder[1] << "does not exist" << endl;
exit(1);
}
if(-1 == link(holder[0].c_str(), (holder[1] + '/' + holder[0]).c_str())){
perror("link");
exit(1);
}
if(-1 == unlink(holder[0].c_str())){
perror("unlink");
exit(1);
}
}
}
else{ //not exist
if(-1 == link(holder[0].c_str(), holder[1].c_str())){
perror("link");
exit(1);
}
if(-1 == unlink(holder[0].c_str())){
perror("unlink");
exit(1);
}
}
return 0;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkFEMLinearSystemWrapper.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#include "itkFEMLinearSystemWrapper.h"
namespace itk {
namespace fem {
void LinearSystemWrapper::ScaleMatrix(Float scale, unsigned int matrixIndex)
{
/* FIX ME: error checking */
/* check for no scaling */
if (scale == 1.0)
{
return;
}
int i;
int j;
for (i=0; i<m_Order; i++)
{
for (j=0; j<m_Order; j++)
{
this->SetMatrixValue(i, j, scale*GetMatrixValue(i,j,matrixIndex), matrixIndex);
}
}
return;
}
void LinearSystemWrapper::ScaleVector(Float scale, unsigned int vectorIndex)
{
/* FIX ME: error checking */
/* check for no scaling */
if (scale == 1.0)
{
return;
}
int i;
for (i=0; i<m_Order; i++)
{
this->SetVectorValue(i, scale * GetVectorValue(i, vectorIndex), vectorIndex);
}
return;
}
void LinearSystemWrapper::ScaleSolution(Float scale, unsigned int solutionIndex)
{
/* FIX ME: error checking */
/* check for no scaling */
if (scale == 1.0)
{
return;
}
int i;
for (i=0; i<m_Order; i++)
{
this->SetSolutionValue(i, scale * GetSolutionValue(i, solutionIndex), solutionIndex);
}
return;
}
void LinearSystemWrapper::AddVectorValue(unsigned int i, Float value, unsigned int vectorIndex)
{
this->SetVectorValue(i, value+this->GetVectorValue(i, vectorIndex), vectorIndex);
}
void LinearSystemWrapper::AddMatrixValue(unsigned int i, unsigned int j, Float value, unsigned int matrixIndex)
{
this->SetMatrixValue(i, j, value+this->GetMatrixValue(i, j, matrixIndex), matrixIndex);
}
void LinearSystemWrapper::MultiplyMatrixVector(unsigned int resultVector, unsigned int matrixIndex, unsigned int vectorIndex)
{
/* FIX ME: error checking */
int i;
int j;
this->InitializeVector(resultVector);
/* perform multiply */
for (i=0; i<m_Order; i++)
{
for (j=0; j<m_Order; j++)
{
this->AddVectorValue(i, this->GetMatrixValue(i,j,matrixIndex) * this->GetVectorValue(j, vectorIndex), resultVector);
}
}
}
}}
<commit_msg>ENH: added solution vector methods<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkFEMLinearSystemWrapper.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#include "itkFEMLinearSystemWrapper.h"
namespace itk {
namespace fem {
void LinearSystemWrapper::ScaleMatrix(Float scale, unsigned int matrixIndex)
{
/* FIX ME: error checking */
/* check for no scaling */
if (scale == 1.0)
{
return;
}
int i;
int j;
for (i=0; i<m_Order; i++)
{
for (j=0; j<m_Order; j++)
{
this->SetMatrixValue(i, j, scale*GetMatrixValue(i,j,matrixIndex), matrixIndex);
}
}
return;
}
void LinearSystemWrapper::ScaleVector(Float scale, unsigned int vectorIndex)
{
/* FIX ME: error checking */
/* check for no scaling */
if (scale == 1.0)
{
return;
}
int i;
for (i=0; i<m_Order; i++)
{
this->SetVectorValue(i, scale * GetVectorValue(i, vectorIndex), vectorIndex);
}
return;
}
void LinearSystemWrapper::ScaleSolution(Float scale, unsigned int solutionIndex)
{
/* FIX ME: error checking */
/* check for no scaling */
if (scale == 1.0)
{
return;
}
int i;
for (i=0; i<m_Order; i++)
{
this->SetSolutionValue(i, scale * GetSolutionValue(i, solutionIndex), solutionIndex);
}
return;
}
void LinearSystemWrapper::AddVectorValue(unsigned int i, Float value, unsigned int vectorIndex)
{
this->SetVectorValue(i, value+this->GetVectorValue(i, vectorIndex), vectorIndex);
}
void LinearSystemWrapper::AddMatrixValue(unsigned int i, unsigned int j, Float value, unsigned int matrixIndex)
{
this->SetMatrixValue(i, j, value+this->GetMatrixValue(i, j, matrixIndex), matrixIndex);
}
void LinearSystemWrapper::AddSolutionValue(unsigned int i, Float value, unsigned int solutionIndex)
{
this->SetSolutionValue(i, value+this->GetSolutionValue(i, solutionIndex), solutionIndex);
}
void LinearSystemWrapper::MultiplyMatrixVector(unsigned int resultVector, unsigned int matrixIndex, unsigned int vectorIndex)
{
/* FIX ME: error checking */
int i;
int j;
this->InitializeVector(resultVector);
/* perform multiply */
for (i=0; i<m_Order; i++)
{
for (j=0; j<m_Order; j++)
{
this->AddVectorValue(i, this->GetMatrixValue(i,j,matrixIndex) * this->GetVectorValue(j, vectorIndex), resultVector);
}
}
}
}}
<|endoftext|>
|
<commit_before>#include "common/upstream/load_stats_reporter.h"
#include "common/protobuf/protobuf.h"
namespace Envoy {
namespace Upstream {
LoadStatsReporter::LoadStatsReporter(const envoy::api::v2::core::Node& node,
ClusterManager& cluster_manager, Stats::Scope& scope,
Grpc::AsyncClientPtr async_client,
Event::Dispatcher& dispatcher,
MonotonicTimeSource& time_source)
: cm_(cluster_manager), stats_{ALL_LOAD_REPORTER_STATS(
POOL_COUNTER_PREFIX(scope, "load_reporter."))},
async_client_(std::move(async_client)),
service_method_(*Protobuf::DescriptorPool::generated_pool()->FindMethodByName(
"envoy.service.load_stats.v2.LoadReportingService.StreamLoadStats")),
time_source_(time_source) {
request_.mutable_node()->MergeFrom(node);
retry_timer_ = dispatcher.createTimer([this]() -> void { establishNewStream(); });
response_timer_ = dispatcher.createTimer([this]() -> void { sendLoadStatsRequest(); });
establishNewStream();
}
void LoadStatsReporter::setRetryTimer() {
retry_timer_->enableTimer(std::chrono::milliseconds(RETRY_DELAY_MS));
}
void LoadStatsReporter::establishNewStream() {
ENVOY_LOG(debug, "Establishing new gRPC bidi stream for {}", service_method_.DebugString());
stream_ = async_client_->start(service_method_, *this);
if (stream_ == nullptr) {
ENVOY_LOG(warn, "Unable to establish new stream");
handleFailure();
return;
}
request_.mutable_cluster_stats()->Clear();
sendLoadStatsRequest();
}
void LoadStatsReporter::sendLoadStatsRequest() {
request_.mutable_cluster_stats()->Clear();
for (const auto& cluster_name_and_timestamp : clusters_) {
const std::string& cluster_name = cluster_name_and_timestamp.first;
auto cluster_info_map = cm_.clusters();
auto it = cluster_info_map.find(cluster_name);
if (it == cluster_info_map.end()) {
ENVOY_LOG(debug, "Cluster {} does not exist", cluster_name);
continue;
}
auto& cluster = it->second.get();
auto* cluster_stats = request_.add_cluster_stats();
cluster_stats->set_cluster_name(cluster_name);
for (auto& host_set : cluster.prioritySet().hostSetsPerPriority()) {
ENVOY_LOG(trace, "Load report locality count {}", host_set->hostsPerLocality().get().size());
for (auto& hosts : host_set->hostsPerLocality().get()) {
ASSERT(hosts.size() > 0);
uint64_t rq_success = 0;
uint64_t rq_error = 0;
uint64_t rq_active = 0;
for (auto host : hosts) {
rq_success += host->stats().rq_success_.latch();
rq_error += host->stats().rq_error_.latch();
rq_active += host->stats().rq_active_.value();
}
if (rq_success + rq_error + rq_active != 0) {
auto* locality_stats = cluster_stats->add_upstream_locality_stats();
locality_stats->mutable_locality()->MergeFrom(hosts[0]->locality());
locality_stats->set_priority(host_set->priority());
locality_stats->set_total_successful_requests(rq_success);
locality_stats->set_total_error_requests(rq_error);
locality_stats->set_total_requests_in_progress(rq_active);
}
}
}
cluster_stats->set_total_dropped_requests(
cluster.info()->loadReportStats().upstream_rq_dropped_.latch());
const auto now = time_source_.currentTime().time_since_epoch();
const auto measured_interval = now - cluster_name_and_timestamp.second;
cluster_stats->mutable_load_report_interval()->MergeFrom(
Protobuf::util::TimeUtil::MicrosecondsToDuration(
std::chrono::duration_cast<std::chrono::microseconds>(measured_interval).count()));
clusters_[cluster_name] = now;
}
ENVOY_LOG(trace, "Sending LoadStatsRequest: {}", request_.DebugString());
stream_->sendMessage(request_, false);
stats_.responses_.inc();
// When the connection is established, the message has not yet been read so we
// will not have a load reporting period.
if (message_.get()) {
startLoadReportPeriod();
}
}
void LoadStatsReporter::handleFailure() {
ENVOY_LOG(warn, "Load reporter stats stream/connection failure, will retry in {} ms.",
RETRY_DELAY_MS);
stats_.errors_.inc();
setRetryTimer();
}
void LoadStatsReporter::onCreateInitialMetadata(Http::HeaderMap& metadata) {
UNREFERENCED_PARAMETER(metadata);
}
void LoadStatsReporter::onReceiveInitialMetadata(Http::HeaderMapPtr&& metadata) {
UNREFERENCED_PARAMETER(metadata);
}
void LoadStatsReporter::onReceiveMessage(
std::unique_ptr<envoy::service::load_stats::v2::LoadStatsResponse>&& message) {
ENVOY_LOG(debug, "New load report epoch: {}", message->DebugString());
stats_.requests_.inc();
message_ = std::move(message);
startLoadReportPeriod();
}
void LoadStatsReporter::startLoadReportPeriod() {
// Once a cluster is tracked, we don't want to reset its stats between reports
// to avoid racing between request/response.
std::unordered_map<absl::string_view, std::chrono::steady_clock::duration, StringViewHash>
existing_clusters;
for (const std::string& cluster_name : message_->clusters()) {
if (clusters_.count(cluster_name) > 0) {
existing_clusters.emplace(cluster_name, clusters_[cluster_name]);
}
}
clusters_.clear();
// Reset stats for all hosts in clusters we are tracking.
for (const std::string& cluster_name : message_->clusters()) {
clusters_.emplace(cluster_name, existing_clusters.count(cluster_name) > 0
? existing_clusters[cluster_name]
: time_source_.currentTime().time_since_epoch());
auto cluster_info_map = cm_.clusters();
auto it = cluster_info_map.find(cluster_name);
if (it == cluster_info_map.end()) {
continue;
}
// Don't reset stats for existing tracked clusters.
if (existing_clusters.count(cluster_name) > 0) {
continue;
}
auto& cluster = it->second.get();
for (auto& host_set : cluster.prioritySet().hostSetsPerPriority()) {
for (auto host : host_set->hosts()) {
host->stats().rq_success_.latch();
host->stats().rq_error_.latch();
}
}
cluster.info()->loadReportStats().upstream_rq_dropped_.latch();
}
response_timer_->enableTimer(std::chrono::milliseconds(
DurationUtil::durationToMilliseconds(message_->load_reporting_interval())));
}
void LoadStatsReporter::onReceiveTrailingMetadata(Http::HeaderMapPtr&& metadata) {
UNREFERENCED_PARAMETER(metadata);
}
void LoadStatsReporter::onRemoteClose(Grpc::Status::GrpcStatus status, const std::string& message) {
ENVOY_LOG(warn, "gRPC config stream closed: {}, {}", status, message);
response_timer_->disableTimer();
stream_ = nullptr;
handleFailure();
}
} // namespace Upstream
} // namespace Envoy
<commit_msg>load_stats: fix for Google import. (#3900)<commit_after>#include "common/upstream/load_stats_reporter.h"
#include "common/protobuf/protobuf.h"
namespace Envoy {
namespace Upstream {
LoadStatsReporter::LoadStatsReporter(const envoy::api::v2::core::Node& node,
ClusterManager& cluster_manager, Stats::Scope& scope,
Grpc::AsyncClientPtr async_client,
Event::Dispatcher& dispatcher,
MonotonicTimeSource& time_source)
: cm_(cluster_manager), stats_{ALL_LOAD_REPORTER_STATS(
POOL_COUNTER_PREFIX(scope, "load_reporter."))},
async_client_(std::move(async_client)),
service_method_(*Protobuf::DescriptorPool::generated_pool()->FindMethodByName(
"envoy.service.load_stats.v2.LoadReportingService.StreamLoadStats")),
time_source_(time_source) {
request_.mutable_node()->MergeFrom(node);
retry_timer_ = dispatcher.createTimer([this]() -> void { establishNewStream(); });
response_timer_ = dispatcher.createTimer([this]() -> void { sendLoadStatsRequest(); });
establishNewStream();
}
void LoadStatsReporter::setRetryTimer() {
retry_timer_->enableTimer(std::chrono::milliseconds(RETRY_DELAY_MS));
}
void LoadStatsReporter::establishNewStream() {
ENVOY_LOG(debug, "Establishing new gRPC bidi stream for {}", service_method_.DebugString());
stream_ = async_client_->start(service_method_, *this);
if (stream_ == nullptr) {
ENVOY_LOG(warn, "Unable to establish new stream");
handleFailure();
return;
}
request_.mutable_cluster_stats()->Clear();
sendLoadStatsRequest();
}
void LoadStatsReporter::sendLoadStatsRequest() {
request_.mutable_cluster_stats()->Clear();
for (const auto& cluster_name_and_timestamp : clusters_) {
const std::string& cluster_name = cluster_name_and_timestamp.first;
auto cluster_info_map = cm_.clusters();
auto it = cluster_info_map.find(cluster_name);
if (it == cluster_info_map.end()) {
ENVOY_LOG(debug, "Cluster {} does not exist", cluster_name);
continue;
}
auto& cluster = it->second.get();
auto* cluster_stats = request_.add_cluster_stats();
cluster_stats->set_cluster_name(cluster_name);
for (auto& host_set : cluster.prioritySet().hostSetsPerPriority()) {
ENVOY_LOG(trace, "Load report locality count {}", host_set->hostsPerLocality().get().size());
for (auto& hosts : host_set->hostsPerLocality().get()) {
ASSERT(hosts.size() > 0);
uint64_t rq_success = 0;
uint64_t rq_error = 0;
uint64_t rq_active = 0;
for (auto host : hosts) {
rq_success += host->stats().rq_success_.latch();
rq_error += host->stats().rq_error_.latch();
rq_active += host->stats().rq_active_.value();
}
if (rq_success + rq_error + rq_active != 0) {
auto* locality_stats = cluster_stats->add_upstream_locality_stats();
locality_stats->mutable_locality()->MergeFrom(hosts[0]->locality());
locality_stats->set_priority(host_set->priority());
locality_stats->set_total_successful_requests(rq_success);
locality_stats->set_total_error_requests(rq_error);
locality_stats->set_total_requests_in_progress(rq_active);
}
}
}
cluster_stats->set_total_dropped_requests(
cluster.info()->loadReportStats().upstream_rq_dropped_.latch());
const auto now = time_source_.currentTime().time_since_epoch();
const auto measured_interval = now - cluster_name_and_timestamp.second;
cluster_stats->mutable_load_report_interval()->MergeFrom(
Protobuf::util::TimeUtil::MicrosecondsToDuration(
std::chrono::duration_cast<std::chrono::microseconds>(measured_interval).count()));
clusters_[cluster_name] = now;
}
ENVOY_LOG(trace, "Sending LoadStatsRequest: {}", request_.DebugString());
stream_->sendMessage(request_, false);
stats_.responses_.inc();
// When the connection is established, the message has not yet been read so we
// will not have a load reporting period.
if (message_.get()) {
startLoadReportPeriod();
}
}
void LoadStatsReporter::handleFailure() {
ENVOY_LOG(warn, "Load reporter stats stream/connection failure, will retry in {} ms.",
RETRY_DELAY_MS);
stats_.errors_.inc();
setRetryTimer();
}
void LoadStatsReporter::onCreateInitialMetadata(Http::HeaderMap& metadata) {
UNREFERENCED_PARAMETER(metadata);
}
void LoadStatsReporter::onReceiveInitialMetadata(Http::HeaderMapPtr&& metadata) {
UNREFERENCED_PARAMETER(metadata);
}
void LoadStatsReporter::onReceiveMessage(
std::unique_ptr<envoy::service::load_stats::v2::LoadStatsResponse>&& message) {
ENVOY_LOG(debug, "New load report epoch: {}", message->DebugString());
stats_.requests_.inc();
message_ = std::move(message);
startLoadReportPeriod();
}
void LoadStatsReporter::startLoadReportPeriod() {
// Once a cluster is tracked, we don't want to reset its stats between reports
// to avoid racing between request/response.
// TODO(htuch): They key here could be absl::string_view, but this causes
// problems due to referencing of temporaries in the below loop with Google's
// internal string type. Consider this optimization when the string types
// converge.
std::unordered_map<std::string, std::chrono::steady_clock::duration> existing_clusters;
for (const std::string& cluster_name : message_->clusters()) {
if (clusters_.count(cluster_name) > 0) {
existing_clusters.emplace(cluster_name, clusters_[cluster_name]);
}
}
clusters_.clear();
// Reset stats for all hosts in clusters we are tracking.
for (const std::string& cluster_name : message_->clusters()) {
clusters_.emplace(cluster_name, existing_clusters.count(cluster_name) > 0
? existing_clusters[cluster_name]
: time_source_.currentTime().time_since_epoch());
auto cluster_info_map = cm_.clusters();
auto it = cluster_info_map.find(cluster_name);
if (it == cluster_info_map.end()) {
continue;
}
// Don't reset stats for existing tracked clusters.
if (existing_clusters.count(cluster_name) > 0) {
continue;
}
auto& cluster = it->second.get();
for (auto& host_set : cluster.prioritySet().hostSetsPerPriority()) {
for (auto host : host_set->hosts()) {
host->stats().rq_success_.latch();
host->stats().rq_error_.latch();
}
}
cluster.info()->loadReportStats().upstream_rq_dropped_.latch();
}
response_timer_->enableTimer(std::chrono::milliseconds(
DurationUtil::durationToMilliseconds(message_->load_reporting_interval())));
}
void LoadStatsReporter::onReceiveTrailingMetadata(Http::HeaderMapPtr&& metadata) {
UNREFERENCED_PARAMETER(metadata);
}
void LoadStatsReporter::onRemoteClose(Grpc::Status::GrpcStatus status, const std::string& message) {
ENVOY_LOG(warn, "gRPC config stream closed: {}, {}", status, message);
response_timer_->disableTimer();
stream_ = nullptr;
handleFailure();
}
} // namespace Upstream
} // namespace Envoy
<|endoftext|>
|
<commit_before>/*
* Database.cpp
*
* Created on: 21 Aug 2013
* Author: nicholas
*/
#include "../include/Database.hpp"
#include <string>
#include <odb/transaction.hxx>
#include <odb/result.hxx>
#include <odb/schema-catalog.hxx>
#include "table/ImageRecord.hpp"
#include "table/ImageRecord-odb.hxx"
const char *dbName = "imageHasher.db";
const char *insertImageQuery = "INSERT INTO `imagerecord` (`path`,`sha_id`,`phash_id`) VALUES (?,?,?);";
const char *insertInvalidQuery = "INSERT INTO `badfilerecord` (`path`) VALUES (?);";
const char *insertFilterQuery = "INSERT OR IGNORE INTO `filterrecord` (`phash_id`, `reason`) VALUES (?,?);";
const char *prunePathQuery = "SELECT `path` FROM `imagerecord` WHERE `path` LIKE ? UNION SELECT `path` FROM `badfilerecord` WHERE `path` LIKE ?;";
const char *prunePathDeleteImage = "DELETE FROM `imagerecord` WHERE `path` = ?;";
const char *prunePathDeleteBadFile = "DELETE FROM `badfilerecord` WHERE `path` = ?;";
const char *checkExistsQuery = "SELECT EXISTS(SELECT 1 FROM `imagerecord` WHERE `path` = ? LIMIT 1) OR EXISTS(SELECT 1 FROM `badfilerecord` WHERE `path` = ? LIMIT 1);";
const char *checkSHAQuery = "SELECT EXISTS(SELECT 1 FROM `imagerecord` JOIN `sha_hash` ON `sha_id`= `id` WHERE `path` = ? AND `sha256` != '' LIMIT 1);";
const char *updateSha = "UPDATE `imagerecord` SET `sha_id`=? WHERE `path` = ?;";
const char *getSHAQuery = "SELECT `sha256` FROM `imagerecord` AS ir JOIN `sha_hash` AS h ON ir.sha_id=h.id WHERE `path` = ?;";
const char *getPhashQuery = "SELECT `pHash` FROM `imagerecord` AS ir JOIN `phash_hash` AS h ON ir.sha_id=h.id WHERE `path` = ?;";
const char *getSHAidQuery = "SELECT `id` FROM `sha_hash` WHERE `sha256`= ?;";
const char *getpHashidQuery = "SELECT `id` FROM `phash_hash` WHERE `pHash`= ?;";
const char *insertShaRecordQuery = "INSERT INTO `sha_hash` (`sha256`) VALUES (?);";
const char *insertpHashRecordQuery = "INSERT INTO `phash_hash` (`pHash`) VALUES (?);";
const char *startTransactionQuery = "BEGIN TRANSACTION;";
const char *commitTransactionQuery = "COMMIT TRANSACTION;";
using namespace odb;
using namespace imageHasher::db::table;
Database::Database(const char* dbPath) {
dbName = dbPath;
init();
}
Database::Database() {
init();
}
Database::~Database() {
shutdown();
}
int Database::flush() {
int drainCount = 0;
LOG4CPLUS_INFO(logger, "Flushing lists...");
drainCount = drain();
drainCount += drain();
return drainCount;
}
void Database::shutdown() {
if (running) {
LOG4CPLUS_INFO(logger, "Shutting down...");
running = false;
LOG4CPLUS_INFO(logger, "Waiting for db worker to finish...");
workerThread->interrupt();
workerThread->join();
LOG4CPLUS_INFO(logger, "Closing database...");
}
}
void Database::exec(const char* command) {
orm_db->execute(command);
}
void Database::init() {
boost::mutex::scoped_lock lock(dbMutex);
this->currentList = &dataA;
this->recordsWritten = 0;
this->running = true;
logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("Database"));
setupDatabase();
prepareStatements();
workerThread = new boost::thread(&Database::doWork, this);
}
void Database::setupDatabase() {
orm_db = new sqlite::database(dbName,SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);
LOG4CPLUS_INFO(logger, "Setting up database " << dbName);
transaction t(orm_db->begin());
odb:schema_catalog::create_schema(*orm_db, "", false);
/*
// TODO get this to work with odb
exec(const_cast<char *>("PRAGMA page_size = 4096;"));
exec(const_cast<char *>("PRAGMA cache_size=10000;"));
exec(const_cast<char *>("PRAGMA locking_mode=EXCLUSIVE;"));
exec(const_cast<char *>("PRAGMA synchronous=NORMAL;"));
exec(const_cast<char *>("PRAGMA temp_store = MEMORY;"));
exec(const_cast<char *>("PRAGMA journal_mode=MEMORY;"));
*/
t.commit();
}
void Database::add(db_data data) {
boost::mutex::scoped_lock lock(flipMutex);
currentList->push_back(data);
}
void Database::flipLists() {
boost::mutex::scoped_lock lock(flipMutex);
if(currentList == &dataA) {
currentList = &dataB;
}else{
currentList = &dataA;
}
}
int Database::drain() {
boost::mutex::scoped_lock lock(dbMutex);
std::list<db_data>* workList;
int drainCount = 0;
workList = currentList;
flipLists();
for(std::list<db_data>::iterator ite = workList->begin(); ite != workList->end(); ++ite) {
addToBatch(*ite);
recordsWritten++;
drainCount++;
}
workList->clear();
return drainCount;
}
bool Database::entryExists(fs::path filePath) {
LOG4CPLUS_DEBUG(logger, "Looking for file " << filePath);
ImageRecord ir = get_imagerecord(filePath);
return ir.is_valid();
}
bool Database::entryExists(db_data data) {
return entryExists(data.filePath);
}
std::list<fs::path> Database::getFilesWithPath(fs::path directoryPath) {
std::list<fs::path> filePaths;
std::string query(directoryPath.string());
query += "%";
const char* path = query.c_str();
int pathSize = query.size();
int response = -1;
LOG4CPLUS_INFO(logger, "Looking for files with path " << directoryPath);
boost::mutex::scoped_lock lock(dbMutex);
//TODO implement get file with path
LOG4CPLUS_INFO(logger, "Found " << filePaths.size() << " records for path " << directoryPath);
return filePaths;
}
void Database::prunePath(std::list<fs::path> filePaths) {
boost::mutex::scoped_lock lock(dbMutex);
bool allOk = true;
for(std::list<fs::path>::iterator ite = filePaths.begin(); ite != filePaths.end(); ++ite){
const char* path = ite->c_str();
int pathSize = ite->string().size();
int response = 0;
//TODO implement prunePath
}
if (!allOk) {
LOG4CPLUS_WARN(logger, "Failed to delete some file paths");
}
}
void Database::addToBatch(db_data data) {
int response = 0;
int hashId = -1;
switch (data.status) {
case OK:
add_record(data);
break;
case INVALID:
//TODO add invalid record
if (response != SQLITE_DONE) {
LOG4CPLUS_WARN(logger, "Failed to add " << data.filePath);
recordsWritten--;
}
break;
case FILTER:
//TODO add filter record
if (response != SQLITE_DONE) {
LOG4CPLUS_WARN(logger, "Failed to add filter for " << data.pHash << " " << data.reason);
}
break;
default:
LOG4CPLUS_ERROR(logger, "Unhandled state encountered");
throw "Unhandled state encountered";
break;
}
}
void Database::add_record(db_data data) {
Hash hash = get_hash(data.sha256);
if (!hash.is_valid()) {
hash = addHashEntry(data.sha256, data.pHash);
}
if(entryExists(data)) {
LOG4CPLUS_DEBUG(logger, "Entry for " << data.filePath << " already exists, discarding...");
recordsWritten--;
}
transaction t(orm_db->begin());
ImageRecord ir = ImageRecord(data.filePath.string(), &hash);
orm_db->persist(ir);
t.commit();
}
void Database::prepareStatements() {
LOG4CPLUS_INFO(logger, "Creating prepared statements...");
}
void Database::doWork() {
while(running) {
try{
boost::this_thread::sleep_for(boost::chrono::seconds(3));
}catch(boost::thread_interrupted&) {
LOG4CPLUS_INFO(logger,"DB thread interrupted");
}
if(currentList->size() > 1000) {
int drainCount = drain();
LOG4CPLUS_INFO(logger, drainCount << " records processed, Total: " << recordsWritten);
}
}
// make sure both lists are committed
int drainCount = flush();
LOG4CPLUS_INFO(logger, drainCount << " records processed, Total: " << recordsWritten);
}
unsigned int Database::getRecordsWritten() {
return recordsWritten;
}
std::string Database::getSHA(fs::path filepath) {
std::string sha = "";
LOG4CPLUS_DEBUG(logger, "Getting SHA for path " << filepath);
transaction t (orm_db->begin());
result<ImageRecord> r (orm_db->query<ImageRecord>(query<ImageRecord>::path == filepath.string()));
for(result<ImageRecord>::iterator itr (r.begin()); itr != r.end(); ++itr) {
Hash hash = itr->get_hash();
sha = hash.get_sha256();
break;
}
t.commit();
return sha;
}
bool Database::sha_exists(std::string sha) {
Hash hash = get_hash(sha);
return hash.is_valid();
}
int64_t Database::getPhash(fs::path filepath) {
int pHash = -1;
LOG4CPLUS_DEBUG(logger, "Getting pHash for path " << filepath);
//TODO implement get phash
return pHash;
}
imageHasher::db::table::Hash Database::get_hash(std::string sha) {
Hash hash;
LOG4CPLUS_DEBUG(logger, "Getting hash for sha " << sha);
transaction t (orm_db->begin());
result<Hash> r (orm_db->query<Hash>(query<Hash>::sha256 == sha));
for(result<Hash>::iterator itr (r.begin()); itr != r.end(); ++itr) {
hash = *itr;
break;
}
t.commit();
return hash;
}
imageHasher::db::table::Hash Database::get_hash(u_int64_t phash) {
Hash hash;
//TODO implement me
return hash;
}
imageHasher::db::table::ImageRecord Database::get_imagerecord(fs::path filepath) {
ImageRecord ir;
transaction t (orm_db->begin());
result<ImageRecord> r (orm_db->query<ImageRecord>(query<ImageRecord>::path == filepath.string()));
for(result<ImageRecord>::iterator itr (r.begin()); itr != r.end(); ++itr) {
ir = *itr;
break;
}
t.commit();
return ir;
}
Hash Database::addHashEntry(std::string sha, u_int64_t pHash) {
Hash hash(sha,pHash);
transaction t (orm_db->begin());
orm_db->persist(hash);
t.commit();
return hash;
}
<commit_msg>Fixed duplicate entry add<commit_after>/*
* Database.cpp
*
* Created on: 21 Aug 2013
* Author: nicholas
*/
#include "../include/Database.hpp"
#include <string>
#include <odb/transaction.hxx>
#include <odb/result.hxx>
#include <odb/schema-catalog.hxx>
#include "table/ImageRecord.hpp"
#include "table/ImageRecord-odb.hxx"
const char *dbName = "imageHasher.db";
const char *insertImageQuery = "INSERT INTO `imagerecord` (`path`,`sha_id`,`phash_id`) VALUES (?,?,?);";
const char *insertInvalidQuery = "INSERT INTO `badfilerecord` (`path`) VALUES (?);";
const char *insertFilterQuery = "INSERT OR IGNORE INTO `filterrecord` (`phash_id`, `reason`) VALUES (?,?);";
const char *prunePathQuery = "SELECT `path` FROM `imagerecord` WHERE `path` LIKE ? UNION SELECT `path` FROM `badfilerecord` WHERE `path` LIKE ?;";
const char *prunePathDeleteImage = "DELETE FROM `imagerecord` WHERE `path` = ?;";
const char *prunePathDeleteBadFile = "DELETE FROM `badfilerecord` WHERE `path` = ?;";
const char *checkExistsQuery = "SELECT EXISTS(SELECT 1 FROM `imagerecord` WHERE `path` = ? LIMIT 1) OR EXISTS(SELECT 1 FROM `badfilerecord` WHERE `path` = ? LIMIT 1);";
const char *checkSHAQuery = "SELECT EXISTS(SELECT 1 FROM `imagerecord` JOIN `sha_hash` ON `sha_id`= `id` WHERE `path` = ? AND `sha256` != '' LIMIT 1);";
const char *updateSha = "UPDATE `imagerecord` SET `sha_id`=? WHERE `path` = ?;";
const char *getSHAQuery = "SELECT `sha256` FROM `imagerecord` AS ir JOIN `sha_hash` AS h ON ir.sha_id=h.id WHERE `path` = ?;";
const char *getPhashQuery = "SELECT `pHash` FROM `imagerecord` AS ir JOIN `phash_hash` AS h ON ir.sha_id=h.id WHERE `path` = ?;";
const char *getSHAidQuery = "SELECT `id` FROM `sha_hash` WHERE `sha256`= ?;";
const char *getpHashidQuery = "SELECT `id` FROM `phash_hash` WHERE `pHash`= ?;";
const char *insertShaRecordQuery = "INSERT INTO `sha_hash` (`sha256`) VALUES (?);";
const char *insertpHashRecordQuery = "INSERT INTO `phash_hash` (`pHash`) VALUES (?);";
const char *startTransactionQuery = "BEGIN TRANSACTION;";
const char *commitTransactionQuery = "COMMIT TRANSACTION;";
using namespace odb;
using namespace imageHasher::db::table;
Database::Database(const char* dbPath) {
dbName = dbPath;
init();
}
Database::Database() {
init();
}
Database::~Database() {
shutdown();
}
int Database::flush() {
int drainCount = 0;
LOG4CPLUS_INFO(logger, "Flushing lists...");
drainCount = drain();
drainCount += drain();
return drainCount;
}
void Database::shutdown() {
if (running) {
LOG4CPLUS_INFO(logger, "Shutting down...");
running = false;
LOG4CPLUS_INFO(logger, "Waiting for db worker to finish...");
workerThread->interrupt();
workerThread->join();
LOG4CPLUS_INFO(logger, "Closing database...");
}
}
void Database::exec(const char* command) {
orm_db->execute(command);
}
void Database::init() {
boost::mutex::scoped_lock lock(dbMutex);
this->currentList = &dataA;
this->recordsWritten = 0;
this->running = true;
logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("Database"));
setupDatabase();
prepareStatements();
workerThread = new boost::thread(&Database::doWork, this);
}
void Database::setupDatabase() {
orm_db = new sqlite::database(dbName,SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);
LOG4CPLUS_INFO(logger, "Setting up database " << dbName);
transaction t(orm_db->begin());
odb:schema_catalog::create_schema(*orm_db, "", false);
/*
// TODO get this to work with odb
exec(const_cast<char *>("PRAGMA page_size = 4096;"));
exec(const_cast<char *>("PRAGMA cache_size=10000;"));
exec(const_cast<char *>("PRAGMA locking_mode=EXCLUSIVE;"));
exec(const_cast<char *>("PRAGMA synchronous=NORMAL;"));
exec(const_cast<char *>("PRAGMA temp_store = MEMORY;"));
exec(const_cast<char *>("PRAGMA journal_mode=MEMORY;"));
*/
t.commit();
}
void Database::add(db_data data) {
boost::mutex::scoped_lock lock(flipMutex);
currentList->push_back(data);
}
void Database::flipLists() {
boost::mutex::scoped_lock lock(flipMutex);
if(currentList == &dataA) {
currentList = &dataB;
}else{
currentList = &dataA;
}
}
int Database::drain() {
boost::mutex::scoped_lock lock(dbMutex);
std::list<db_data>* workList;
int drainCount = 0;
workList = currentList;
flipLists();
for(std::list<db_data>::iterator ite = workList->begin(); ite != workList->end(); ++ite) {
addToBatch(*ite);
recordsWritten++;
drainCount++;
}
workList->clear();
return drainCount;
}
bool Database::entryExists(fs::path filePath) {
LOG4CPLUS_DEBUG(logger, "Looking for file " << filePath);
ImageRecord ir = get_imagerecord(filePath);
return ir.is_valid();
}
bool Database::entryExists(db_data data) {
return entryExists(data.filePath);
}
std::list<fs::path> Database::getFilesWithPath(fs::path directoryPath) {
std::list<fs::path> filePaths;
std::string query(directoryPath.string());
query += "%";
const char* path = query.c_str();
int pathSize = query.size();
int response = -1;
LOG4CPLUS_INFO(logger, "Looking for files with path " << directoryPath);
boost::mutex::scoped_lock lock(dbMutex);
//TODO implement get file with path
LOG4CPLUS_INFO(logger, "Found " << filePaths.size() << " records for path " << directoryPath);
return filePaths;
}
void Database::prunePath(std::list<fs::path> filePaths) {
boost::mutex::scoped_lock lock(dbMutex);
bool allOk = true;
for(std::list<fs::path>::iterator ite = filePaths.begin(); ite != filePaths.end(); ++ite){
const char* path = ite->c_str();
int pathSize = ite->string().size();
int response = 0;
//TODO implement prunePath
}
if (!allOk) {
LOG4CPLUS_WARN(logger, "Failed to delete some file paths");
}
}
void Database::addToBatch(db_data data) {
int response = 0;
int hashId = -1;
switch (data.status) {
case OK:
add_record(data);
break;
case INVALID:
//TODO add invalid record
if (response != SQLITE_DONE) {
LOG4CPLUS_WARN(logger, "Failed to add " << data.filePath);
recordsWritten--;
}
break;
case FILTER:
//TODO add filter record
if (response != SQLITE_DONE) {
LOG4CPLUS_WARN(logger, "Failed to add filter for " << data.pHash << " " << data.reason);
}
break;
default:
LOG4CPLUS_ERROR(logger, "Unhandled state encountered");
throw "Unhandled state encountered";
break;
}
}
void Database::add_record(db_data data) {
Hash hash = get_hash(data.sha256);
if (!hash.is_valid()) {
hash = addHashEntry(data.sha256, data.pHash);
}
if(entryExists(data)) {
LOG4CPLUS_DEBUG(logger, "Entry for " << data.filePath << " already exists, discarding...");
recordsWritten--;
return;
}
transaction t(orm_db->begin());
ImageRecord ir = ImageRecord(data.filePath.string(), &hash);
orm_db->persist(ir);
t.commit();
}
void Database::prepareStatements() {
LOG4CPLUS_INFO(logger, "Creating prepared statements...");
}
void Database::doWork() {
while(running) {
try{
boost::this_thread::sleep_for(boost::chrono::seconds(3));
}catch(boost::thread_interrupted&) {
LOG4CPLUS_INFO(logger,"DB thread interrupted");
}
if(currentList->size() > 1000) {
int drainCount = drain();
LOG4CPLUS_INFO(logger, drainCount << " records processed, Total: " << recordsWritten);
}
}
// make sure both lists are committed
int drainCount = flush();
LOG4CPLUS_INFO(logger, drainCount << " records processed, Total: " << recordsWritten);
}
unsigned int Database::getRecordsWritten() {
return recordsWritten;
}
std::string Database::getSHA(fs::path filepath) {
std::string sha = "";
LOG4CPLUS_DEBUG(logger, "Getting SHA for path " << filepath);
transaction t (orm_db->begin());
result<ImageRecord> r (orm_db->query<ImageRecord>(query<ImageRecord>::path == filepath.string()));
for(result<ImageRecord>::iterator itr (r.begin()); itr != r.end(); ++itr) {
Hash hash = itr->get_hash();
sha = hash.get_sha256();
break;
}
t.commit();
return sha;
}
bool Database::sha_exists(std::string sha) {
Hash hash = get_hash(sha);
return hash.is_valid();
}
int64_t Database::getPhash(fs::path filepath) {
int pHash = -1;
LOG4CPLUS_DEBUG(logger, "Getting pHash for path " << filepath);
//TODO implement get phash
return pHash;
}
imageHasher::db::table::Hash Database::get_hash(std::string sha) {
Hash hash;
LOG4CPLUS_DEBUG(logger, "Getting hash for sha " << sha);
transaction t (orm_db->begin());
result<Hash> r (orm_db->query<Hash>(query<Hash>::sha256 == sha));
for(result<Hash>::iterator itr (r.begin()); itr != r.end(); ++itr) {
hash = *itr;
break;
}
t.commit();
return hash;
}
imageHasher::db::table::Hash Database::get_hash(u_int64_t phash) {
Hash hash;
//TODO implement me
return hash;
}
imageHasher::db::table::ImageRecord Database::get_imagerecord(fs::path filepath) {
ImageRecord ir;
transaction t (orm_db->begin());
result<ImageRecord> r (orm_db->query<ImageRecord>(query<ImageRecord>::path == filepath.string()));
for(result<ImageRecord>::iterator itr (r.begin()); itr != r.end(); ++itr) {
ir = *itr;
break;
}
t.commit();
return ir;
}
Hash Database::addHashEntry(std::string sha, u_int64_t pHash) {
Hash hash(sha,pHash);
transaction t (orm_db->begin());
orm_db->persist(hash);
t.commit();
return hash;
}
<|endoftext|>
|
<commit_before>#pragma once
#include <cstdint>
#include <depthai-shared/common/optional.hpp>
#include <nlohmann/json.hpp>
#include <vector>
#include "DatatypeEnum.hpp"
#include "RawBuffer.hpp"
namespace dai {
/**
* Median filter config for disparity post-processing
*/
enum class MedianFilter : int32_t { MEDIAN_OFF = 0, KERNEL_3x3 = 3, KERNEL_5x5 = 5, KERNEL_7x7 = 7 };
/// RawStereoDepthConfig configuration structure
struct RawStereoDepthConfig : public RawBuffer {
using MedianFilter = dai::MedianFilter;
struct AlgorithmControl {
/**
* Computes and combines disparities in both L-R and R-L directions, and combine them.
* For better occlusion handling
*/
bool enableLeftRightCheck = true;
/**
* Disparity range increased from 95 to 190, combined from full resolution and downscaled images.
* Suitable for short range objects
*/
bool enableExtended = false;
/**
* Computes disparity with sub-pixel interpolation (5 fractional bits), suitable for long range
*/
bool enableSubpixel = false;
/**
* Left-right check threshold for left-right, right-left disparity map combine, 0..128
* Used only when left-right check mode is enabled.
* Defines the maximum difference between the confidence of pixels from left-right and right-left confidence maps
*/
std::int32_t leftRightCheckThreshold = 10;
/**
* Number of fractional bits for subpixel mode.
* Valid values: 3,4,5.
* Defines the number of fractional disparities: 2^x.
* Median filter postprocessing is supported only for 3 fractional bits.
*/
std::int32_t subpixelFractionalBits = 3;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(AlgorithmControl, enableLeftRightCheck, enableExtended, enableSubpixel, leftRightCheckThreshold, subpixelFractionalBits);
};
/**
* Controls the flow of stereo algorithm: left-right check, subpixel etc.
*/
AlgorithmControl algorithmControl;
struct PostProcessing {
/**
* Set kernel size for disparity/depth median filtering, or disable
*/
MedianFilter median = MedianFilter::KERNEL_5x5;
/**
* Sigma value for bilateral filter. 0 means disabled
* A larger value of the parameter means that farther colors within the pixel neighborhood will be mixed together.
*/
std::int16_t bilateralSigmaValue = 0;
struct TemporalFilter {
bool enable = false;
enum class PersistencyMode : int32_t {
PERSISTENCY_OFF = 0,
VALID_8_OUT_OF_8 = 1,
VALID_2_IN_LAST_3 = 2,
VALID_2_IN_LAST_4 = 3,
VALID_2_OUT_OF_8 = 4,
VALID_1_IN_LAST_2 = 5,
VALID_1_IN_LAST_5 = 6,
VALID_1_IN_LAST_8 = 7,
PERSISTENCY_INDEFINITELY = 8,
};
PersistencyMode persistencyMode = PersistencyMode::VALID_2_IN_LAST_4;
float alpha = 0.4f;
std::int32_t delta = 20;
};
NLOHMANN_DEFINE_TYPE_INTRUSIVE(TemporalFilter, enable, persistencyMode, alpha, delta);
TemporalFilter temporalFilter;
struct ThresholdFilter {
std::int32_t minRange = 0;
std::int32_t maxRange = 65535;
};
NLOHMANN_DEFINE_TYPE_INTRUSIVE(ThresholdFilter, minRange, maxRange);
ThresholdFilter thresholdFilter;
struct SpeckleFilter {
bool enable = false;
std::int8_t speckleRange = 100;
};
NLOHMANN_DEFINE_TYPE_INTRUSIVE(SpeckleFilter, enable, speckleRange);
SpeckleFilter speckleFilter;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(PostProcessing, median, bilateralSigmaValue, temporalFilter, thresholdFilter, speckleFilter);
};
/**
* Controls the postprocessing of disparity and/or depth map.
*/
PostProcessing postProcessing;
/**
* The basic cost function used by the Stereo Accelerator for matching the left and right images is the Census
* Transform. It works on a block of pixels and computes a bit vector which represents the structure of the
* image in that block.
* There are two types of Census Transform based on how the middle pixel is used:
* Classic Approach and Modified Census. The comparisons that are made between pixels can be or not thresholded.
* In some cases a mask can be applied to filter out only specific bits from the entire bit stream.
* All these approaches are:
* Classic Approach: Uses middle pixel to compare against all its neighbors over a defined window. Each
* comparison results in a new bit, that is 0 if central pixel is smaller, or 1 if is it bigger than its neighbor.
* Modified Census Transform: same as classic Census Transform, but instead of comparing central pixel
* with its neighbors, the window mean will be compared with each pixel over the window.
* Thresholding Census Transform: same as classic Census Transform, but it is not enough that a
* neighbor pixel to be bigger than the central pixel, it must be significant bigger (based on a threshold).
* Census Transform with Mask: same as classic Census Transform, but in this case not all of the pixel from
* the support window are part of the binary descriptor. We use a ma sk “M” to define which pixels are part
* of the binary descriptor (1), and which pixels should be skipped (0).
*/
struct CensusTransform {
/**
* Census transform kernel size possible values.
*/
enum class KernelSize : std::int32_t { AUTO = -1, KERNEL_5x5 = 0, KERNEL_7x7, KERNEL_7x9 };
/**
* Census transform kernel size.
*/
KernelSize kernelSize = KernelSize::AUTO;
/**
* Census transform mask, default: auto, mask is set based on resolution and kernel size.
* Disabled for 400p input resolution.
* Enabled for 720p.
* 0XA82415 for 5x5 census transform kernel.
* 0XAA02A8154055 for 7x7 census transform kernel.
* 0X2AA00AA805540155 for 7x9 census transform kernel.
* Empirical values.
*/
uint64_t kernelMask = 0;
/**
* If enabled, each pixel in the window is compared with the mean window value instead of the central pixel.
*/
bool enableMeanMode = true;
/**
* Census transform comparation treshold value.
*/
uint32_t threshold = 0;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(CensusTransform, kernelSize, kernelMask, enableMeanMode, threshold);
};
/**
* Census transform settings.
*/
CensusTransform censusTransform;
/**
* The matching cost is way of measuring the similarity of image locations in stereo correspondence
* algorithm. Based on the configuration parameters and based on the descriptor type, a linear equation
* is applied to computing the cost for each candidate disparity at each pixel.
*/
struct CostMatching {
/**
* Disparity search range: 64 or 96 pixels are supported by the HW.
*/
enum class DisparityWidth : std::uint32_t { DISPARITY_64, DISPARITY_96 };
/**
* Disparity search range, default 96 pixels.
*/
DisparityWidth disparityWidth = DisparityWidth::DISPARITY_96;
/**
* Disparity companding using sparse matching.
* Matching pixel by pixel for N disparities.
* Matching every 2nd pixel for M disparitites.
* Matching every 4th pixel for T disparities.
* In case of 96 disparities: N=48, M=32, T=16.
* This way the search range is extended to 176 disparities, by sparse matching.
* Note: when enabling this flag only depth map will be affected, disparity map is not.
*/
bool enableCompanding = false;
/**
* Used only for debug purposes, SW postprocessing handled only invalid value of 0 properly.
*/
uint8_t invalidDisparityValue = 0;
/**
* Disparities with confidence value under this threshold are accepted.
* Higher confidence threshold means disparities with less confidence are accepted too.
*/
uint8_t confidenceThreshold = 245;
/**
* The linear equation applied for computing the cost is:
* COMB_COST = α*AD + β*(CTC<<3).
* CLAMP(COMB_COST >> 5, threshold).
* Where AD is the Absolute Difference between 2 pixels values.
* CTC is the Census Transform Cost between 2 pixels, based on Hamming distance (xor).
* The α and β parameters are subject to fine fine tuning by the user.
*/
struct LinearEquationParameters {
uint8_t alpha = 0;
uint8_t beta = 2;
uint8_t threshold = 127;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(LinearEquationParameters, alpha, beta, threshold);
};
/**
* Cost calculation linear equation parameters.
*/
LinearEquationParameters linearEquationParameters;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(CostMatching, disparityWidth, enableCompanding, invalidDisparityValue, confidenceThreshold, linearEquationParameters);
};
/**
* Cost matching settings.
*/
CostMatching costMatching;
/**
* Cost Aggregation is based on Semi Global Block Matching (SGBM). This algorithm uses a semi global
* technique to aggregate the cost map. Ultimately the idea is to build inertia into the stereo algorithm. If
* a pixel has very little texture information, then odds are the correct disparity for this pixel is close to
* that of the previous pixel considered. This means that we get improved results in areas with low
* texture.
*/
struct CostAggregation {
static constexpr const int defaultPenaltyP1 = 250;
static constexpr const int defaultPenaltyP2 = 500;
/**
* Cost calculation linear equation parameters.
*/
uint8_t divisionFactor = 1;
/**
* Horizontal P1 penalty cost parameter.
*/
uint16_t horizontalPenaltyCostP1 = defaultPenaltyP1;
/**
* Horizontal P2 penalty cost parameter.
*/
uint16_t horizontalPenaltyCostP2 = defaultPenaltyP2;
/**
* Vertical P1 penalty cost parameter.
*/
uint16_t verticalPenaltyCostP1 = defaultPenaltyP1;
/**
* Vertical P2 penalty cost parameter.
*/
uint16_t verticalPenaltyCostP2 = defaultPenaltyP2;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(
CostAggregation, divisionFactor, horizontalPenaltyCostP1, horizontalPenaltyCostP2, verticalPenaltyCostP1, verticalPenaltyCostP2);
};
/**
* Cost aggregation settings.
*/
CostAggregation costAggregation;
void serialize(std::vector<std::uint8_t>& metadata, DatatypeEnum& datatype) const override {
nlohmann::json j = *this;
metadata = nlohmann::json::to_msgpack(j);
datatype = DatatypeEnum::StereoDepthConfig;
};
NLOHMANN_DEFINE_TYPE_INTRUSIVE(RawStereoDepthConfig, algorithmControl, postProcessing, censusTransform, costMatching, costAggregation);
};
} // namespace dai
<commit_msg>Add edge preserving spatial filter<commit_after>#pragma once
#include <cstdint>
#include <depthai-shared/common/optional.hpp>
#include <nlohmann/json.hpp>
#include <vector>
#include "DatatypeEnum.hpp"
#include "RawBuffer.hpp"
namespace dai {
/**
* Median filter config for disparity post-processing
*/
enum class MedianFilter : int32_t { MEDIAN_OFF = 0, KERNEL_3x3 = 3, KERNEL_5x5 = 5, KERNEL_7x7 = 7 };
/// RawStereoDepthConfig configuration structure
struct RawStereoDepthConfig : public RawBuffer {
using MedianFilter = dai::MedianFilter;
struct AlgorithmControl {
/**
* Computes and combines disparities in both L-R and R-L directions, and combine them.
* For better occlusion handling
*/
bool enableLeftRightCheck = true;
/**
* Disparity range increased from 95 to 190, combined from full resolution and downscaled images.
* Suitable for short range objects
*/
bool enableExtended = false;
/**
* Computes disparity with sub-pixel interpolation (5 fractional bits), suitable for long range
*/
bool enableSubpixel = false;
/**
* Left-right check threshold for left-right, right-left disparity map combine, 0..128
* Used only when left-right check mode is enabled.
* Defines the maximum difference between the confidence of pixels from left-right and right-left confidence maps
*/
std::int32_t leftRightCheckThreshold = 10;
/**
* Number of fractional bits for subpixel mode.
* Valid values: 3,4,5.
* Defines the number of fractional disparities: 2^x.
* Median filter postprocessing is supported only for 3 fractional bits.
*/
std::int32_t subpixelFractionalBits = 3;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(AlgorithmControl, enableLeftRightCheck, enableExtended, enableSubpixel, leftRightCheckThreshold, subpixelFractionalBits);
};
/**
* Controls the flow of stereo algorithm: left-right check, subpixel etc.
*/
AlgorithmControl algorithmControl;
struct PostProcessing {
/**
* Set kernel size for disparity/depth median filtering, or disable
*/
MedianFilter median = MedianFilter::KERNEL_5x5;
/**
* Sigma value for bilateral filter. 0 means disabled
* A larger value of the parameter means that farther colors within the pixel neighborhood will be mixed together.
*/
std::int16_t bilateralSigmaValue = 0;
struct SpatialFilter {
bool enable = false;
enum class HoleFillingRadius : int32_t {
HOLE_FILLING_OFF = 0,
RADIUS_2 = 2,
RADIUS_4 = 4,
RADIUS_8 = 8,
RADIUS_16 = 16,
RADIUS_UNLIMITED = 255,
};
HoleFillingRadius holeFillingRadius = HoleFillingRadius::RADIUS_2;
float alpha = 0.5f;
std::int32_t delta = 20;
std::int32_t numIterations = 2;
};
NLOHMANN_DEFINE_TYPE_INTRUSIVE(SpatialFilter, enable, holeFillingRadius, alpha, delta, numIterations);
SpatialFilter spatialFilter;
struct TemporalFilter {
bool enable = false;
enum class PersistencyMode : int32_t {
PERSISTENCY_OFF = 0,
VALID_8_OUT_OF_8 = 1,
VALID_2_IN_LAST_3 = 2,
VALID_2_IN_LAST_4 = 3,
VALID_2_OUT_OF_8 = 4,
VALID_1_IN_LAST_2 = 5,
VALID_1_IN_LAST_5 = 6,
VALID_1_IN_LAST_8 = 7,
PERSISTENCY_INDEFINITELY = 8,
};
PersistencyMode persistencyMode = PersistencyMode::VALID_2_IN_LAST_4;
float alpha = 0.4f;
std::int32_t delta = 20;
};
NLOHMANN_DEFINE_TYPE_INTRUSIVE(TemporalFilter, enable, persistencyMode, alpha, delta);
TemporalFilter temporalFilter;
struct ThresholdFilter {
std::int32_t minRange = 0;
std::int32_t maxRange = 65535;
};
NLOHMANN_DEFINE_TYPE_INTRUSIVE(ThresholdFilter, minRange, maxRange);
ThresholdFilter thresholdFilter;
struct SpeckleFilter {
bool enable = false;
std::int8_t speckleRange = 100;
};
NLOHMANN_DEFINE_TYPE_INTRUSIVE(SpeckleFilter, enable, speckleRange);
SpeckleFilter speckleFilter;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(PostProcessing, median, bilateralSigmaValue, spatialFilter, temporalFilter, thresholdFilter, speckleFilter);
};
/**
* Controls the postprocessing of disparity and/or depth map.
*/
PostProcessing postProcessing;
/**
* The basic cost function used by the Stereo Accelerator for matching the left and right images is the Census
* Transform. It works on a block of pixels and computes a bit vector which represents the structure of the
* image in that block.
* There are two types of Census Transform based on how the middle pixel is used:
* Classic Approach and Modified Census. The comparisons that are made between pixels can be or not thresholded.
* In some cases a mask can be applied to filter out only specific bits from the entire bit stream.
* All these approaches are:
* Classic Approach: Uses middle pixel to compare against all its neighbors over a defined window. Each
* comparison results in a new bit, that is 0 if central pixel is smaller, or 1 if is it bigger than its neighbor.
* Modified Census Transform: same as classic Census Transform, but instead of comparing central pixel
* with its neighbors, the window mean will be compared with each pixel over the window.
* Thresholding Census Transform: same as classic Census Transform, but it is not enough that a
* neighbor pixel to be bigger than the central pixel, it must be significant bigger (based on a threshold).
* Census Transform with Mask: same as classic Census Transform, but in this case not all of the pixel from
* the support window are part of the binary descriptor. We use a ma sk “M” to define which pixels are part
* of the binary descriptor (1), and which pixels should be skipped (0).
*/
struct CensusTransform {
/**
* Census transform kernel size possible values.
*/
enum class KernelSize : std::int32_t { AUTO = -1, KERNEL_5x5 = 0, KERNEL_7x7, KERNEL_7x9 };
/**
* Census transform kernel size.
*/
KernelSize kernelSize = KernelSize::AUTO;
/**
* Census transform mask, default: auto, mask is set based on resolution and kernel size.
* Disabled for 400p input resolution.
* Enabled for 720p.
* 0XA82415 for 5x5 census transform kernel.
* 0XAA02A8154055 for 7x7 census transform kernel.
* 0X2AA00AA805540155 for 7x9 census transform kernel.
* Empirical values.
*/
uint64_t kernelMask = 0;
/**
* If enabled, each pixel in the window is compared with the mean window value instead of the central pixel.
*/
bool enableMeanMode = true;
/**
* Census transform comparation treshold value.
*/
uint32_t threshold = 0;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(CensusTransform, kernelSize, kernelMask, enableMeanMode, threshold);
};
/**
* Census transform settings.
*/
CensusTransform censusTransform;
/**
* The matching cost is way of measuring the similarity of image locations in stereo correspondence
* algorithm. Based on the configuration parameters and based on the descriptor type, a linear equation
* is applied to computing the cost for each candidate disparity at each pixel.
*/
struct CostMatching {
/**
* Disparity search range: 64 or 96 pixels are supported by the HW.
*/
enum class DisparityWidth : std::uint32_t { DISPARITY_64, DISPARITY_96 };
/**
* Disparity search range, default 96 pixels.
*/
DisparityWidth disparityWidth = DisparityWidth::DISPARITY_96;
/**
* Disparity companding using sparse matching.
* Matching pixel by pixel for N disparities.
* Matching every 2nd pixel for M disparitites.
* Matching every 4th pixel for T disparities.
* In case of 96 disparities: N=48, M=32, T=16.
* This way the search range is extended to 176 disparities, by sparse matching.
* Note: when enabling this flag only depth map will be affected, disparity map is not.
*/
bool enableCompanding = false;
/**
* Used only for debug purposes, SW postprocessing handled only invalid value of 0 properly.
*/
uint8_t invalidDisparityValue = 0;
/**
* Disparities with confidence value under this threshold are accepted.
* Higher confidence threshold means disparities with less confidence are accepted too.
*/
uint8_t confidenceThreshold = 245;
/**
* The linear equation applied for computing the cost is:
* COMB_COST = α*AD + β*(CTC<<3).
* CLAMP(COMB_COST >> 5, threshold).
* Where AD is the Absolute Difference between 2 pixels values.
* CTC is the Census Transform Cost between 2 pixels, based on Hamming distance (xor).
* The α and β parameters are subject to fine fine tuning by the user.
*/
struct LinearEquationParameters {
uint8_t alpha = 0;
uint8_t beta = 2;
uint8_t threshold = 127;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(LinearEquationParameters, alpha, beta, threshold);
};
/**
* Cost calculation linear equation parameters.
*/
LinearEquationParameters linearEquationParameters;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(CostMatching, disparityWidth, enableCompanding, invalidDisparityValue, confidenceThreshold, linearEquationParameters);
};
/**
* Cost matching settings.
*/
CostMatching costMatching;
/**
* Cost Aggregation is based on Semi Global Block Matching (SGBM). This algorithm uses a semi global
* technique to aggregate the cost map. Ultimately the idea is to build inertia into the stereo algorithm. If
* a pixel has very little texture information, then odds are the correct disparity for this pixel is close to
* that of the previous pixel considered. This means that we get improved results in areas with low
* texture.
*/
struct CostAggregation {
static constexpr const int defaultPenaltyP1 = 250;
static constexpr const int defaultPenaltyP2 = 500;
/**
* Cost calculation linear equation parameters.
*/
uint8_t divisionFactor = 1;
/**
* Horizontal P1 penalty cost parameter.
*/
uint16_t horizontalPenaltyCostP1 = defaultPenaltyP1;
/**
* Horizontal P2 penalty cost parameter.
*/
uint16_t horizontalPenaltyCostP2 = defaultPenaltyP2;
/**
* Vertical P1 penalty cost parameter.
*/
uint16_t verticalPenaltyCostP1 = defaultPenaltyP1;
/**
* Vertical P2 penalty cost parameter.
*/
uint16_t verticalPenaltyCostP2 = defaultPenaltyP2;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(
CostAggregation, divisionFactor, horizontalPenaltyCostP1, horizontalPenaltyCostP2, verticalPenaltyCostP1, verticalPenaltyCostP2);
};
/**
* Cost aggregation settings.
*/
CostAggregation costAggregation;
void serialize(std::vector<std::uint8_t>& metadata, DatatypeEnum& datatype) const override {
nlohmann::json j = *this;
metadata = nlohmann::json::to_msgpack(j);
datatype = DatatypeEnum::StereoDepthConfig;
};
NLOHMANN_DEFINE_TYPE_INTRUSIVE(RawStereoDepthConfig, algorithmControl, postProcessing, censusTransform, costMatching, costAggregation);
};
} // namespace dai
<|endoftext|>
|
<commit_before>#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/local_time_adjustor.hpp>
#include <boost/date_time/c_local_time_adjustor.hpp>
#include <boost/thread.hpp>
#include <cassert>
#include <ir/index_manager/index/Indexer.h>
#include <ir/index_manager/index/IndexWriter.h>
#include <ir/index_manager/index/IndexReader.h>
#include <ir/index_manager/index/IndexBarrelWriter.h>
#include <ir/index_manager/index/IndexerPropertyConfig.h>
#include <ir/index_manager/index/IndexMergeManager.h>
#include <ir/index_manager/index/rtype/BTreeIndexerManager.h>
#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
#include <util/scheduler.h>
#include <fstream>
using namespace std;
NS_IZENELIB_IR_BEGIN
namespace indexmanager{
namespace bfs = boost::filesystem;
IndexWriter::IndexWriter(Indexer* pIndex)
:pIndexer_(pIndex)
,pIndexBarrelWriter_(NULL)
,pBarrelsInfo_(NULL)
,pCurBarrelInfo_(NULL)
,pIndexMergeManager_(NULL)
{
pBarrelsInfo_ = pIndexer_->getBarrelsInfo();
pIndexMergeManager_ = new IndexMergeManager(pIndex);
}
IndexWriter::~IndexWriter()
{
if (!optimizeJobDesc_.empty())
Scheduler::removeJob(optimizeJobDesc_);
if (pIndexMergeManager_)
delete pIndexMergeManager_;
if (pIndexBarrelWriter_)
delete pIndexBarrelWriter_;
}
void IndexWriter::tryResumeExistingBarrels()
{
// in order to resume merging previous barrels,
// add them into pIndexMergeManager_
BarrelInfo* pBarrelInfo = NULL;
boost::mutex::scoped_lock lock(pBarrelsInfo_->getMutex());
pBarrelsInfo_->startIterator();
while (pBarrelsInfo_->hasNext())
{
pBarrelInfo = pBarrelsInfo_->next();
assert(pBarrelInfo->getWriter() == NULL && "the loaded BarrelInfo should not be in-memory barrel");
pIndexMergeManager_->addToMerge(pBarrelInfo);
}
}
void IndexWriter::close()
{
///The difference between close and flush is close don't need t reopen indexreader
DVLOG(2) << "=> IndexWriter::close()...";
if (pCurBarrelInfo_ == NULL)
{
// write file "barrels" to update the doc count of each barrel
if (pBarrelsInfo_->getBarrelCount() > 0)
pBarrelsInfo_->write(pIndexer_->getDirectory());
DVLOG(2) << "<= IndexWriter::flush(), pCurBarrelInfo_ is NULL";
return;
}
assert(pIndexBarrelWriter_ && "pIndexBarrelWriter_ should have been created with pCurBarrelInfo_ together in IndexWriter::createBarrelInfo()");
/*for realtime index need not flush when stop normally*/
//pIndexBarrelWriter_->flush();
//pBarrelsInfo_->write(pIndexer_->getDirectory());
pIndexBarrelWriter_->reset();
pCurBarrelInfo_ = NULL;
DVLOG(2) << "<= IndexWriter::close()";
}
void IndexWriter::flush()
{
DVLOG(2) << "=> IndexWriter::flush()...";
if (!pCurBarrelInfo_)
{
// write file "barrels" to update the doc count of each barrel
if (pBarrelsInfo_->getBarrelCount() > 0)
pBarrelsInfo_->write(pIndexer_->getDirectory());
DVLOG(2) << "<= IndexWriter::flush(), pCurBarrelInfo_ is NULL";
return;
}
assert(pIndexBarrelWriter_ && "pIndexBarrelWriter_ should have been created with pCurBarrelInfo_ together in IndexWriter::createBarrelInfo()");
pIndexBarrelWriter_->flush();
if (!pIndexer_->isRealTime())
pCurBarrelInfo_->setSearchable(true);
pIndexer_->setDirty();
pIndexer_->getIndexReader();
pIndexMergeManager_->addToMerge(pCurBarrelInfo_);
pBarrelsInfo_->write(pIndexer_->getDirectory());
pIndexBarrelWriter_->reset();
pCurBarrelInfo_ = NULL;
DVLOG(2) << "<= IndexWriter::flush()";
}
void IndexWriter::flushDocLen()
{
if (pIndexBarrelWriter_) pIndexBarrelWriter_->flushDocLen();
}
void IndexWriter::createBarrelInfo()
{
DVLOG(2)<< "=> IndexWriter::createBarrelInfo()...";
pCurBarrelInfo_ = new BarrelInfo(pBarrelsInfo_->newBarrel(), 0, pIndexer_->pConfigurationManager_->indexStrategy_.indexLevel_, pIndexer_->getIndexCompressType());
pCurBarrelInfo_->setSearchable(pIndexer_->isRealTime());
pCurBarrelInfo_->setWriter(pIndexBarrelWriter_);
pIndexBarrelWriter_->setBarrelInfo(pCurBarrelInfo_);
pBarrelsInfo_->addBarrel(pCurBarrelInfo_);
DVLOG(2)<< "<= IndexWriter::createBarrelInfo()";
}
void IndexWriter::checkbinlog()
{
pIndexBarrelWriter_->checkbinlog();
}
void IndexWriter::deletebinlog()
{
pIndexBarrelWriter_->deletebinlog();
}
void IndexWriter::indexDocument(IndexerDocument& doc)
{
boost::lock_guard<boost::mutex> lock(indexMutex_);
if (!pCurBarrelInfo_) createBarrelInfo();
if (pIndexer_->isRealTime())
{
///If indexreader has not contained the in-memory barrel reader,
///The dirty flag should be set, so that the new query could open the in-memory barrel
///for real time query
if (!pIndexer_->pIndexReader_->hasMemBarrelReader())
pIndexer_->setDirty();
if (pIndexBarrelWriter_->cacheFull())
{
DVLOG(2) << "IndexWriter::indexDocument() => realtime cache full...";
flush();//
deletebinlog();
createBarrelInfo();
}
}
DocId uniqueID;
doc.getDocId(uniqueID);
if (pCurBarrelInfo_->getBaseDocID() == BAD_DOCID)
pCurBarrelInfo_->addBaseDocID(uniqueID.colId,uniqueID.docId);
pCurBarrelInfo_->updateMaxDoc(uniqueID.docId);
pBarrelsInfo_->updateMaxDoc(uniqueID.docId);
++(pCurBarrelInfo_->nNumDocs);
pIndexBarrelWriter_->addDocument(doc);
}
void IndexWriter::removeDocument(collectionid_t colID, docid_t docId)
{
pIndexer_->getIndexReader()->delDocument(colID, docId);
pIndexer_->pBTreeIndexer_->delDocument(pIndexer_->getBarrelsInfo()->maxDocId() + 1, docId);
if (!pIndexBarrelWriter_->getDocFilter())
pIndexBarrelWriter_->setDocFilter(pIndexer_->getIndexReader()->getDocFilter());
}
void IndexWriter::updateDocument(IndexerDocument& doc)
{
DocId uniqueID;
doc.getDocId(uniqueID);
// if (doc.getId() > pBarrelsInfo_->maxDocId())
// return;
indexDocument(doc);
removeDocument(uniqueID.colId,doc.getOldId());
}
void IndexWriter::updateRtypeDocument(IndexerDocument& oldDoc, IndexerDocument& doc)
{
DocId uniqueID;
doc.getDocId(uniqueID);
// rtype update is difference from common update, because rtype update is an inplace update while
// common update will remove old document and insert new document instead.
// so we should handle this separately.
// as result, the rtype property can not have any analyzer
std::list<std::pair<IndexerPropertyConfig, IndexerDocumentPropertyType> >&
propertyValueList = doc.getPropertyList();
std::map<IndexerPropertyConfig, IndexerDocumentPropertyType> oldDocMap;
oldDoc.to_map(oldDocMap);
for (std::list<std::pair<IndexerPropertyConfig, IndexerDocumentPropertyType> >::const_iterator iter
= propertyValueList.begin(); iter != propertyValueList.end(); ++iter)
{
if (iter->first.isIndex() && iter->first.isFilter())
{
map<IndexerPropertyConfig, IndexerDocumentPropertyType>::const_iterator it;
if ( (it = oldDocMap.find(iter->first)) != oldDocMap.end() )
{
if (it->second == iter->second)
continue;
if (it->first.isMultiValue())
{
MultiValuePropertyType oldProp = boost::get<MultiValuePropertyType>(it->second);
for (MultiValuePropertyType::iterator multiIt = oldProp.begin(); multiIt != oldProp.end(); ++multiIt)
pIndexer_->getBTreeIndexer()->remove(iter->first.getName(), *multiIt, uniqueID.docId);
}
else
{
PropertyType oldProp = boost::get<PropertyType>(it->second);
pIndexer_->getBTreeIndexer()->remove(iter->first.getName(), oldProp, uniqueID.docId);
}
}
if (iter->first.isMultiValue())
{
MultiValuePropertyType prop = boost::get<MultiValuePropertyType>(iter->second);
for (MultiValuePropertyType::iterator multiIt = prop.begin(); multiIt != prop.end(); ++multiIt)
pIndexer_->getBTreeIndexer()->add(iter->first.getName(), *multiIt, uniqueID.docId);
}
else
{
PropertyType prop = boost::get<PropertyType>(iter->second);
pIndexer_->getBTreeIndexer()->add(iter->first.getName(), prop, uniqueID.docId);
}
}
}
}
void IndexWriter::optimizeIndex()
{
boost::lock_guard<boost::mutex> lock(indexMutex_);
flush();
if(pIndexer_->isRealTime())
deletebinlog();
pIndexMergeManager_->optimizeIndex();
}
void IndexWriter::lazyOptimizeIndex()
{
using namespace boost::posix_time;
using namespace boost::gregorian;
using namespace izenelib::util;
boost::posix_time::ptime now = second_clock::local_time();
boost::gregorian::date date = now.date();
boost::posix_time::time_duration du = now.time_of_day();
int dow = date.day_of_week();
int month = date.month();
int day = date.day();
int hour = du.hours();
int minute = du.minutes();
if (scheduleExpression_.matches(minute, hour, day, month, dow))
{
boost::lock_guard<boost::mutex> lock(indexMutex_);
flush();
if(pIndexer_->isRealTime())
deletebinlog();
pIndexMergeManager_->optimizeIndex();
}
}
void IndexWriter::scheduleOptimizeTask(std::string expression, string uuid)
{
scheduleExpression_.setExpression(expression);
const string optimizeJob = "optimizeindex"+uuid;
///we need an uuid here because scheduler is an singleton in the system
Scheduler::removeJob(optimizeJob);
optimizeJobDesc_ = optimizeJob;
boost::function<void (void)> task = boost::bind(&IndexWriter::lazyOptimizeIndex,this);
Scheduler::addJob(optimizeJob, 60*1000, 0, task);
}
void IndexWriter::setIndexMode(bool realtime)
{
if (!pIndexBarrelWriter_)
{
pIndexBarrelWriter_ = new IndexBarrelWriter(pIndexer_);
pIndexBarrelWriter_->setCollectionsMeta(pIndexer_->getCollectionsMeta());
}
pIndexBarrelWriter_->setIndexMode(realtime);
}
}
NS_IZENELIB_IR_END
<commit_msg>Fix counting error of index during duplicate deleting documents<commit_after>#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/local_time_adjustor.hpp>
#include <boost/date_time/c_local_time_adjustor.hpp>
#include <boost/thread.hpp>
#include <cassert>
#include <ir/index_manager/index/Indexer.h>
#include <ir/index_manager/index/IndexWriter.h>
#include <ir/index_manager/index/IndexReader.h>
#include <ir/index_manager/index/IndexBarrelWriter.h>
#include <ir/index_manager/index/IndexerPropertyConfig.h>
#include <ir/index_manager/index/IndexMergeManager.h>
#include <ir/index_manager/index/rtype/BTreeIndexerManager.h>
#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
#include <util/scheduler.h>
#include <fstream>
using namespace std;
NS_IZENELIB_IR_BEGIN
namespace indexmanager{
namespace bfs = boost::filesystem;
IndexWriter::IndexWriter(Indexer* pIndex)
:pIndexer_(pIndex)
,pIndexBarrelWriter_(NULL)
,pBarrelsInfo_(NULL)
,pCurBarrelInfo_(NULL)
,pIndexMergeManager_(NULL)
{
pBarrelsInfo_ = pIndexer_->getBarrelsInfo();
pIndexMergeManager_ = new IndexMergeManager(pIndex);
}
IndexWriter::~IndexWriter()
{
if (!optimizeJobDesc_.empty())
Scheduler::removeJob(optimizeJobDesc_);
if (pIndexMergeManager_)
delete pIndexMergeManager_;
if (pIndexBarrelWriter_)
delete pIndexBarrelWriter_;
}
void IndexWriter::tryResumeExistingBarrels()
{
// in order to resume merging previous barrels,
// add them into pIndexMergeManager_
BarrelInfo* pBarrelInfo = NULL;
boost::mutex::scoped_lock lock(pBarrelsInfo_->getMutex());
pBarrelsInfo_->startIterator();
while (pBarrelsInfo_->hasNext())
{
pBarrelInfo = pBarrelsInfo_->next();
assert(pBarrelInfo->getWriter() == NULL && "the loaded BarrelInfo should not be in-memory barrel");
pIndexMergeManager_->addToMerge(pBarrelInfo);
}
}
void IndexWriter::close()
{
///The difference between close and flush is close don't need t reopen indexreader
DVLOG(2) << "=> IndexWriter::close()...";
if (pCurBarrelInfo_ == NULL)
{
// write file "barrels" to update the doc count of each barrel
if (pBarrelsInfo_->getBarrelCount() > 0)
pBarrelsInfo_->write(pIndexer_->getDirectory());
DVLOG(2) << "<= IndexWriter::flush(), pCurBarrelInfo_ is NULL";
return;
}
assert(pIndexBarrelWriter_ && "pIndexBarrelWriter_ should have been created with pCurBarrelInfo_ together in IndexWriter::createBarrelInfo()");
/*for realtime index need not flush when stop normally*/
//pIndexBarrelWriter_->flush();
//pBarrelsInfo_->write(pIndexer_->getDirectory());
pIndexBarrelWriter_->reset();
pCurBarrelInfo_ = NULL;
DVLOG(2) << "<= IndexWriter::close()";
}
void IndexWriter::flush()
{
DVLOG(2) << "=> IndexWriter::flush()...";
if (!pCurBarrelInfo_)
{
// write file "barrels" to update the doc count of each barrel
if (pBarrelsInfo_->getBarrelCount() > 0)
pBarrelsInfo_->write(pIndexer_->getDirectory());
DVLOG(2) << "<= IndexWriter::flush(), pCurBarrelInfo_ is NULL";
return;
}
assert(pIndexBarrelWriter_ && "pIndexBarrelWriter_ should have been created with pCurBarrelInfo_ together in IndexWriter::createBarrelInfo()");
pIndexBarrelWriter_->flush();
if (!pIndexer_->isRealTime())
pCurBarrelInfo_->setSearchable(true);
pIndexer_->setDirty();
pIndexer_->getIndexReader();
pIndexMergeManager_->addToMerge(pCurBarrelInfo_);
pBarrelsInfo_->write(pIndexer_->getDirectory());
pIndexBarrelWriter_->reset();
pCurBarrelInfo_ = NULL;
DVLOG(2) << "<= IndexWriter::flush()";
}
void IndexWriter::flushDocLen()
{
if (pIndexBarrelWriter_) pIndexBarrelWriter_->flushDocLen();
}
void IndexWriter::createBarrelInfo()
{
DVLOG(2)<< "=> IndexWriter::createBarrelInfo()...";
pCurBarrelInfo_ = new BarrelInfo(pBarrelsInfo_->newBarrel(), 0, pIndexer_->pConfigurationManager_->indexStrategy_.indexLevel_, pIndexer_->getIndexCompressType());
pCurBarrelInfo_->setSearchable(pIndexer_->isRealTime());
pCurBarrelInfo_->setWriter(pIndexBarrelWriter_);
pIndexBarrelWriter_->setBarrelInfo(pCurBarrelInfo_);
pBarrelsInfo_->addBarrel(pCurBarrelInfo_);
DVLOG(2)<< "<= IndexWriter::createBarrelInfo()";
}
void IndexWriter::checkbinlog()
{
pIndexBarrelWriter_->checkbinlog();
}
void IndexWriter::deletebinlog()
{
pIndexBarrelWriter_->deletebinlog();
}
void IndexWriter::indexDocument(IndexerDocument& doc)
{
boost::lock_guard<boost::mutex> lock(indexMutex_);
if (!pCurBarrelInfo_) createBarrelInfo();
if (pIndexer_->isRealTime())
{
///If indexreader has not contained the in-memory barrel reader,
///The dirty flag should be set, so that the new query could open the in-memory barrel
///for real time query
if (!pIndexer_->pIndexReader_->hasMemBarrelReader())
pIndexer_->setDirty();
if (pIndexBarrelWriter_->cacheFull())
{
DVLOG(2) << "IndexWriter::indexDocument() => realtime cache full...";
flush();//
deletebinlog();
createBarrelInfo();
}
}
DocId uniqueID;
doc.getDocId(uniqueID);
if (pCurBarrelInfo_->getBaseDocID() == BAD_DOCID)
pCurBarrelInfo_->addBaseDocID(uniqueID.colId,uniqueID.docId);
pCurBarrelInfo_->updateMaxDoc(uniqueID.docId);
pBarrelsInfo_->updateMaxDoc(uniqueID.docId);
++(pCurBarrelInfo_->nNumDocs);
pIndexBarrelWriter_->addDocument(doc);
}
void IndexWriter::removeDocument(collectionid_t colID, docid_t docId)
{
///avoid of delete counting error
BitVector* del_filter = pIndexer_->getIndexReader()->getDocFilter();
if(del_filter && del_filter->test(docId)) return;
///Perform deletion
pIndexer_->getIndexReader()->delDocument(colID, docId);
pIndexer_->pBTreeIndexer_->delDocument(pIndexer_->getBarrelsInfo()->maxDocId() + 1, docId);
if (!pIndexBarrelWriter_->getDocFilter())
pIndexBarrelWriter_->setDocFilter(pIndexer_->getIndexReader()->getDocFilter());
}
void IndexWriter::updateDocument(IndexerDocument& doc)
{
DocId uniqueID;
doc.getDocId(uniqueID);
// if (doc.getId() > pBarrelsInfo_->maxDocId())
// return;
indexDocument(doc);
removeDocument(uniqueID.colId,doc.getOldId());
}
void IndexWriter::updateRtypeDocument(IndexerDocument& oldDoc, IndexerDocument& doc)
{
DocId uniqueID;
doc.getDocId(uniqueID);
// rtype update is difference from common update, because rtype update is an inplace update while
// common update will remove old document and insert new document instead.
// so we should handle this separately.
// as result, the rtype property can not have any analyzer
std::list<std::pair<IndexerPropertyConfig, IndexerDocumentPropertyType> >&
propertyValueList = doc.getPropertyList();
std::map<IndexerPropertyConfig, IndexerDocumentPropertyType> oldDocMap;
oldDoc.to_map(oldDocMap);
for (std::list<std::pair<IndexerPropertyConfig, IndexerDocumentPropertyType> >::const_iterator iter
= propertyValueList.begin(); iter != propertyValueList.end(); ++iter)
{
if (iter->first.isIndex() && iter->first.isFilter())
{
map<IndexerPropertyConfig, IndexerDocumentPropertyType>::const_iterator it;
if ( (it = oldDocMap.find(iter->first)) != oldDocMap.end() )
{
if (it->second == iter->second)
continue;
if (it->first.isMultiValue())
{
MultiValuePropertyType oldProp = boost::get<MultiValuePropertyType>(it->second);
for (MultiValuePropertyType::iterator multiIt = oldProp.begin(); multiIt != oldProp.end(); ++multiIt)
pIndexer_->getBTreeIndexer()->remove(iter->first.getName(), *multiIt, uniqueID.docId);
}
else
{
PropertyType oldProp = boost::get<PropertyType>(it->second);
pIndexer_->getBTreeIndexer()->remove(iter->first.getName(), oldProp, uniqueID.docId);
}
}
if (iter->first.isMultiValue())
{
MultiValuePropertyType prop = boost::get<MultiValuePropertyType>(iter->second);
for (MultiValuePropertyType::iterator multiIt = prop.begin(); multiIt != prop.end(); ++multiIt)
pIndexer_->getBTreeIndexer()->add(iter->first.getName(), *multiIt, uniqueID.docId);
}
else
{
PropertyType prop = boost::get<PropertyType>(iter->second);
pIndexer_->getBTreeIndexer()->add(iter->first.getName(), prop, uniqueID.docId);
}
}
}
}
void IndexWriter::optimizeIndex()
{
boost::lock_guard<boost::mutex> lock(indexMutex_);
flush();
if(pIndexer_->isRealTime())
deletebinlog();
pIndexMergeManager_->optimizeIndex();
}
void IndexWriter::lazyOptimizeIndex()
{
using namespace boost::posix_time;
using namespace boost::gregorian;
using namespace izenelib::util;
boost::posix_time::ptime now = second_clock::local_time();
boost::gregorian::date date = now.date();
boost::posix_time::time_duration du = now.time_of_day();
int dow = date.day_of_week();
int month = date.month();
int day = date.day();
int hour = du.hours();
int minute = du.minutes();
if (scheduleExpression_.matches(minute, hour, day, month, dow))
{
boost::lock_guard<boost::mutex> lock(indexMutex_);
flush();
if(pIndexer_->isRealTime())
deletebinlog();
pIndexMergeManager_->optimizeIndex();
}
}
void IndexWriter::scheduleOptimizeTask(std::string expression, string uuid)
{
scheduleExpression_.setExpression(expression);
const string optimizeJob = "optimizeindex"+uuid;
///we need an uuid here because scheduler is an singleton in the system
Scheduler::removeJob(optimizeJob);
optimizeJobDesc_ = optimizeJob;
boost::function<void (void)> task = boost::bind(&IndexWriter::lazyOptimizeIndex,this);
Scheduler::addJob(optimizeJob, 60*1000, 0, task);
}
void IndexWriter::setIndexMode(bool realtime)
{
if (!pIndexBarrelWriter_)
{
pIndexBarrelWriter_ = new IndexBarrelWriter(pIndexer_);
pIndexBarrelWriter_->setCollectionsMeta(pIndexer_->getCollectionsMeta());
}
pIndexBarrelWriter_->setIndexMode(realtime);
}
}
NS_IZENELIB_IR_END
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbISRAUnmixingImageFilter.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include "otbVectorImageToMatrixImageFilter.h"
#include "otbStandardWriterWatcher.h"
const unsigned int Dimension = 2;
typedef double PixelType;
typedef otb::VectorImage<PixelType, Dimension> ImageType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::ISRAUnmixingImageFilter<ImageType,ImageType,double> UnmixingImageFilterType;
typedef otb::VectorImageToMatrixImageFilter<ImageType> VectorImageToMatrixImageFilterType;
typedef otb::StreamingImageFileWriter<ImageType> WriterType;
int otbISRAUnmixingImageFilterNewTest(int argc, char * argv[])
{
UnmixingImageFilterType::Pointer filter = UnmixingImageFilterType::New();
std::cout << filter << std::endl;
return EXIT_SUCCESS;
}
int otbISRAUnmixingImageFilterTest(int argc, char * argv[])
{
const char * inputImage = argv[1];
const char * inputEndmembers = argv[2];
const char * outputImage = argv[3];
int maxIter = atoi(argv[4]);
ReaderType::Pointer readerImage = ReaderType::New();
readerImage->SetFileName(inputImage);
ReaderType::Pointer readerEndMembers = ReaderType::New();
readerEndMembers->SetFileName(inputEndmembers);
VectorImageToMatrixImageFilterType::Pointer endMember2Matrix = VectorImageToMatrixImageFilterType::New();
endMember2Matrix->SetInput(readerEndMembers->GetOutput());
endMember2Matrix->Update();
typedef VectorImageToMatrixImageFilterType::MatrixType MatrixType;
MatrixType endMembers = endMember2Matrix->GetMatrix();
MatrixType pinv = vnl_matrix_inverse<PixelType>(endMembers);
UnmixingImageFilterType::Pointer unmixer = UnmixingImageFilterType::New();
unmixer->SetInput(readerImage->GetOutput());
unmixer->SetMaxIteration(maxIter);
unmixer->SetEndmembersMatrix(endMember2Matrix->GetMatrix());
WriterType::Pointer writer = WriterType::New();
writer->SetFileName(outputImage);
writer->SetInput(unmixer->GetOutput());
writer->SetBufferNumberOfLinesDivisions(10);
otb::StandardWriterWatcher w4(writer,unmixer,"FullyConstrainedLeastSquare");
writer->Update();
return EXIT_SUCCESS;
}
<commit_msg>TEST: fix watcher name<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbISRAUnmixingImageFilter.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include "otbVectorImageToMatrixImageFilter.h"
#include "otbStandardWriterWatcher.h"
const unsigned int Dimension = 2;
typedef double PixelType;
typedef otb::VectorImage<PixelType, Dimension> ImageType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::ISRAUnmixingImageFilter<ImageType,ImageType,double> UnmixingImageFilterType;
typedef otb::VectorImageToMatrixImageFilter<ImageType> VectorImageToMatrixImageFilterType;
typedef otb::StreamingImageFileWriter<ImageType> WriterType;
int otbISRAUnmixingImageFilterNewTest(int argc, char * argv[])
{
UnmixingImageFilterType::Pointer filter = UnmixingImageFilterType::New();
std::cout << filter << std::endl;
return EXIT_SUCCESS;
}
int otbISRAUnmixingImageFilterTest(int argc, char * argv[])
{
const char * inputImage = argv[1];
const char * inputEndmembers = argv[2];
const char * outputImage = argv[3];
int maxIter = atoi(argv[4]);
ReaderType::Pointer readerImage = ReaderType::New();
readerImage->SetFileName(inputImage);
ReaderType::Pointer readerEndMembers = ReaderType::New();
readerEndMembers->SetFileName(inputEndmembers);
VectorImageToMatrixImageFilterType::Pointer endMember2Matrix = VectorImageToMatrixImageFilterType::New();
endMember2Matrix->SetInput(readerEndMembers->GetOutput());
endMember2Matrix->Update();
typedef VectorImageToMatrixImageFilterType::MatrixType MatrixType;
MatrixType endMembers = endMember2Matrix->GetMatrix();
MatrixType pinv = vnl_matrix_inverse<PixelType>(endMembers);
UnmixingImageFilterType::Pointer unmixer = UnmixingImageFilterType::New();
unmixer->SetInput(readerImage->GetOutput());
unmixer->SetMaxIteration(maxIter);
unmixer->SetNumberOfThreads(1);
unmixer->SetEndmembersMatrix(endMember2Matrix->GetMatrix());
WriterType::Pointer writer = WriterType::New();
writer->SetFileName(outputImage);
writer->SetInput(unmixer->GetOutput());
writer->SetBufferNumberOfLinesDivisions(10);
otb::StandardWriterWatcher w4(writer,unmixer,"ISRAUnmixingImageFilter");
writer->Update();
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include "Sanitizers.h"
#include "IRMutator.h"
#include "Debug.h"
#include "IRPrinter.h"
#include "CodeGen_GPU_Dev.h"
#include "IROperator.h"
#include <map>
namespace Halide {
namespace Internal {
namespace {
class InjectMSANHelpers : public IRMutator {
using IRMutator::visit;
void visit(const ProducerConsumer *op) {
Stmt produce, update, consume;
std::cerr << "ProducerConsumer "<< op->name << "\n";
produce = mutate(op->produce);
if (op->update.defined()) {
update = mutate(op->update);
}
consume = mutate(op->consume);
Expr buffer = Variable::make(type_of<struct buffer_t *>(), op->name + ".buffer");
Expr call = Call::make(Int(32), "halide_msan_annotate_buffer_is_initialized", {buffer}, Call::Extern);
std::string call_result_name = unique_name(op->name + "_annotate_result");
Expr call_result_var = Variable::make(Int(32), call_result_name);
Stmt annotate = LetStmt::make(call_result_name, call, AssertStmt::make(EQ::make(call_result_var, 0), call_result_var));
if (op->update.defined()) {
update = Block::make(update, annotate);
} else {
produce = Block::make(produce, annotate);
}
stmt = ProducerConsumer::make(op->name, produce, update, consume);
}
public:
InjectMSANHelpers() {}
};
} // namespace
Stmt inject_msan_helpers(Stmt s) {
return InjectMSANHelpers().mutate(s);
}
}
}
<commit_msg>Remove scalpel left in patient<commit_after>#include "Sanitizers.h"
#include "IRMutator.h"
#include "Debug.h"
#include "IRPrinter.h"
#include "CodeGen_GPU_Dev.h"
#include "IROperator.h"
#include <map>
namespace Halide {
namespace Internal {
namespace {
class InjectMSANHelpers : public IRMutator {
using IRMutator::visit;
void visit(const ProducerConsumer *op) {
Stmt produce, update, consume;
produce = mutate(op->produce);
if (op->update.defined()) {
update = mutate(op->update);
}
consume = mutate(op->consume);
Expr buffer = Variable::make(type_of<struct buffer_t *>(), op->name + ".buffer");
Expr call = Call::make(Int(32), "halide_msan_annotate_buffer_is_initialized", {buffer}, Call::Extern);
std::string call_result_name = unique_name(op->name + "_annotate_result");
Expr call_result_var = Variable::make(Int(32), call_result_name);
Stmt annotate = LetStmt::make(call_result_name, call, AssertStmt::make(EQ::make(call_result_var, 0), call_result_var));
if (op->update.defined()) {
update = Block::make(update, annotate);
} else {
produce = Block::make(produce, annotate);
}
stmt = ProducerConsumer::make(op->name, produce, update, consume);
}
public:
InjectMSANHelpers() {}
};
} // namespace
Stmt inject_msan_helpers(Stmt s) {
return InjectMSANHelpers().mutate(s);
}
}
}
<|endoftext|>
|
<commit_before>/*
* GeoIP C library binding for nodejs
*
* Licensed under the GNU LGPL 2.1 license
*/
#include "org.h"
#include "global.h"
using namespace native;
Org::Org() {};
Org::~Org() { if (db) {
GeoIP_delete(db);
}
};
Nan::Persistent<v8::Function> Org::constructor;
void Org::Init(v8::Local<v8::Object> exports) {
Nan::HandleScope scope;
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
tpl->SetClassName(Nan::New("Org").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->PrototypeTemplate()->Set(Nan::New("lookupSync").ToLocalChecked(),
Nan::New<v8::FunctionTemplate>(lookupSync)->GetFunction());
constructor.Reset(tpl->GetFunction());
exports->Set(Nan::New("Org").ToLocalChecked(), tpl->GetFunction());;
}
NAN_METHOD(Org::New) {
Nan::HandleScope scope;
Org *o = new Org();
String::Utf8Value file_str(info[0]->ToString());
const char *file_cstr = ToCString(file_str);
bool cache_on = info[1]->ToBoolean()->Value();
o->db = GeoIP_open(file_cstr, cache_on?GEOIP_MEMORY_CACHE:GEOIP_STANDARD);
if (o->db) {
// Successfully opened the file, return 1 (true)
o->db_edition = GeoIP_database_edition(o->db);
if (o->db_edition == GEOIP_ORG_EDITION ||
o->db_edition == GEOIP_ASNUM_EDITION ||
o->db_edition == GEOIP_ISP_EDITION) {
o->Wrap(info.This());
info.GetReturnValue().Set(info.This());
} else {
GeoIP_delete(o->db); // free()'s the reference & closes fd
return Nan::ThrowError("Error: Not valid org database");
}
} else {
return Nan::ThrowError("Error: Cannot open database");
}
}
NAN_METHOD(Org::lookupSync) {
Nan::HandleScope scope;
Org *o = ObjectWrap::Unwrap<Org>(info.This());
//static Nan::Utf8String *host_cstr = new Nan::Utf8String(info[0]);
Nan::Utf8String host_cstr(info[0]);
uint32_t ipnum = _GeoIP_lookupaddress(*host_cstr);
if (ipnum <= 0) {
info.GetReturnValue().SetNull();
}
char *org = GeoIP_org_by_ipnum(o->db, ipnum);
if (!org) {
info.GetReturnValue().SetNull();
}
//char *name = _GeoIP_iso_8859_1__utf8(org);
//data = Nan::New<String>(_GeoIP_iso_8859_1__utf8(org)).ToLocalChecked();
free(org);
//free(name);
info.GetReturnValue().Set(
Nan::New<String>(_GeoIP_iso_8859_1__utf8(org)).ToLocalChecked());
}
<commit_msg>Fixed segment fault<commit_after>/*
* GeoIP C library binding for nodejs
*
* Licensed under the GNU LGPL 2.1 license
*/
#include "org.h"
#include "global.h"
using namespace native;
Org::Org() {};
Org::~Org() { if (db) {
GeoIP_delete(db);
}
};
Nan::Persistent<v8::Function> Org::constructor;
void Org::Init(v8::Local<v8::Object> exports) {
Nan::HandleScope scope;
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
tpl->SetClassName(Nan::New("Org").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->PrototypeTemplate()->Set(Nan::New("lookupSync").ToLocalChecked(),
Nan::New<v8::FunctionTemplate>(lookupSync)->GetFunction());
constructor.Reset(tpl->GetFunction());
exports->Set(Nan::New("Org").ToLocalChecked(), tpl->GetFunction());;;
}
NAN_METHOD(Org::New) {
Nan::HandleScope scope;
Org *o = new Org();
String::Utf8Value file_str(info[0]->ToString());
const char *file_cstr = ToCString(file_str);
bool cache_on = info[1]->ToBoolean()->Value();
o->db = GeoIP_open(file_cstr, cache_on?GEOIP_MEMORY_CACHE:GEOIP_STANDARD);
if (o->db) {
// Successfully opened the file, return 1 (true)
o->db_edition = GeoIP_database_edition(o->db);
if (o->db_edition == GEOIP_ORG_EDITION ||
o->db_edition == GEOIP_ASNUM_EDITION ||
o->db_edition == GEOIP_ISP_EDITION) {
o->Wrap(info.This());
info.GetReturnValue().Set(info.This());
} else {
GeoIP_delete(o->db); // free()'s the reference & closes fd
return Nan::ThrowError("Error: Not valid org database");
}
} else {
return Nan::ThrowError("Error: Cannot open database");
}
}
NAN_METHOD(Org::lookupSync) {
Nan::HandleScope scope;
Local<Value> data = Nan::New(Nan::Null());
//Local<String> host_str = info[0]->ToString();
//size_t size = host_str->Length() + 1;
//char host_cstr[size];
//size_t bc;
//NanCString(info[0], &bc, host_cstr, size);
Org *o = ObjectWrap::Unwrap<Org>(info.This());
Nan::Utf8String host_cstr(info[0]->ToString());
uint32_t ipnum = _GeoIP_lookupaddress(*host_cstr);
if (ipnum <= 0) {
info.GetReturnValue().SetNull();
}
char *org = GeoIP_org_by_ipnum(o->db, ipnum);
if (!org) {
info.GetReturnValue().SetNull();
}
char *name = _GeoIP_iso_8859_1__utf8(org);
data = Nan::New<String>(name).ToLocalChecked();
free(org);
free(name);
info.GetReturnValue().Set(data);
}
<|endoftext|>
|
<commit_before>/*
* IrcEventMessage.cpp -- on channel message event
*
* Copyright (c) 2013 David Demelier <markand@malikania.fr>
*
* 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 "IrcEventMessage.h"
namespace irccd {
IrcEventMessage::IrcEventMessage(Server::Ptr server,
const std::string &channel,
const std::string &who,
const std::string &message)
: m_server(server)
, m_channel(channel)
, m_who(who)
, m_message(message)
{
}
void IrcEventMessage::action(lua_State *L) const
{
auto cc = m_server->getOptions().commandChar;
auto name = Process::info(L).name;
auto msg = m_message;
bool iscommand(false);
// handle special commands "!<plugin> command"
if (cc.length() > 0) {
auto pos = msg.find_first_of(" \t");
/*
* If the message that comes is "!foo" without spaces we
* compare the command char + the plugin name. If there
* is a space, we check until we find a space, if not
* typing "!foo123123" will trigger foo plugin.
*/
if (pos == std::string::npos) {
iscommand = msg.length() == cc.length() + name.length() &&
msg.compare(cc.length(), name.length(), name) == 0;
} else {
iscommand = msg.compare(cc.length(), pos - 1, name) == 0;
}
if (iscommand) {
/*
* If no space is found we just set the message to "" otherwise
* the plugin name will be passed through onCommand
*/
if (pos == std::string::npos)
msg = "";
else
msg = m_message.substr(pos + 1);
}
}
if (iscommand)
call(L, "onCommand", m_server, m_channel, m_who, msg);
else
call(L, "onMessage", m_server, m_channel, m_who, msg);
}
} // !irccd
<commit_msg>Fix bad detection of commands because the command character was not included<commit_after>/*
* IrcEventMessage.cpp -- on channel message event
*
* Copyright (c) 2013 David Demelier <markand@malikania.fr>
*
* 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 "IrcEventMessage.h"
namespace irccd {
IrcEventMessage::IrcEventMessage(Server::Ptr server,
const std::string &channel,
const std::string &who,
const std::string &message)
: m_server(server)
, m_channel(channel)
, m_who(who)
, m_message(message)
{
}
void IrcEventMessage::action(lua_State *L) const
{
auto cc = m_server->getOptions().commandChar;
auto name = Process::info(L).name;
auto msg = m_message;
bool iscommand(false);
// handle special commands "!<plugin> command"
if (cc.length() > 0) {
auto pos = msg.find_first_of(" \t");
auto fullcommand = cc + name;
/*
* If the message that comes is "!foo" without spaces we
* compare the command char + the plugin name. If there
* is a space, we check until we find a space, if not
* typing "!foo123123" will trigger foo plugin.
*/
if (pos == std::string::npos) {
iscommand = msg == fullcommand;
} else {
iscommand = msg.length() >= fullcommand.length() &&
msg.compare(0, fullcommand.length(), fullcommand) == 0;
}
if (iscommand) {
/*
* If no space is found we just set the message to "" otherwise
* the plugin name will be passed through onCommand
*/
if (pos == std::string::npos)
msg = "";
else
msg = m_message.substr(pos + 1);
}
}
if (iscommand)
call(L, "onCommand", m_server, m_channel, m_who, msg);
else
call(L, "onMessage", m_server, m_channel, m_who, msg);
}
} // !irccd
<|endoftext|>
|
<commit_before>/*! \file io.cxx
* \brief this file contains routines for io
*/
#include "halomergertree.h"
///Read data from a number of snapshot files
HaloTreeData *ReadData(Options &opt)
{
HaloTreeData *HaloTree;
fstream Fin;//file is list of halo data files
long unsigned j,nparts,haloid;
HaloTree=new HaloTreeData[opt.numsnapshots];
char buf[1000*opt.numsnapshots];
Int_t tothalos=0;
int i,nthreads;
Fin.open(opt.fname);
if (!Fin.is_open()) {cerr<<"file containing snapshot list can't be opened"<<endl;exit(9);}
#ifndef USEOPENMP
nthreads=1;
#else
#pragma omp parallel
{
if (omp_get_thread_num()==0) nthreads=omp_get_num_threads();
}
#endif
#ifdef USEOPENMP
for(i=0; i<opt.numsnapshots; i++) Fin>>&(buf[i*1000]);
#pragma omp parallel default(shared) \
private(i)
{
#pragma omp for reduction(+:tothalos)
for(i=0; i<opt.numsnapshots; i++)
{
if (opt.ioformat==DSUSSING) HaloTree[i].Halo=ReadHaloData(&buf[i*1000],HaloTree[i].numhalos);
else if (opt.ioformat==DCATALOG) HaloTree[i].Halo=ReadHaloGroupCatalogData(&buf[i*1000],HaloTree[i].numhalos, opt.nmpifiles, opt.ibinary,opt.ifield, opt.itypematch);
else if (opt.ioformat==DNIFTY) HaloTree[i].Halo=ReadNIFTYData(&buf[i*1000],HaloTree[i].numhalos, opt.idcorrectflag);
tothalos+=HaloTree[i].numhalos;
}
}
opt.TotalNumberofHalos=tothalos;
#else
for(i=0; i<opt.numsnapshots; i++)
{
Fin>>buf;
if (opt.ioformat==DSUSSING) HaloTree[i].Halo=ReadHaloData(buf,HaloTree[i].numhalos);
else if (opt.ioformat==DCATALOG) HaloTree[i].Halo=ReadHaloGroupCatalogData(buf,HaloTree[i].numhalos, opt.nmpifiles, opt.ibinary, opt.ifield, opt.itypematch);
else if (opt.ioformat==DNIFTY) HaloTree[i].Halo=ReadNIFTYData(buf,HaloTree[i].numhalos, opt.idcorrectflag);
opt.TotalNumberofHalos+=HaloTree[i].numhalos;
}
#endif
Fin.close();
return HaloTree;
}
void WriteHaloMergerTree(Options &opt, ProgenitorData **p, HaloTreeData *h) {
fstream Fout;
char fname[1000];
sprintf(fname,"%s",opt.outname);
cout<<"saving halo merger tree to "<<fname<<endl;
Fout.open(fname,ios::out);
Fout<<1<<endl;
Fout<<opt.description<<endl;
Fout<<opt.TotalNumberofHalos<<endl;
if (opt.outputformat==0) {
for (int i=opt.numsnapshots-1;i>0;i--) {
Fout<<i+opt.snapshotvaloffset<<"\t"<<h[i].numhalos<<endl;
for (int j=0;j<h[i].numhalos;j++) {
Fout<<h[i].Halo[j].haloID<<"\t"<<p[i][j].NumberofProgenitors<<endl;
for (int k=0;k<p[i][j].NumberofProgenitors;k++) {
Fout<<h[i-1].Halo[p[i][j].ProgenitorList[k]].haloID<<endl;
}
}
}
}
else {
for (int i=opt.numsnapshots-1;i>0;i--) {
Fout<<i+opt.snapshotvaloffset<<"\t"<<h[i].numhalos<<endl;
for (int j=0;j<h[i].numhalos;j++) {
Fout<<h[i].Halo[j].haloID<<"\t"<<p[i][j].NumberofProgenitors<<endl;
for (int k=0;k<p[i][j].NumberofProgenitors;k++) {
Fout<<h[i-1].Halo[p[i][j].ProgenitorList[k]].haloID<<" "<<p[i][j].Merit[k]<<endl;
}
}
}
}
///last file has no connections
for (int j=0;j<h[0].numhalos;j++) {
Fout<<h[0].Halo[j].haloID<<"\t"<<0<<endl;
}
Fout<<"END"<<endl;
Fout.close();
}
void WriteHaloGraph(Options &opt, ProgenitorData **p, DescendantData **d, HaloTreeData *h) {
fstream Fout;
char fname[1000];
sprintf(fname,"%s",opt.outname);
cout<<"saving halo merger tree to "<<fname<<endl;
Fout.open(fname,ios::out);
Fout<<1<<endl;
Fout<<opt.description<<endl;
Fout<<opt.TotalNumberofHalos<<endl;
if (opt.outputformat==0) {
for (int i=opt.numsnapshots-1;i>=0;i--) {
Fout<<i+opt.snapshotvaloffset<<"\t"<<h[i].numhalos<<endl;
for (int j=0;j<h[i].numhalos;j++) {
Fout<<h[i].Halo[j].haloID<<"\t"<<p[i][j].NumberofProgenitors<<"\t"<<d[i][j].NumberofDescendants<<endl;
for (int k=0;k<p[i][j].NumberofProgenitors;k++) {
Fout<<h[i-1].Halo[p[i][j].ProgenitorList[k]].haloID<<endl;
}
for (int k=0;k<d[i][j].NumberofDescendants;k++) {
Fout<<h[i+1].Halo[d[i][j].DescendantList[k]].haloID<<endl;
}
}
}
}
else {
for (int i=opt.numsnapshots-1;i>=0;i--) {
Fout<<i+opt.snapshotvaloffset<<"\t"<<h[i].numhalos<<endl;
for (int j=0;j<h[i].numhalos;j++) {
Fout<<h[i].Halo[j].haloID<<"\t"<<p[i][j].NumberofProgenitors<<"\t"<<d[i][j].NumberofDescendants<<endl;
for (int k=0;k<p[i][j].NumberofProgenitors;k++) {
Fout<<h[i-1].Halo[p[i][j].ProgenitorList[k]].haloID<<" "<<p[i][j].Merit[k]<<endl;
}
for (int k=0;k<d[i][j].NumberofDescendants;k++) {
Fout<<h[i+1].Halo[d[i][j].DescendantList[k]].haloID<<" "<<d[i][j].Merit[k]<<endl;
}
}
}
}
Fout<<"END"<<endl;
Fout.close();
}
void WriteCrossComp(Options &opt, ProgenitorData **p, HaloTreeData *h) {
fstream Fout;
char fname[1000];
sprintf(fname,"%s",opt.outname);
cout<<"saving halo merger tree to "<<fname<<endl;
Fout.open(fname,ios::out);
Fout<<opt.description<<endl;
Fout<<opt.TotalNumberofHalos<<endl;
if (opt.outputformat==0) {
for (int i=opt.numsnapshots-1;i>0;i--) {
Fout<<i<<"\t"<<h[i].numhalos<<endl;
for (int j=0;j<h[i].numhalos;j++) {
Fout<<h[i].Halo[j].haloID<<"\t"<<p[i][j].NumberofProgenitors<<endl;
for (int k=0;k<p[i][j].NumberofProgenitors;k++) {
Fout<<h[i-1].Halo[p[i][j].ProgenitorList[k]].haloID<<" "<<p[i][j].Merit[k]<<endl;
}
}
}
}
else if (opt.outputformat==1) {
for (int i=opt.numsnapshots-1;i>0;i--) {
Fout<<i<<"\t"<<h[i].numhalos<<endl;
for (int j=0;j<h[i].numhalos;j++) {
Fout<<h[i].Halo[j].haloID<<"\t"<<p[i][j].NumberofProgenitors<<endl;
for (int k=0;k<p[i][j].NumberofProgenitors;k++) {
Fout<<h[i-1].Halo[p[i][j].ProgenitorList[k]].haloID<<" "<<p[i][j].Merit[k]<<" "<<p[i][j].nsharedfrac[k]<<" ";
}
}
}
}
Fout<<"END"<<endl;
Fout.close();
}
<commit_msg>correction to halo merger io<commit_after>/*! \file io.cxx
* \brief this file contains routines for io
*/
#include "halomergertree.h"
///Read data from a number of snapshot files
HaloTreeData *ReadData(Options &opt)
{
HaloTreeData *HaloTree;
fstream Fin;//file is list of halo data files
long unsigned j,nparts,haloid;
HaloTree=new HaloTreeData[opt.numsnapshots];
char buf[1000*opt.numsnapshots];
Int_t tothalos=0;
int i,nthreads;
Fin.open(opt.fname);
if (!Fin.is_open()) {cerr<<"file containing snapshot list can't be opened"<<endl;exit(9);}
#ifndef USEOPENMP
nthreads=1;
#else
#pragma omp parallel
{
if (omp_get_thread_num()==0) nthreads=omp_get_num_threads();
}
#endif
#ifdef USEOPENMP
for(i=0; i<opt.numsnapshots; i++) Fin>>&(buf[i*1000]);
#pragma omp parallel default(shared) \
private(i)
{
#pragma omp for reduction(+:tothalos)
for(i=0; i<opt.numsnapshots; i++)
{
if (opt.ioformat==DSUSSING) HaloTree[i].Halo=ReadHaloData(&buf[i*1000],HaloTree[i].numhalos);
else if (opt.ioformat==DCATALOG) HaloTree[i].Halo=ReadHaloGroupCatalogData(&buf[i*1000],HaloTree[i].numhalos, opt.nmpifiles, opt.ibinary,opt.ifield, opt.itypematch);
else if (opt.ioformat==DNIFTY) HaloTree[i].Halo=ReadNIFTYData(&buf[i*1000],HaloTree[i].numhalos, opt.idcorrectflag);
tothalos+=HaloTree[i].numhalos;
}
}
opt.TotalNumberofHalos=tothalos;
#else
for(i=0; i<opt.numsnapshots; i++)
{
Fin>>buf;
if (opt.ioformat==DSUSSING) HaloTree[i].Halo=ReadHaloData(buf,HaloTree[i].numhalos);
else if (opt.ioformat==DCATALOG) HaloTree[i].Halo=ReadHaloGroupCatalogData(buf,HaloTree[i].numhalos, opt.nmpifiles, opt.ibinary, opt.ifield, opt.itypematch);
else if (opt.ioformat==DNIFTY) HaloTree[i].Halo=ReadNIFTYData(buf,HaloTree[i].numhalos, opt.idcorrectflag);
opt.TotalNumberofHalos+=HaloTree[i].numhalos;
}
#endif
Fin.close();
return HaloTree;
}
void WriteHaloMergerTree(Options &opt, ProgenitorData **p, HaloTreeData *h) {
fstream Fout;
char fname[1000];
sprintf(fname,"%s",opt.outname);
cout<<"saving halo merger tree to "<<fname<<endl;
Fout.open(fname,ios::out);
Fout<<1<<endl;
Fout<<opt.description<<endl;
Fout<<opt.TotalNumberofHalos<<endl;
if (opt.outputformat==0) {
for (int i=opt.numsnapshots-1;i>0;i--) {
Fout<<i+opt.snapshotvaloffset<<"\t"<<h[i].numhalos<<endl;
for (int j=0;j<h[i].numhalos;j++) {
Fout<<h[i].Halo[j].haloID<<"\t"<<p[i][j].NumberofProgenitors<<endl;
for (int k=0;k<p[i][j].NumberofProgenitors;k++) {
Fout<<h[i-1].Halo[p[i][j].ProgenitorList[k]-1].haloID<<endl;
}
}
}
}
else {
for (int i=opt.numsnapshots-1;i>0;i--) {
Fout<<i+opt.snapshotvaloffset<<"\t"<<h[i].numhalos<<endl;
for (int j=0;j<h[i].numhalos;j++) {
Fout<<h[i].Halo[j].haloID<<"\t"<<p[i][j].NumberofProgenitors<<endl;
for (int k=0;k<p[i][j].NumberofProgenitors;k++) {
Fout<<h[i-1].Halo[p[i][j].ProgenitorList[k]-1].haloID<<" "<<p[i][j].Merit[k]<<endl;
}
}
}
}
///last file has no connections
for (int j=0;j<h[0].numhalos;j++) {
Fout<<h[0].Halo[j].haloID<<"\t"<<0<<endl;
}
Fout<<"END"<<endl;
Fout.close();
}
void WriteHaloGraph(Options &opt, ProgenitorData **p, DescendantData **d, HaloTreeData *h) {
fstream Fout;
char fname[1000];
sprintf(fname,"%s",opt.outname);
cout<<"saving halo merger tree to "<<fname<<endl;
Fout.open(fname,ios::out);
Fout<<1<<endl;
Fout<<opt.description<<endl;
Fout<<opt.TotalNumberofHalos<<endl;
if (opt.outputformat==0) {
for (int i=opt.numsnapshots-1;i>=0;i--) {
Fout<<i+opt.snapshotvaloffset<<"\t"<<h[i].numhalos<<endl;
for (int j=0;j<h[i].numhalos;j++) {
Fout<<h[i].Halo[j].haloID<<"\t"<<p[i][j].NumberofProgenitors<<"\t"<<d[i][j].NumberofDescendants<<endl;
for (int k=0;k<p[i][j].NumberofProgenitors;k++) {
Fout<<h[i-1].Halo[p[i][j].ProgenitorList[k]-1].haloID<<endl;
}
for (int k=0;k<d[i][j].NumberofDescendants;k++) {
Fout<<h[i+1].Halo[d[i][j].DescendantList[k]-1].haloID<<endl;
}
}
}
}
else {
for (int i=opt.numsnapshots-1;i>=0;i--) {
Fout<<i+opt.snapshotvaloffset<<"\t"<<h[i].numhalos<<endl;
for (int j=0;j<h[i].numhalos;j++) {
Fout<<h[i].Halo[j].haloID<<"\t"<<p[i][j].NumberofProgenitors<<"\t"<<d[i][j].NumberofDescendants<<endl;
for (int k=0;k<p[i][j].NumberofProgenitors;k++) {
Fout<<h[i-1].Halo[p[i][j].ProgenitorList[k]-1].haloID<<" "<<p[i][j].Merit[k]<<endl;
}
for (int k=0;k<d[i][j].NumberofDescendants;k++) {
Fout<<h[i+1].Halo[d[i][j].DescendantList[k]-1].haloID<<" "<<d[i][j].Merit[k]<<endl;
}
}
}
}
Fout<<"END"<<endl;
Fout.close();
}
void WriteCrossComp(Options &opt, ProgenitorData **p, HaloTreeData *h) {
fstream Fout;
char fname[1000];
sprintf(fname,"%s",opt.outname);
cout<<"saving halo merger tree to "<<fname<<endl;
Fout.open(fname,ios::out);
Fout<<opt.description<<endl;
Fout<<opt.TotalNumberofHalos<<endl;
if (opt.outputformat==0) {
for (int i=opt.numsnapshots-1;i>0;i--) {
Fout<<i<<"\t"<<h[i].numhalos<<endl;
for (int j=0;j<h[i].numhalos;j++) {
Fout<<h[i].Halo[j].haloID<<"\t"<<p[i][j].NumberofProgenitors<<endl;
for (int k=0;k<p[i][j].NumberofProgenitors;k++) {
Fout<<h[i-1].Halo[p[i][j].ProgenitorList[k]-1].haloID<<" "<<p[i][j].Merit[k]<<endl;
}
}
}
}
else if (opt.outputformat==1) {
for (int i=opt.numsnapshots-1;i>0;i--) {
Fout<<i<<"\t"<<h[i].numhalos<<endl;
for (int j=0;j<h[i].numhalos;j++) {
Fout<<h[i].Halo[j].haloID<<"\t"<<p[i][j].NumberofProgenitors<<endl;
for (int k=0;k<p[i][j].NumberofProgenitors;k++) {
Fout<<h[i-1].Halo[p[i][j].ProgenitorList[k]-1].haloID<<" "<<p[i][j].Merit[k]<<" "<<p[i][j].nsharedfrac[k]<<" ";
}
}
}
}
Fout<<"END"<<endl;
Fout.close();
}
<|endoftext|>
|
<commit_before>#ifndef ISOMON_MONEY_HPP
#define ISOMON_MONEY_HPP
#include "currency.hpp"
#include <limits>
#include <ostream>
#include <iomanip>
#include <locale>
#include <tr1/cmath>
namespace isomon {
class money
{
public:
money();
money(int64_t value, currency unit);
money(int64_t major_units, int64_t minor_units, currency unit);
static money pos_infinity(currency unit);
static money neg_infinity(currency unit);
static money epsilon(currency unit);
double value() const;
currency unit() const;
int64_t total_minors() const;
money & operator += (money rhs);
money & operator -= (money rhs);
money & operator *= (int rhs);
money operator - () const;
money operator + (money rhs) const;
money operator - (money rhs) const;
money operator * (int rhs) const;
bool operator == (money rhs) const { return _data == rhs._data; }
bool operator != (money rhs) const { return _data != rhs._data; }
friend money nextafter(money m);
private:
#ifndef DOXYGEN_SHOULD_SKIP_THIS
void init(int64_t minors, currency unit);
void fix_overflow();
#endif
int64_t _data;
};
inline bool isfinite(money m) { return std::isfinite(m.value()); }
// Construction from floating point numbers
template <class _Number>
money money_floor(_Number value, currency unit);
template <class _Number>
money money_ceil(_Number value, currency unit);
template <class _Number>
money money_trunc(_Number value, currency unit);
template <class _Number>
money round(_Number value, currency unit);
template <class _Number>
money rounde(_Number value, currency unit);
// More operators
inline money operator * (int i, money m) { return m * i; }
inline std::ostream & operator << (std::ostream & os, money m)
{
using namespace std;
const moneypunct<char> & mp = use_facet<moneypunct<char> >(os.getloc());
bool symbol_first = mp.pos_format().field[0] == moneypunct<char>::symbol;
if (symbol_first) { os << m.unit() << ' '; }
int num_digits = m.unit().num_digits();
streamsize saved_digits = os.precision(num_digits);
ios_base::fmtflags saved_flags = os.flags();
os << fixed << m.value();
os.flags(saved_flags);
os.precision(saved_digits);
if (!symbol_first) { os << ' ' << m.unit(); }
return os;
}
/// Number traits
template <class _Number>
struct number_traits {};
// number traits are pre-defined for type double
// define similar struct in isomon namespace for other float types
template<>
struct number_traits<double>
{
static bool isnan(double x) { return std::isnan(x); }
static bool isinf(double x) { return std::isinf(x); }
static int64_t floor(double x) { return std::floor(x); }
static int64_t ceil(double x) { return std::ceil(x); }
static int64_t trunc(double x) { return std::tr1::trunc(x); }
static int64_t roundhalfout(double x) { return std::tr1::round(x); }
// round half (towards) even, "banker's rounding"
static int64_t roundhalfeven(double x) {
int64_t halfout = roundhalfout(x);
if (halfout % 2) { // if odd, might need to adjust
// x is exactly halfway between two integers
// and was rounded OUT (away from zero) to an odd number
// we want to round IN (toward zero) to an even number instead
if (halfout - x == 0.5) return halfout - 1;
if (halfout - x == -0.5) return halfout + 1;
}
return halfout;
}
};
/////////////////////////////////////////////////////////////////////
namespace detail {
const int64_t CURRENCY_BITS = 0x3ffLL; // low 10 bits
const int64_t POS_INF_MINORS = (1LL << 53) - 1; // 2^53 - 1
const int64_t NEG_INF_MINORS = -(POS_INF_MINORS + 1); // - 2^53
template <class _Number>
money money_cast(_Number value, currency unit, int64_t (*rounder)(_Number) )
{
typedef number_traits<_Number> nt;
if (nt::isnan(value) || unit.num_minors() < 1) return money();
if (nt::isinf(value)) {
if (value > 0) return money::pos_infinity(unit);
else return money::neg_infinity(unit);
}
_Number minors = unit.num_minors() * value;
return money(0, rounder(minors), unit);
}
} // namespace isomon::detail
inline void money::init(int64_t minors, currency unit) {
if (unit.num_minors() < 1) {
_data = ISO_XXX;
} else {
_data = std::max( detail::NEG_INF_MINORS,
std::min(detail::POS_INF_MINORS, minors) );
_data <<= 10;
_data |= 0x3FF & unit.isonum();
}
}
inline money::money() : _data(ISO_XXX) {}
inline money::money(int64_t value, currency unit) {
init( value * unit.num_minors(), unit );
}
inline money::money(int64_t majors, int64_t minors, currency unit) {
init( majors * unit.num_minors() + minors, unit );
}
inline money money::pos_infinity(currency unit) {
money ret;
if (unit.num_minors() > 0) {
ret._data = unit.isonum() | (detail::POS_INF_MINORS << 10);
}
return ret;
}
inline money money::neg_infinity(currency unit) {
money ret;
if (unit.num_minors() > 0) {
ret._data = unit.isonum() | (detail::NEG_INF_MINORS << 10);
}
return ret;
}
inline money money::epsilon(currency unit) {
money ret;
if (unit.num_minors() > 0) {
ret._data = (1 << 10) | (0x3FF & unit.isonum());
}
return ret;
}
inline double money::value() const {
int64_t minors = _data >> 10;
if (minors == detail::NEG_INF_MINORS) {
return -std::numeric_limits<double>::infinity();
} else if (minors == detail::POS_INF_MINORS) {
return std::numeric_limits<double>::infinity();
}
return double(minors)/unit().num_minors();
}
inline currency money::unit() const {
return currency(0x3FF & _data);
}
inline int64_t money::total_minors() const {
return _data >> 10;
}
inline money & money::operator += (money rhs) {
int64_t diff_bits = (_data ^ rhs._data);
if (detail::CURRENCY_BITS & diff_bits) {
_data = ISO_XXX;
} else {
_data += ~detail::CURRENCY_BITS & rhs._data;
int64_t neg_if_sign_changed = (_data ^ rhs._data);
int64_t neg_if_overflow = neg_if_sign_changed & ~diff_bits;
if (neg_if_overflow < 0) fix_overflow();
}
return *this;
}
inline money & money::operator -= (money rhs) {
return *this += -rhs;
}
inline money & money::operator *= (int rhs) {
int64_t minors = rhs * this->total_minors();
//TODO detect all multiplication overflows
minors = std::max( detail::NEG_INF_MINORS,
std::min(detail::POS_INF_MINORS, minors) );
_data = (minors << 10) | (0x3FF & _data);
return *this;
}
inline money money::operator - () const {
return money(0, -this->total_minors(), this->unit());
}
inline money money::operator + (money rhs) const {
money ret(*this);
return ret += rhs;
}
inline money money::operator - (money rhs) const {
money ret(*this);
return ret -= rhs;
}
inline money money::operator * (int rhs) const {
money ret = *this;
return ret *= rhs;
}
inline void money::fix_overflow()
{
int64_t minors = (_data < 0 ? detail::POS_INF_MINORS
: detail::NEG_INF_MINORS);
_data &= detail::CURRENCY_BITS; // clear the minors bits
_data |= (minors << 10);
}
inline money nextafter(money m)
{
money ret;
ret._data = m._data + (1LL << 10);
int64_t neg_if_overflow = ~m._data & ret._data;
if (neg_if_overflow < 0) {
ret._data &= detail::CURRENCY_BITS;
ret._data |= (detail::POS_INF_MINORS << 10);
}
return ret;
}
template <class _Number>
money floor(_Number value, currency unit)
{
return detail::money_cast(value, unit, number_traits<_Number>::floor);
}
template <class _Number>
money ceil(_Number value, currency unit)
{
return detail::money_cast(value, unit, number_traits<_Number>::ceil);
}
template <class _Number>
money trunc(_Number value, currency unit)
{
return detail::money_cast(value, unit, number_traits<_Number>::trunc);
}
template <class _Number>
money round(_Number value, currency unit)
{
typedef number_traits<_Number> nt;
return detail::money_cast(value, unit, nt::roundhalfout);
}
template <class _Number>
money rounde(_Number value, currency unit)
{
typedef number_traits<_Number> nt;
return detail::money_cast(value, unit, nt::roundhalfeven);
}
} // namespace isomon
#endif
<commit_msg>remove money::epsilon function<commit_after>#ifndef ISOMON_MONEY_HPP
#define ISOMON_MONEY_HPP
#include "currency.hpp"
#include <limits>
#include <ostream>
#include <iomanip>
#include <locale>
#include <tr1/cmath>
namespace isomon {
class money
{
public:
money();
money(int64_t value, currency unit);
money(int64_t major_units, int64_t minor_units, currency unit);
static money pos_infinity(currency unit);
static money neg_infinity(currency unit);
double value() const;
currency unit() const;
int64_t total_minors() const;
money & operator += (money rhs);
money & operator -= (money rhs);
money & operator *= (int rhs);
money operator - () const;
money operator + (money rhs) const;
money operator - (money rhs) const;
money operator * (int rhs) const;
bool operator == (money rhs) const { return _data == rhs._data; }
bool operator != (money rhs) const { return _data != rhs._data; }
friend money nextafter(money m);
private:
#ifndef DOXYGEN_SHOULD_SKIP_THIS
void init(int64_t minors, currency unit);
void fix_overflow();
#endif
int64_t _data;
};
inline bool isfinite(money m) { return std::isfinite(m.value()); }
// Construction from floating point numbers
template <class _Number>
money money_floor(_Number value, currency unit);
template <class _Number>
money money_ceil(_Number value, currency unit);
template <class _Number>
money money_trunc(_Number value, currency unit);
template <class _Number>
money round(_Number value, currency unit);
template <class _Number>
money rounde(_Number value, currency unit);
// More operators
inline money operator * (int i, money m) { return m * i; }
inline std::ostream & operator << (std::ostream & os, money m)
{
using namespace std;
const moneypunct<char> & mp = use_facet<moneypunct<char> >(os.getloc());
bool symbol_first = mp.pos_format().field[0] == moneypunct<char>::symbol;
if (symbol_first) { os << m.unit() << ' '; }
int num_digits = m.unit().num_digits();
streamsize saved_digits = os.precision(num_digits);
ios_base::fmtflags saved_flags = os.flags();
os << fixed << m.value();
os.flags(saved_flags);
os.precision(saved_digits);
if (!symbol_first) { os << ' ' << m.unit(); }
return os;
}
/// Number traits
template <class _Number>
struct number_traits {};
// number traits are pre-defined for type double
// define similar struct in isomon namespace for other float types
template<>
struct number_traits<double>
{
static bool isnan(double x) { return std::isnan(x); }
static bool isinf(double x) { return std::isinf(x); }
static int64_t floor(double x) { return std::floor(x); }
static int64_t ceil(double x) { return std::ceil(x); }
static int64_t trunc(double x) { return std::tr1::trunc(x); }
static int64_t roundhalfout(double x) { return std::tr1::round(x); }
// round half (towards) even, "banker's rounding"
static int64_t roundhalfeven(double x) {
int64_t halfout = roundhalfout(x);
if (halfout % 2) { // if odd, might need to adjust
// x is exactly halfway between two integers
// and was rounded OUT (away from zero) to an odd number
// we want to round IN (toward zero) to an even number instead
if (halfout - x == 0.5) return halfout - 1;
if (halfout - x == -0.5) return halfout + 1;
}
return halfout;
}
};
/////////////////////////////////////////////////////////////////////
namespace detail {
const int64_t CURRENCY_BITS = 0x3ffLL; // low 10 bits
const int64_t POS_INF_MINORS = (1LL << 53) - 1; // 2^53 - 1
const int64_t NEG_INF_MINORS = -(POS_INF_MINORS + 1); // - 2^53
template <class _Number>
money money_cast(_Number value, currency unit, int64_t (*rounder)(_Number) )
{
typedef number_traits<_Number> nt;
if (nt::isnan(value) || unit.num_minors() < 1) return money();
if (nt::isinf(value)) {
if (value > 0) return money::pos_infinity(unit);
else return money::neg_infinity(unit);
}
_Number minors = unit.num_minors() * value;
return money(0, rounder(minors), unit);
}
} // namespace isomon::detail
inline void money::init(int64_t minors, currency unit) {
if (unit.num_minors() < 1) {
_data = ISO_XXX;
} else {
_data = std::max( detail::NEG_INF_MINORS,
std::min(detail::POS_INF_MINORS, minors) );
_data <<= 10;
_data |= 0x3FF & unit.isonum();
}
}
inline money::money() : _data(ISO_XXX) {}
inline money::money(int64_t value, currency unit) {
init( value * unit.num_minors(), unit );
}
inline money::money(int64_t majors, int64_t minors, currency unit) {
init( majors * unit.num_minors() + minors, unit );
}
inline money money::pos_infinity(currency unit) {
money ret;
if (unit.num_minors() > 0) {
ret._data = unit.isonum() | (detail::POS_INF_MINORS << 10);
}
return ret;
}
inline money money::neg_infinity(currency unit) {
money ret;
if (unit.num_minors() > 0) {
ret._data = unit.isonum() | (detail::NEG_INF_MINORS << 10);
}
return ret;
}
inline double money::value() const {
int64_t minors = _data >> 10;
if (minors == detail::NEG_INF_MINORS) {
return -std::numeric_limits<double>::infinity();
} else if (minors == detail::POS_INF_MINORS) {
return std::numeric_limits<double>::infinity();
}
return double(minors)/unit().num_minors();
}
inline currency money::unit() const {
return currency(0x3FF & _data);
}
inline int64_t money::total_minors() const {
return _data >> 10;
}
inline money & money::operator += (money rhs) {
int64_t diff_bits = (_data ^ rhs._data);
if (detail::CURRENCY_BITS & diff_bits) {
_data = ISO_XXX;
} else {
_data += ~detail::CURRENCY_BITS & rhs._data;
int64_t neg_if_sign_changed = (_data ^ rhs._data);
int64_t neg_if_overflow = neg_if_sign_changed & ~diff_bits;
if (neg_if_overflow < 0) fix_overflow();
}
return *this;
}
inline money & money::operator -= (money rhs) {
return *this += -rhs;
}
inline money & money::operator *= (int rhs) {
int64_t minors = rhs * this->total_minors();
//TODO detect all multiplication overflows
minors = std::max( detail::NEG_INF_MINORS,
std::min(detail::POS_INF_MINORS, minors) );
_data = (minors << 10) | (0x3FF & _data);
return *this;
}
inline money money::operator - () const {
return money(0, -this->total_minors(), this->unit());
}
inline money money::operator + (money rhs) const {
money ret(*this);
return ret += rhs;
}
inline money money::operator - (money rhs) const {
money ret(*this);
return ret -= rhs;
}
inline money money::operator * (int rhs) const {
money ret = *this;
return ret *= rhs;
}
inline void money::fix_overflow()
{
int64_t minors = (_data < 0 ? detail::POS_INF_MINORS
: detail::NEG_INF_MINORS);
_data &= detail::CURRENCY_BITS; // clear the minors bits
_data |= (minors << 10);
}
inline money nextafter(money m)
{
money ret;
ret._data = m._data + (1LL << 10);
int64_t neg_if_overflow = ~m._data & ret._data;
if (neg_if_overflow < 0) {
ret._data &= detail::CURRENCY_BITS;
ret._data |= (detail::POS_INF_MINORS << 10);
}
return ret;
}
template <class _Number>
money floor(_Number value, currency unit)
{
return detail::money_cast(value, unit, number_traits<_Number>::floor);
}
template <class _Number>
money ceil(_Number value, currency unit)
{
return detail::money_cast(value, unit, number_traits<_Number>::ceil);
}
template <class _Number>
money trunc(_Number value, currency unit)
{
return detail::money_cast(value, unit, number_traits<_Number>::trunc);
}
template <class _Number>
money round(_Number value, currency unit)
{
typedef number_traits<_Number> nt;
return detail::money_cast(value, unit, nt::roundhalfout);
}
template <class _Number>
money rounde(_Number value, currency unit)
{
typedef number_traits<_Number> nt;
return detail::money_cast(value, unit, nt::roundhalfeven);
}
} // namespace isomon
#endif
<|endoftext|>
|
<commit_before>
#include "CMainMenuState.h"
#include <ionGUI.h>
#include "CMainState.h"
#include "ColorMappers.h"
#include "CDataLoadingThread.h"
#include "CGlyphSceneObject.h"
#include "CSite.h"
#include "SciDataParser.h"
CMainMenuState::CMainMenuState()
{}
void CMainMenuState::Begin()
{
Context->GUIContext->SetupMenuState();
std::cout << "Menu State begin." << std::endl;
}
void CMainMenuState::End()
{
Context->GUIContext->Clear();
std::cout << "Menu State end." << std::endl;
}
void CMainMenuState::Update(f32 const Elapsed)
{
printOpenGLErrors();
std::chrono::milliseconds Milliseconds(50);
std::this_thread::sleep_for(Milliseconds);
Thread.Sync();
Context->GUIContext->Draw(Elapsed, true);
CApplication::Get().GetWindow().SwapBuffers();
static int Counter = 0;
if (! Counter--)
{
Context->CurrentSite->GetCurrentDataSet()->Traits.PositionXField = "Longitude";
Context->CurrentSite->GetCurrentDataSet()->Traits.PositionYField = "DFS Depth (m)";
Context->CurrentSite->GetCurrentDataSet()->Traits.PositionZField = "Latitude";
CreateDataSet();
LoadData("HopavagenBay1.dat");
}
}
void CMainMenuState::OnEvent(SWindowResizedEvent & Event)
{
Context->GUIContext->GetCanvas()->SetSize(Event.Size.X, Event.Size.Y);
Context->GUIContext->GetCanvas()->Invalidate();
Context->GUIContext->GetCanvas()->InvalidateChildren(true);
}
void CMainMenuState::LoadData(std::string const & FileName)
{
//DataSetName = FileName;
//std::stringstream s;
//s << "Datasets/";
//s << FileName;
Thread.Context = Context;
Thread.LoadingWidget = new CGUIProgressBarWidget(Context->GUIContext, "Loading data and initializing scene elements");
Thread.LoadingWidget->BeginProgress();
Thread.Run(/*s.str()*/);
}
void CMainMenuState::CreateDataSet()
{
//SciDataParserCSV Parser1;
//CSpectrumColorMapper ColorMapper("Chla Conc");
//Parser1.DataSet = Context->CurrentSite->GetCurrentDataSet();
//Parser1.FieldDelim = Parser1.ValueDelim = ';';
////Parser1.Load("Sites/Catalina/20131006_130020_catalina_shallow_10_IVER2-132.log");
////Parser1.Load("Sites/Catalina/20131005_191049_catalina_10_IVER2-132.log"); // BAD!
//Parser1.Load("Sites/Catalina/20131006_120459_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_121530_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_122601_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_124220_catalina_10_IVER2-132.log");
////Parser1.Load("Sites/Catalina/20131006_130020_catalina_shallow_10_IVER2-132.log");
////Parser1.Load("Sites/Catalina/20131006_142755_catalina_undulate_10_IVER2-132.log");
////Parser1.Load("Sites/Catalina/20131006_143331_catalina_undulate_10_IVER2-132.log");
////Parser1.Load("Sites/Catalina/20131006_221316_catalina_10_IVER2-132.log"); // BAD!
//Parser1.Load("Sites/Catalina/20131006_221639_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_222457_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_222608_catalina_10_IVER2-132.log");
////Parser1.Load("Sites/Catalina/20131006_222654_catalina_10_IVER2-132.log"); // Out of range
////Parser1.Load("Sites/Catalina/20131006_223043_catalina_10_IVER2-132.log"); // Out of range
//Parser1.Load("Sites/Catalina/20131007_100031_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131005_191049_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_120459_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_121530_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_122601_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_124220_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_130020_catalina_shallow_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_142755_catalina_undulate_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_143331_catalina_undulate_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_221316_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_221639_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_222457_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_222608_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_222654_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_223043_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131007_100031_catalina_10_IVER2-132.log");
//Context->DataManager->createGridDataFromRawValuesRBFI(SRange<f64>::Full, 15.0, "Chla Conc");
//Context->DataManager->createVolumeFromGridValues(& ColorMapper);
//Context->DataManager->writeToFile("Datasets/DenmarkNewMission1.dat");
/*
SciDataParserSimpleTXT * Parser1 = new SciDataParserSimpleTXT();
Parser1->Manager = Context->DataManager;
Parser1->load("ForZoe.txt");
SciDataParserGrid1 * Parser2 = new SciDataParserGrid1();
Parser2->Manager = Context->DataManager;
Parser2->load("oxyMaps.mat");
COxygenColorMapper o;
Context->DataManager->createVolumeFromGridValues(& o);
Context->DataManager->writeToFile("Datasets/Catalina1.dat");*/
SciDataParserSimpleTXT * Parser1 = new SciDataParserSimpleTXT();
Parser1->DataSet = Context->CurrentSite->GetCurrentDataSet();
Parser1->load("ForZoe.txt");
//SciDataParserGrid1 * Parser2 = new SciDataParserGrid1();
//Parser2->DataSet = Context->CurrentSite->GetCurrentDataSet();
//Parser2->load("oxyMaps.mat");
//COxygenColorMapper o;
//Context->CurrentSite->GetCurrentDataSet()->createVolumeFromGridValues(& o);
//Context->DataManager->writeToFile("Datasets/HopavagenBay1.dat");
}
<commit_msg>+ Disabled data load to improve startup time<commit_after>
#include "CMainMenuState.h"
#include <ionGUI.h>
#include "CMainState.h"
#include "ColorMappers.h"
#include "CDataLoadingThread.h"
#include "CGlyphSceneObject.h"
#include "CSite.h"
#include "SciDataParser.h"
CMainMenuState::CMainMenuState()
{}
void CMainMenuState::Begin()
{
Context->GUIContext->SetupMenuState();
std::cout << "Menu State begin." << std::endl;
}
void CMainMenuState::End()
{
Context->GUIContext->Clear();
std::cout << "Menu State end." << std::endl;
}
void CMainMenuState::Update(f32 const Elapsed)
{
printOpenGLErrors();
std::chrono::milliseconds Milliseconds(50);
std::this_thread::sleep_for(Milliseconds);
Thread.Sync();
Context->GUIContext->Draw(Elapsed, true);
CApplication::Get().GetWindow().SwapBuffers();
static int Counter = 0;
if (! Counter--)
{
Context->CurrentSite->GetCurrentDataSet()->Traits.PositionXField = "Longitude";
Context->CurrentSite->GetCurrentDataSet()->Traits.PositionYField = "DFS Depth (m)";
Context->CurrentSite->GetCurrentDataSet()->Traits.PositionZField = "Latitude";
CreateDataSet();
LoadData("HopavagenBay1.dat");
}
}
void CMainMenuState::OnEvent(SWindowResizedEvent & Event)
{
Context->GUIContext->GetCanvas()->SetSize(Event.Size.X, Event.Size.Y);
Context->GUIContext->GetCanvas()->Invalidate();
Context->GUIContext->GetCanvas()->InvalidateChildren(true);
}
void CMainMenuState::LoadData(std::string const & FileName)
{
//DataSetName = FileName;
//std::stringstream s;
//s << "Datasets/";
//s << FileName;
Thread.Context = Context;
Thread.LoadingWidget = new CGUIProgressBarWidget(Context->GUIContext, "Loading data and initializing scene elements");
Thread.LoadingWidget->BeginProgress();
Thread.Run(/*s.str()*/);
}
void CMainMenuState::CreateDataSet()
{
//SciDataParserCSV Parser1;
//CSpectrumColorMapper ColorMapper("Chla Conc");
//Parser1.DataSet = Context->CurrentSite->GetCurrentDataSet();
//Parser1.FieldDelim = Parser1.ValueDelim = ';';
////Parser1.Load("Sites/Catalina/20131006_130020_catalina_shallow_10_IVER2-132.log");
////Parser1.Load("Sites/Catalina/20131005_191049_catalina_10_IVER2-132.log"); // BAD!
//Parser1.Load("Sites/Catalina/20131006_120459_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_121530_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_122601_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_124220_catalina_10_IVER2-132.log");
////Parser1.Load("Sites/Catalina/20131006_130020_catalina_shallow_10_IVER2-132.log");
////Parser1.Load("Sites/Catalina/20131006_142755_catalina_undulate_10_IVER2-132.log");
////Parser1.Load("Sites/Catalina/20131006_143331_catalina_undulate_10_IVER2-132.log");
////Parser1.Load("Sites/Catalina/20131006_221316_catalina_10_IVER2-132.log"); // BAD!
//Parser1.Load("Sites/Catalina/20131006_221639_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_222457_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_222608_catalina_10_IVER2-132.log");
////Parser1.Load("Sites/Catalina/20131006_222654_catalina_10_IVER2-132.log"); // Out of range
////Parser1.Load("Sites/Catalina/20131006_223043_catalina_10_IVER2-132.log"); // Out of range
//Parser1.Load("Sites/Catalina/20131007_100031_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131005_191049_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_120459_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_121530_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_122601_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_124220_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_130020_catalina_shallow_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_142755_catalina_undulate_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_143331_catalina_undulate_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_221316_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_221639_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_222457_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_222608_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_222654_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131006_223043_catalina_10_IVER2-132.log");
//Parser1.Load("Sites/Catalina/20131007_100031_catalina_10_IVER2-132.log");
//Context->DataManager->createGridDataFromRawValuesRBFI(SRange<f64>::Full, 15.0, "Chla Conc");
//Context->DataManager->createVolumeFromGridValues(& ColorMapper);
//Context->DataManager->writeToFile("Datasets/DenmarkNewMission1.dat");
/*
SciDataParserSimpleTXT * Parser1 = new SciDataParserSimpleTXT();
Parser1->Manager = Context->DataManager;
Parser1->load("ForZoe.txt");
SciDataParserGrid1 * Parser2 = new SciDataParserGrid1();
Parser2->Manager = Context->DataManager;
Parser2->load("oxyMaps.mat");
COxygenColorMapper o;
Context->DataManager->createVolumeFromGridValues(& o);
Context->DataManager->writeToFile("Datasets/Catalina1.dat");*/
//SciDataParserSimpleTXT * Parser1 = new SciDataParserSimpleTXT();
//Parser1->DataSet = Context->CurrentSite->GetCurrentDataSet();
//Parser1->load("ForZoe.txt");
//SciDataParserGrid1 * Parser2 = new SciDataParserGrid1();
//Parser2->DataSet = Context->CurrentSite->GetCurrentDataSet();
//Parser2->load("oxyMaps.mat");
//COxygenColorMapper o;
//Context->CurrentSite->GetCurrentDataSet()->createVolumeFromGridValues(& o);
//Context->DataManager->writeToFile("Datasets/HopavagenBay1.dat");
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright 2018 The Apollo 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 <getopt.h>
#include <stddef.h>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
#include "cybertron/common/file.h"
#include "cybertron/common/time_conversion.h"
#include "cybertron/init.h"
#include "cybertron/tools/cyber_recorder/info.h"
#include "cybertron/tools/cyber_recorder/player.h"
#include "cybertron/tools/cyber_recorder/recorder.h"
#include "cybertron/tools/cyber_recorder/recoverer.h"
#include "cybertron/tools/cyber_recorder/spliter.h"
using apollo::cybertron::record::Info;
using apollo::cybertron::record::Recorder;
using apollo::cybertron::record::Player;
using apollo::cybertron::record::Spliter;
using apollo::cybertron::record::Recoverer;
using apollo::cybertron::common::GetFileName;
using apollo::cybertron::common::StringToUnixSeconds;
using apollo::cybertron::common::UnixSecondsToString;
const char INFO_OPTIONS[] = "f:h";
const char RECORD_OPTIONS[] = "o:ac:h";
const char PLAY_OPTIONS[] = "f:c:lr:b:e:s:d:h";
const char SPLIT_OPTIONS[] = "f:o:c:k:b:e:h";
const char RECOVER_OPTIONS[] = "f:o:h";
void DisplayUsage(const std::string& binary);
void DisplayUsage(const std::string& binary, const std::string& command);
void DisplayUsage(const std::string& binary, const std::string& command,
const std::string& options);
void DisplayUsage(const std::string& binary) {
std::cout << "usage: " << binary << " <command> [<args>]\n"
<< "The " << binary << " commands are:\n"
<< "\tinfo\tShow infomation of an exist record.\n"
<< "\tplay\tPlay an exist record.\n"
<< "\trecord\tRecord same topic.\n"
<< "\tsplit\tSplit an exist record.\n"
<< "\trecover\tRecover an exist record.\n"
<< std::endl;
}
void DisplayUsage(const std::string& binary, const std::string& command) {
std::cout << "usage: " << binary << " " << command << " [options]"
<< std::endl;
if (command == "info") {
DisplayUsage(binary, command, INFO_OPTIONS);
} else if (command == "record") {
DisplayUsage(binary, command, RECORD_OPTIONS);
} else if (command == "play") {
DisplayUsage(binary, command, PLAY_OPTIONS);
} else if (command == "split") {
DisplayUsage(binary, command, SPLIT_OPTIONS);
} else if (command == "recover") {
DisplayUsage(binary, command, RECOVER_OPTIONS);
} else {
std::cout << "Unknown command: " << command << std::endl;
DisplayUsage(binary);
}
}
void DisplayUsage(const std::string& binary, const std::string& command,
const std::string& options) {
for (char option : options) {
switch (option) {
case 'f':
std::cout << "\t-f, --file <file>\t\t\tinput record file" << std::endl;
break;
case 'o':
std::cout << "\t-o, --output <file>\t\t\toutput record file"
<< std::endl;
break;
case 'a':
std::cout << "\t-a, --all\t\t\t\t" << command << " all" << std::endl;
break;
case 'c':
std::cout << "\t-c, --white-channel <name>\t\t\tonly " << command
<< " the specified channel" << std::endl;
break;
case 'k':
std::cout << "\t-k, --black-channel <name>\t\t\tnot " << command
<< " the specified channel" << std::endl;
break;
case 'l':
std::cout << "\t-l, --loop\t\t\t\tloop " << command << std::endl;
break;
case 'r':
std::cout << "\t-r, --rate <1.0>\t\t\tmultiply the " << command
<< " rate by FACTOR" << std::endl;
break;
case 'b':
std::cout << "\t-b, --begin <2018-07-01 00:00:00>\t" << command
<< " the record begin at" << std::endl;
break;
case 'e':
std::cout << "\t-e, --end <2018-07-01 00:01:00>\t\t" << command
<< " the record end at" << std::endl;
break;
case 's':
std::cout << "\t-s, --start <seconds>\t\t\t" << command
<< " started at n seconds" << std::endl;
break;
case 'd':
std::cout << "\t-d, --delay <seconds>\t\t\t" << command
<< " delayed n seconds" << std::endl;
break;
case 'h':
std::cout << "\t-h, --help\t\t\t\tshow help message" << std::endl;
break;
case ':':
break;
default:
std::cout << "unknown option: -" << option;
break;
}
}
}
int main(int argc, char** argv) {
std::string binary = GetFileName(std::string(argv[0]));
if (argc < 2) {
DisplayUsage(binary);
return -1;
}
const std::string command(argv[1]);
int long_index = 0;
const std::string short_opts = "f:c:k:o:alr:b:e:s:d:h";
static const struct option long_opts[] = {
{"files", required_argument, nullptr, 'f'},
{"white-channel", required_argument, nullptr, 'c'},
{"black-channel", required_argument, nullptr, 'k'},
{"output", required_argument, nullptr, 'o'},
{"all", no_argument, nullptr, 'a'},
{"loop", no_argument, nullptr, 'l'},
{"rate", required_argument, nullptr, 'r'},
{"begin", required_argument, nullptr, 'b'},
{"end", required_argument, nullptr, 'e'},
{"start", required_argument, nullptr, 's'},
{"delay", required_argument, nullptr, 'd'},
{"help", no_argument, nullptr, 'h'}};
std::vector<std::string> opt_file_vec;
std::vector<std::string> opt_output_vec;
std::vector<std::string> opt_white_channels;
std::vector<std::string> opt_black_channels;
bool opt_all = false;
bool opt_loop = false;
float opt_rate = 1.0f;
uint64_t opt_begin = 0;
uint64_t opt_end = UINT64_MAX;
uint64_t opt_start = 0;
uint64_t opt_delay = 0;
do {
int opt =
getopt_long(argc, argv, short_opts.c_str(), long_opts, &long_index);
if (opt == -1) {
break;
}
switch (opt) {
case 'f':
opt_file_vec.push_back(std::string(optarg));
break;
case 'c':
optind--;
while (optind < argc) {
if (*argv[optind] != '-') {
opt_white_channels.emplace_back(argv[optind]);
optind++;
} else {
optind--;
break;
}
}
break;
case 'k':
optind--;
while (optind < argc) {
if (*argv[optind] != '-') {
opt_black_channels.emplace_back(argv[optind]);
optind++;
} else {
optind--;
break;
}
}
break;
case 'o':
opt_output_vec.push_back(std::string(optarg));
break;
case 'a':
opt_all = true;
break;
case 'l':
opt_loop = true;
break;
case 'r':
try {
opt_rate = std::stof(optarg);
} catch (const std::invalid_argument& ia) {
std::cout << "Invalid argument: -r/--rate " << std::string(optarg)
<< std::endl;
return -1;
} catch (const std::out_of_range& e) {
std::cout << "Argument is out of range: -r/--rate "
<< std::string(optarg) << std::endl;
return -1;
}
break;
case 'b':
opt_begin = StringToUnixSeconds(std::string(optarg)) * 1e9;
break;
case 'e':
opt_end = StringToUnixSeconds(std::string(optarg)) * 1e9;
break;
case 's':
try {
opt_start = std::stoi(optarg);
} catch (const std::invalid_argument& ia) {
std::cout << "Invalid argument: -s/--start " << std::string(optarg)
<< std::endl;
return -1;
} catch (const std::out_of_range& e) {
std::cout << "Argument is out of range: -s/--start "
<< std::string(optarg) << std::endl;
return -1;
}
break;
case 'd':
try {
opt_delay = std::stoi(optarg);
} catch (std::invalid_argument& ia) {
std::cout << "Invalid argument: -d/--delay " << std::string(optarg)
<< std::endl;
return -1;
} catch (const std::out_of_range& e) {
std::cout << "Argument is out of range: -d/--delay "
<< std::string(optarg) << std::endl;
return -1;
}
break;
case 'h':
DisplayUsage(binary, command);
return 0;
default:
break;
}
} while (true);
// cyber_recorder info
if (command == "info") {
if (opt_file_vec.empty()) {
std::cout << "MUST specify file option (-f)." << std::endl;
return -1;
}
::apollo::cybertron::Init(argv[0]);
Info info;
bool info_result = true;
for (auto& opt_file : opt_file_vec) {
info_result = info_result && info.Display(opt_file) ? true : false;
}
::apollo::cybertron::Shutdown();
return info_result ? 0 : -1;
} else if (command == "recover") {
if (opt_file_vec.empty()) {
std::cout << "MUST specify file option (-f)." << std::endl;
return -1;
}
if (opt_file_vec.size() > 1 || opt_output_vec.size() > 1) {
std::cout << "TOO many input/output file option (-f/-o)." << std::endl;
return -1;
}
if (opt_output_vec.empty()) {
std::string default_output_file = opt_file_vec[0] + ".recover";
opt_output_vec.push_back(default_output_file);
}
::apollo::cybertron::Init(argv[0]);
Recoverer recoverer(opt_file_vec[0], opt_output_vec[0]);
bool recover_result = recoverer.Proc();
::apollo::cybertron::Shutdown();
return recover_result ? 0 : -1;
}
if (command == "play") {
if (opt_file_vec.empty()) {
std::cout << "MUST specify file option (-f)." << std::endl;
return -1;
}
::apollo::cybertron::Init(argv[0]);
// TODO @baownayu order input record file
bool play_result = true;
for (size_t i = 0; i < opt_file_vec.size(); ++i) {
Player player(opt_file_vec[0], opt_white_channels.empty(),
opt_white_channels, opt_loop, opt_rate, opt_begin, opt_end,
opt_start, opt_delay);
play_result = play_result && player.Init() ? true : false;
play_result = play_result && player.Start() ? true : false;
}
::apollo::cybertron::Shutdown();
return play_result ? 0 : -1;
} else if (command == "record") {
if (opt_white_channels.empty() && !opt_all) {
std::cout
<< "MUST specify channels option (-c) or all channels option (-a)."
<< std::endl;
return -1;
}
if (opt_output_vec.size() > 1) {
std::cout << "TOO many ouput file option (-o)." << std::endl;
return -1;
}
if (opt_output_vec.empty()) {
std::string default_output_file =
UnixSecondsToString(time(nullptr), "%Y%m%d%H%M%S") + ".record";
opt_output_vec.push_back(default_output_file);
}
bool record_result = true;
::apollo::cybertron::Init(argv[0]);
auto recorder = std::make_shared<Recorder>(opt_output_vec[0], opt_all,
opt_white_channels);
record_result = record_result && recorder->Start() ? true : false;
if (record_result) {
while (::apollo::cybertron::OK()) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
record_result = record_result && recorder->Stop() ? true : false;
}
::apollo::cybertron::Shutdown();
return record_result ? 0 : -1;
} else if (command == "split") {
if (opt_file_vec.empty()) {
std::cout << "MUST specify file option (-f)." << std::endl;
return -1;
}
if (opt_file_vec.size() > 1 || opt_output_vec.size() > 1) {
std::cout << "TOO many input/output file option (-f/-o)." << std::endl;
return -1;
}
if (opt_output_vec.empty()) {
std::string default_output_file = opt_file_vec[0] + ".split";
opt_output_vec.push_back(default_output_file);
}
::apollo::cybertron::Init(argv[0]);
Spliter spliter(opt_file_vec[0], opt_output_vec[0], opt_white_channels,
opt_black_channels, opt_begin, opt_end);
bool split_result = spliter.Proc();
::apollo::cybertron::Shutdown();
return split_result ? 0 : -1;
}
// unknown command
DisplayUsage(binary, command);
return -1;
}
<commit_msg>framework: support "-f file1 file2 ..." in player.<commit_after>/******************************************************************************
* Copyright 2018 The Apollo 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 <getopt.h>
#include <stddef.h>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
#include "cybertron/common/file.h"
#include "cybertron/common/time_conversion.h"
#include "cybertron/init.h"
#include "cybertron/tools/cyber_recorder/info.h"
#include "cybertron/tools/cyber_recorder/player.h"
#include "cybertron/tools/cyber_recorder/recorder.h"
#include "cybertron/tools/cyber_recorder/recoverer.h"
#include "cybertron/tools/cyber_recorder/spliter.h"
using apollo::cybertron::record::Info;
using apollo::cybertron::record::Recorder;
using apollo::cybertron::record::Player;
using apollo::cybertron::record::Spliter;
using apollo::cybertron::record::Recoverer;
using apollo::cybertron::common::GetFileName;
using apollo::cybertron::common::StringToUnixSeconds;
using apollo::cybertron::common::UnixSecondsToString;
const char INFO_OPTIONS[] = "f:h";
const char RECORD_OPTIONS[] = "o:ac:h";
const char PLAY_OPTIONS[] = "f:c:lr:b:e:s:d:h";
const char SPLIT_OPTIONS[] = "f:o:c:k:b:e:h";
const char RECOVER_OPTIONS[] = "f:o:h";
void DisplayUsage(const std::string& binary);
void DisplayUsage(const std::string& binary, const std::string& command);
void DisplayUsage(const std::string& binary, const std::string& command,
const std::string& options);
void DisplayUsage(const std::string& binary) {
std::cout << "usage: " << binary << " <command> [<args>]\n"
<< "The " << binary << " commands are:\n"
<< "\tinfo\tShow infomation of an exist record.\n"
<< "\tplay\tPlay an exist record.\n"
<< "\trecord\tRecord same topic.\n"
<< "\tsplit\tSplit an exist record.\n"
<< "\trecover\tRecover an exist record.\n"
<< std::endl;
}
void DisplayUsage(const std::string& binary, const std::string& command) {
std::cout << "usage: " << binary << " " << command << " [options]"
<< std::endl;
if (command == "info") {
DisplayUsage(binary, command, INFO_OPTIONS);
} else if (command == "record") {
DisplayUsage(binary, command, RECORD_OPTIONS);
} else if (command == "play") {
DisplayUsage(binary, command, PLAY_OPTIONS);
} else if (command == "split") {
DisplayUsage(binary, command, SPLIT_OPTIONS);
} else if (command == "recover") {
DisplayUsage(binary, command, RECOVER_OPTIONS);
} else {
std::cout << "Unknown command: " << command << std::endl;
DisplayUsage(binary);
}
}
void DisplayUsage(const std::string& binary, const std::string& command,
const std::string& options) {
for (char option : options) {
switch (option) {
case 'f':
std::cout << "\t-f, --file <file>\t\t\tinput record file" << std::endl;
break;
case 'o':
std::cout << "\t-o, --output <file>\t\t\toutput record file"
<< std::endl;
break;
case 'a':
std::cout << "\t-a, --all\t\t\t\t" << command << " all" << std::endl;
break;
case 'c':
std::cout << "\t-c, --white-channel <name>\t\t\tonly " << command
<< " the specified channel" << std::endl;
break;
case 'k':
std::cout << "\t-k, --black-channel <name>\t\t\tnot " << command
<< " the specified channel" << std::endl;
break;
case 'l':
std::cout << "\t-l, --loop\t\t\t\tloop " << command << std::endl;
break;
case 'r':
std::cout << "\t-r, --rate <1.0>\t\t\tmultiply the " << command
<< " rate by FACTOR" << std::endl;
break;
case 'b':
std::cout << "\t-b, --begin <2018-07-01 00:00:00>\t" << command
<< " the record begin at" << std::endl;
break;
case 'e':
std::cout << "\t-e, --end <2018-07-01 00:01:00>\t\t" << command
<< " the record end at" << std::endl;
break;
case 's':
std::cout << "\t-s, --start <seconds>\t\t\t" << command
<< " started at n seconds" << std::endl;
break;
case 'd':
std::cout << "\t-d, --delay <seconds>\t\t\t" << command
<< " delayed n seconds" << std::endl;
break;
case 'h':
std::cout << "\t-h, --help\t\t\t\tshow help message" << std::endl;
break;
case ':':
break;
default:
std::cout << "unknown option: -" << option;
break;
}
}
}
int main(int argc, char** argv) {
std::string binary = GetFileName(std::string(argv[0]));
if (argc < 2) {
DisplayUsage(binary);
return -1;
}
const std::string command(argv[1]);
int long_index = 0;
const std::string short_opts = "f:c:k:o:alr:b:e:s:d:h";
static const struct option long_opts[] = {
{"files", required_argument, nullptr, 'f'},
{"white-channel", required_argument, nullptr, 'c'},
{"black-channel", required_argument, nullptr, 'k'},
{"output", required_argument, nullptr, 'o'},
{"all", no_argument, nullptr, 'a'},
{"loop", no_argument, nullptr, 'l'},
{"rate", required_argument, nullptr, 'r'},
{"begin", required_argument, nullptr, 'b'},
{"end", required_argument, nullptr, 'e'},
{"start", required_argument, nullptr, 's'},
{"delay", required_argument, nullptr, 'd'},
{"help", no_argument, nullptr, 'h'}};
std::vector<std::string> opt_file_vec;
std::vector<std::string> opt_output_vec;
std::vector<std::string> opt_white_channels;
std::vector<std::string> opt_black_channels;
bool opt_all = false;
bool opt_loop = false;
float opt_rate = 1.0f;
uint64_t opt_begin = 0;
uint64_t opt_end = UINT64_MAX;
uint64_t opt_start = 0;
uint64_t opt_delay = 0;
do {
int opt =
getopt_long(argc, argv, short_opts.c_str(), long_opts, &long_index);
if (opt == -1) {
break;
}
switch (opt) {
case 'f':
optind--;
while (optind < argc) {
if (*argv[optind] != '-') {
opt_file_vec.emplace_back(argv[optind]);
optind++;
} else {
optind--;
break;
}
}
break;
case 'c':
optind--;
while (optind < argc) {
if (*argv[optind] != '-') {
opt_white_channels.emplace_back(argv[optind]);
optind++;
} else {
optind--;
break;
}
}
break;
case 'k':
optind--;
while (optind < argc) {
if (*argv[optind] != '-') {
opt_black_channels.emplace_back(argv[optind]);
optind++;
} else {
optind--;
break;
}
}
break;
case 'o':
opt_output_vec.push_back(std::string(optarg));
break;
case 'a':
opt_all = true;
break;
case 'l':
opt_loop = true;
break;
case 'r':
try {
opt_rate = std::stof(optarg);
} catch (const std::invalid_argument& ia) {
std::cout << "Invalid argument: -r/--rate " << std::string(optarg)
<< std::endl;
return -1;
} catch (const std::out_of_range& e) {
std::cout << "Argument is out of range: -r/--rate "
<< std::string(optarg) << std::endl;
return -1;
}
break;
case 'b':
opt_begin = StringToUnixSeconds(std::string(optarg)) * 1e9;
break;
case 'e':
opt_end = StringToUnixSeconds(std::string(optarg)) * 1e9;
break;
case 's':
try {
opt_start = std::stoi(optarg);
} catch (const std::invalid_argument& ia) {
std::cout << "Invalid argument: -s/--start " << std::string(optarg)
<< std::endl;
return -1;
} catch (const std::out_of_range& e) {
std::cout << "Argument is out of range: -s/--start "
<< std::string(optarg) << std::endl;
return -1;
}
break;
case 'd':
try {
opt_delay = std::stoi(optarg);
} catch (std::invalid_argument& ia) {
std::cout << "Invalid argument: -d/--delay " << std::string(optarg)
<< std::endl;
return -1;
} catch (const std::out_of_range& e) {
std::cout << "Argument is out of range: -d/--delay "
<< std::string(optarg) << std::endl;
return -1;
}
break;
case 'h':
DisplayUsage(binary, command);
return 0;
default:
break;
}
} while (true);
// cyber_recorder info
if (command == "info") {
if (opt_file_vec.empty()) {
std::cout << "MUST specify file option (-f)." << std::endl;
return -1;
}
::apollo::cybertron::Init(argv[0]);
Info info;
bool info_result = true;
for (auto& opt_file : opt_file_vec) {
info_result = info_result && info.Display(opt_file) ? true : false;
}
::apollo::cybertron::Shutdown();
return info_result ? 0 : -1;
} else if (command == "recover") {
if (opt_file_vec.empty()) {
std::cout << "MUST specify file option (-f)." << std::endl;
return -1;
}
if (opt_file_vec.size() > 1 || opt_output_vec.size() > 1) {
std::cout << "TOO many input/output file option (-f/-o)." << std::endl;
return -1;
}
if (opt_output_vec.empty()) {
std::string default_output_file = opt_file_vec[0] + ".recover";
opt_output_vec.push_back(default_output_file);
}
::apollo::cybertron::Init(argv[0]);
Recoverer recoverer(opt_file_vec[0], opt_output_vec[0]);
bool recover_result = recoverer.Proc();
::apollo::cybertron::Shutdown();
return recover_result ? 0 : -1;
}
if (command == "play") {
if (opt_file_vec.empty()) {
std::cout << "MUST specify file option (-f)." << std::endl;
return -1;
}
::apollo::cybertron::Init(argv[0]);
bool play_result = true;
for (size_t i = 0; i < opt_file_vec.size(); ++i) {
Player player(opt_file_vec[i], opt_white_channels.empty(),
opt_white_channels, opt_loop, opt_rate, opt_begin, opt_end,
opt_start, opt_delay);
play_result = play_result && player.Init() ? true : false;
play_result = play_result && player.Start() ? true : false;
}
::apollo::cybertron::Shutdown();
return play_result ? 0 : -1;
} else if (command == "record") {
if (opt_white_channels.empty() && !opt_all) {
std::cout
<< "MUST specify channels option (-c) or all channels option (-a)."
<< std::endl;
return -1;
}
if (opt_output_vec.size() > 1) {
std::cout << "TOO many ouput file option (-o)." << std::endl;
return -1;
}
if (opt_output_vec.empty()) {
std::string default_output_file =
UnixSecondsToString(time(nullptr), "%Y%m%d%H%M%S") + ".record";
opt_output_vec.push_back(default_output_file);
}
bool record_result = true;
::apollo::cybertron::Init(argv[0]);
auto recorder = std::make_shared<Recorder>(opt_output_vec[0], opt_all,
opt_white_channels);
record_result = record_result && recorder->Start() ? true : false;
if (record_result) {
while (::apollo::cybertron::OK()) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
record_result = record_result && recorder->Stop() ? true : false;
}
::apollo::cybertron::Shutdown();
return record_result ? 0 : -1;
} else if (command == "split") {
if (opt_file_vec.empty()) {
std::cout << "MUST specify file option (-f)." << std::endl;
return -1;
}
if (opt_file_vec.size() > 1 || opt_output_vec.size() > 1) {
std::cout << "TOO many input/output file option (-f/-o)." << std::endl;
return -1;
}
if (opt_output_vec.empty()) {
std::string default_output_file = opt_file_vec[0] + ".split";
opt_output_vec.push_back(default_output_file);
}
::apollo::cybertron::Init(argv[0]);
Spliter spliter(opt_file_vec[0], opt_output_vec[0], opt_white_channels,
opt_black_channels, opt_begin, opt_end);
bool split_result = spliter.Proc();
::apollo::cybertron::Shutdown();
return split_result ? 0 : -1;
}
// unknown command
DisplayUsage(binary, command);
return -1;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <cassert>
#include "gl.hpp"
#include <GLFW/glfw3.h>
#include "ShaderProgram.hpp"
bool glInit()
{
if(gl3wInit())
{
return true;
}
return false;
}
class glframework
{
public:
static void error_callback(int error, const char* description)
{
std::cerr << "[" << error << "] " << description << std::endl;
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
{
glfwSetWindowShouldClose(window, GL_TRUE);
}
}
glframework() : window(0)
{
}
~glframework()
{
glfwTerminate();
}
bool init ()
{
glfwSetErrorCallback(error_callback);
/* Initialize the library */
if (!glfwInit())
{
return false;
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
if (!window) {
return false;
}
return true;
}
void makeCurrent()
{
if (window)
{
/* Make the window's context current */
glfwMakeContextCurrent(window);
glfwSetKeyCallback(window, key_callback);
}
}
bool shouldContinue()
{
return !glfwWindowShouldClose(window);
}
void swapAndPollEvents()
{
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
private:
GLFWwindow *window;
};
template<typename Tuto>
int tutoRunner(int argc, char **argv)
{
glframework glfw;
if (!glfw.init())
{
std::cerr<<"GLFW failed, aborting."<< std::endl;
return -1;
}
glfw.makeCurrent();
Tuto tuto;
/* Loop until the user closes the window */
while (glfw.shouldContinue())
{
tuto();
glfw.swapAndPollEvents();
}
return 0;
}
class Tutorial1
{
public:
Tutorial1()
{
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);
// An array of 3 vectors which represents 3 vertices
static const GLfloat g_vertex_buffer_data[] = {
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
};
// This will identify our vertex buffer
GLuint vertexbuffer;
// Generate 1 buffer, put the resulting identifier in vertexbuffer
glGenBuffers(1, &vertexbuffer);
// The following commands will talk about our 'vertexbuffer' buffer
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
// Give our vertices to OpenGL.
glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);
glVertexAttribPointer(
0, // attribute 0. No particular reason for 0, but must match the layout in the shader.
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
glEnableVertexAttribArray(0);
glBindVertexArray(0);
}
void operator()()
{
glBindVertexArray(VertexArrayID);
// Draw the triangle !
glDrawArrays(GL_TRIANGLES, 0, 3); // Starting from vertex 0; 3 vertices total -> 1 triangle
glBindVertexArray(0);
}
private:
GLuint VertexArrayID;
};
class Tutorial2 : private Tutorial1
{
public:
Tutorial2()
{
glv::Shader vs(glv::Shader::VERTEX_SHADER);
vs.compile(
"#version 330 core\n"
"in vec3 vertices;\n"
"void main(){\n"
" gl_Position = vec4(vertices, 1);\n"
"}\n"
);
glv::Shader fs(glv::Shader::FRAGMENT_SHADER);
fs.compile(
"#version 330 core\n"
"out vec3 color;\n"
"void main(){\n"
" color = vec3(1, 0, 0);\n"
"}\n"
);
program.attach(vs);
program.attach(fs);
program.link();
}
void operator()()
{
program.use();
Tutorial1::operator ()();
}
private:
glv::ShaderProgram program;
};
int main(int argc, char **argv)
{
if (!glInit())
{
std::cerr<<"GL init failed, aborting."<< std::endl;
return -1;
}
return tutoRunner<Tutorial2>(argc, argv);
}
<commit_msg>3rd tutorial using GLSL<commit_after>#include <iostream>
#include <cassert>
#include "gl.hpp"
#include <GLFW/glfw3.h>
#include "ShaderProgram.hpp"
bool glInit()
{
if(gl3wInit())
{
return true;
}
return false;
}
class glframework
{
public:
static void error_callback(int error, const char* description)
{
std::cerr << "[" << error << "] " << description << std::endl;
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
{
glfwSetWindowShouldClose(window, GL_TRUE);
}
}
glframework() : window(0)
{
}
~glframework()
{
glfwTerminate();
}
bool init ()
{
glfwSetErrorCallback(error_callback);
/* Initialize the library */
if (!glfwInit())
{
return false;
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(1280, 960, "Hello World", NULL, NULL);
if (!window) {
return false;
}
return true;
}
void makeCurrent()
{
if (window)
{
/* Make the window's context current */
glfwMakeContextCurrent(window);
glfwSetKeyCallback(window, key_callback);
}
}
bool shouldContinue()
{
return !glfwWindowShouldClose(window);
}
void swapAndPollEvents()
{
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
private:
GLFWwindow *window;
};
template<typename Tuto>
int tutoRunner(int argc, char **argv)
{
glframework glfw;
if (!glfw.init())
{
std::cerr<<"GLFW failed, aborting."<< std::endl;
return -1;
}
glfw.makeCurrent();
Tuto tuto;
/* Loop until the user closes the window */
while (glfw.shouldContinue())
{
tuto();
glfw.swapAndPollEvents();
}
return 0;
}
class Tutorial1
{
public:
Tutorial1()
{
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);
// An array of 3 vectors which represents 3 vertices
static const GLfloat g_vertex_buffer_data[] = {
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
};
// This will identify our vertex buffer
GLuint vertexbuffer;
// Generate 1 buffer, put the resulting identifier in vertexbuffer
glGenBuffers(1, &vertexbuffer);
// The following commands will talk about our 'vertexbuffer' buffer
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
// Give our vertices to OpenGL.
glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);
glVertexAttribPointer(
0, // attribute 0. No particular reason for 0, but must match the layout in the shader.
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
glEnableVertexAttribArray(0);
glBindVertexArray(0);
}
void operator()()
{
glBindVertexArray(VertexArrayID);
// Draw the triangle !
glDrawArrays(GL_TRIANGLES, 0, 3); // Starting from vertex 0; 3 vertices total -> 1 triangle
glBindVertexArray(0);
}
private:
GLuint VertexArrayID;
};
class Tutorial2 : private Tutorial1
{
public:
Tutorial2()
{
glv::Shader vs(glv::Shader::VERTEX_SHADER);
vs.compile(
"#version 330 core\n"
"in vec3 vertices;\n"
"void main(){\n"
" gl_Position = vec4(vertices, 1);\n"
"}\n"
);
glv::Shader fs(glv::Shader::FRAGMENT_SHADER);
fs.compile(
"#version 330 core\n"
"out vec3 color;\n"
"void main(){\n"
" color = vec3(1, 0, 0);\n"
"}\n"
);
program.attach(vs);
program.attach(fs);
program.link();
}
void operator()()
{
program.use();
Tutorial1::operator ()();
}
private:
glv::ShaderProgram program;
};
timespec diff(timespec t1, timespec t2)
{
timespec diff;
if ((t2.tv_nsec > t1.tv_nsec)) {
diff.tv_sec = t2.tv_sec - t1.tv_sec;
diff.tv_nsec = t2.tv_nsec - t1.tv_nsec;
} else {
diff.tv_sec = t2.tv_sec - t1.tv_sec - 1;
diff.tv_nsec = 1000000000 - t2.tv_nsec + t1.tv_nsec;
}
return diff;
}
class Tutorial3
{
public:
Tutorial3()
{
createVertexArray();
createProgram();
}
void createVertexArray()
{
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);
// An array of vectors which represents 3 vertices
static const GLfloat g_vertex_buffer_data[] = {
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
-1.0f, 1.0f, 0.0f,
1.0f, 1.0f, 0.0f,
};
// This will identify our vertex buffer
GLuint vertexbuffer;
// Generate 1 buffer, put the resulting identifier in vertexbuffer
glGenBuffers(1, &vertexbuffer);
// The following commands will talk about our 'vertexbuffer' buffer
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
// Give our vertices to OpenGL.
glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);
glVertexAttribPointer(
0, // attribute 0. No particular reason for 0, but must match the layout in the shader.
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
glEnableVertexAttribArray(0);
glBindVertexArray(0);
}
void createProgram()
{
glv::Shader vs(glv::Shader::VERTEX_SHADER);
vs.compile(
"#version 330 core\n"
"in vec3 vertices;\n"
"out vec2 surfacePosition;\n"
"void main(){\n"
" gl_Position = vec4(vertices, 1);\n"
" surfacePosition = vertices.xy;\n"
"}\n"
);
std::cout << vs.getLastCompilationLog() << std::endl;
glv::Shader fs(glv::Shader::FRAGMENT_SHADER);
fs.compile(
"varying vec2 surfacePosition;\n"
"uniform float time;\n"
"const float color_intensity = .5;\n"
"const float Pi = 3.14159;\n"
"void main()\n"
"{\n"
"vec2 p=(1.32*surfacePosition);\n"
"for(int i=1;i<5;i++)\n"
"{\n"
"vec2 newp=p;\n"
"newp.x+=.912/float(i)*sin(float(i)*Pi*p.y+time*0.15)+0.91;\n"
"newp.y+=.913/float(i)*cos(float(i)*Pi*p.x+time*-0.14)-0.91;\n"
"p=newp;\n"
"}\n"
"vec3 col=vec3((sin(p.x+p.y)*.91+.1)*color_intensity);\n"
"gl_FragColor=vec4(col, 1.0);\n"
"}\n"
);
std::cout << fs.getLastCompilationLog() << std::endl;
program.attach(vs);
program.attach(fs);
program.link();
std::cout << program.getLastLinkLog() << std::endl;
}
void operator()()
{
program.use();
timespec currenttime;
clock_gettime(CLOCK_REALTIME, ¤ttime);
glProgramUniform1f(program.getId(), 0, (currenttime.tv_sec %1000) + ((float)currenttime.tv_nsec / 1000000000));
glBindVertexArray(VertexArrayID);
// Draw the triangle !
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); // Starting from vertex 0; 3 vertices total -> 1 triangle
glBindVertexArray(0);
}
private:
GLuint VertexArrayID;
glv::ShaderProgram program;
};
int main(int argc, char **argv)
{
if (!glInit())
{
std::cerr<<"GL init failed, aborting."<< std::endl;
return -1;
}
return tutoRunner<Tutorial3>(argc, argv);
}
<|endoftext|>
|
<commit_before>/* mk_baseline_wplane_map.cpp
Copyright (C) 2015 Braam Research, LLC.
*/
#include <omp.h>
#include <string.h>
#include "common.h"
#include "OskarBinReader.h"
void mkBlWpMap(const WMaxMin * bl_ws, int numBaselines, double wstep, BlWMap * bl_wis)
{
double cmax, cmin;
for (int i = 0; i < numBaselines; i++) {
cmax = bl_ws[i].maxw/wstep;
cmin = bl_ws[i].minw/wstep;
bl_wis[i].bl = i;
/*
if (cmax > 0.0)
bl_wis[i].wp = round(cmax);
else if (cmin < 0.0)
bl_wis[i].wp = round(cmin);
else
bl_wis[i].wp = 0;
*/
// Use minimum instead of maximum
// to make things easier at the moment,
// because this determines max support handled by
// threadblock in Romein-like algorithm and if it
// is greater than that determined by current data point
// we point to nonsensical GCF data.
if (cmax < 0.0)
bl_wis[i].wp = int(round(cmax));
else if (cmin > 0.0)
bl_wis[i].wp = int(round(cmin));
else
bl_wis[i].wp = 0;
}
}
long long count_points(BlWMap * m, int n){
long long res = 0;
for(int i = 0; i < n; i++) {
int supp = get_supp(m[i].wp);
res += supp * supp;
}
return res;
}
// This function is required to
// correctly calculate GCF, namely we
// need to know the correct w's mean value
// for each w-plane.
void calcAccums(
const Double3 uvw[]
// We retain separate sum and num of points info
// because it is a valuable information
, /*out*/ double sums[]
, /*out*/ int npts[]
, double wstep
, int numDataPoints // baselines * channels * timesteps
, int numOfWPlanes
) {
int nthreads;
#pragma omp parallel
#pragma omp single
nthreads = omp_get_num_threads();
memset(sums, 0, sizeof(double) * numOfWPlanes);
memset(npts, 0, sizeof(int) * numOfWPlanes);
// VLAs. Requires GNU extension.
double tmpsums[nthreads-1][numOfWPlanes];
int tmpnpts[nthreads-1][numOfWPlanes];
#pragma omp parallel
{
int _thread = omp_get_thread_num();
double * _sums;
int * _npts;
if (_thread == 0) {
_sums = sums;
_npts = npts;
} else {
_sums = tmpsums[_thread - 1];
_npts = tmpnpts[_thread - 1];
}
memset(_sums, 0, sizeof(double) * numOfWPlanes);
memset(_npts, 0, sizeof(int) * numOfWPlanes);
double w;
int wplane;
#pragma omp for schedule(dynamic)
for(int n = 0; n < numDataPoints; n++) {
w = uvw[n].w / wstep;
wplane = int(round(w));
_sums[wplane] += w;
_npts[wplane]++;
}
}
// Simple linear addition (it is faster than starting any threads here)
// Don't use any fance AVX tricks because of
// a negligibility of the whole processing time.
for(int i=0; i<nthreads; i++)
for(int j=0; j<numOfWPlanes; j++) {
sums[j] += tmpsums[i][j];
npts[j] += tmpnpts[i][j];
}
}
<commit_msg>Fix bound for final summation.<commit_after>/* mk_baseline_wplane_map.cpp
Copyright (C) 2015 Braam Research, LLC.
*/
#include <omp.h>
#include <string.h>
#include "common.h"
#include "OskarBinReader.h"
void mkBlWpMap(const WMaxMin * bl_ws, int numBaselines, double wstep, BlWMap * bl_wis)
{
double cmax, cmin;
for (int i = 0; i < numBaselines; i++) {
cmax = bl_ws[i].maxw/wstep;
cmin = bl_ws[i].minw/wstep;
bl_wis[i].bl = i;
/*
if (cmax > 0.0)
bl_wis[i].wp = round(cmax);
else if (cmin < 0.0)
bl_wis[i].wp = round(cmin);
else
bl_wis[i].wp = 0;
*/
// Use minimum instead of maximum
// to make things easier at the moment,
// because this determines max support handled by
// threadblock in Romein-like algorithm and if it
// is greater than that determined by current data point
// we point to nonsensical GCF data.
if (cmax < 0.0)
bl_wis[i].wp = int(round(cmax));
else if (cmin > 0.0)
bl_wis[i].wp = int(round(cmin));
else
bl_wis[i].wp = 0;
}
}
long long count_points(BlWMap * m, int n){
long long res = 0;
for(int i = 0; i < n; i++) {
int supp = get_supp(m[i].wp);
res += supp * supp;
}
return res;
}
// This function is required to
// correctly calculate GCF, namely we
// need to know the correct w's mean value
// for each w-plane.
void calcAccums(
const Double3 uvw[]
// We retain separate sum and num of points info
// because it is a valuable information
, /*out*/ double sums[]
, /*out*/ int npts[]
, double wstep
, int numDataPoints // baselines * channels * timesteps
, int numOfWPlanes
) {
int nthreads;
#pragma omp parallel
#pragma omp single
nthreads = omp_get_num_threads();
memset(sums, 0, sizeof(double) * numOfWPlanes);
memset(npts, 0, sizeof(int) * numOfWPlanes);
// VLAs. Requires GNU extension.
double tmpsums[nthreads-1][numOfWPlanes];
int tmpnpts[nthreads-1][numOfWPlanes];
#pragma omp parallel
{
int _thread = omp_get_thread_num();
double * _sums;
int * _npts;
if (_thread == 0) {
_sums = sums;
_npts = npts;
} else {
_sums = tmpsums[_thread - 1];
_npts = tmpnpts[_thread - 1];
}
memset(_sums, 0, sizeof(double) * numOfWPlanes);
memset(_npts, 0, sizeof(int) * numOfWPlanes);
double w;
int wplane;
#pragma omp for schedule(dynamic)
for(int n = 0; n < numDataPoints; n++) {
w = uvw[n].w / wstep;
wplane = int(round(w));
_sums[wplane] += w;
_npts[wplane]++;
}
}
// Simple linear addition (it is faster than starting any threads here)
// Don't use any fance AVX tricks because of
// a negligibility of the whole processing time.
for(int i=0; i<nthreads-1; i++)
for(int j=0; j<numOfWPlanes; j++) {
sums[j] += tmpsums[i][j];
npts[j] += tmpnpts[i][j];
}
}
<|endoftext|>
|
<commit_before>//--------------------------------------------------------------
// ofApp.h
//--------------------------------------------------------------
#include "ofMain.h"
// ofxGui addon
#include "ofXml.h"
// ofxOsc addon
#include "ofxOscReceiver.h"
// ofxInterface
#include "ofxInterface.h"
// ofxUiEditor addon
#include "ofxUiEditor.h"
const string paramsFile = "params.xml";
const string layoutFile = "layout.json";
class ofApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
void keyPressed(int key);
void exit(ofEventArgs &args);
bool loadLayouts(const string& createSceneNode="");
bool saveLayouts();
private: // attributes
ofxOscReceiver oscReceiver;
ofxUiEditor::MeshDataManager meshDataManager;
shared_ptr<ofxInterface::Node> sceneRef;
ofEasyCam cam;
bool bDrawDebug, bDrawManager;
};
//--------------------------------------------------------------
// ofApp.cpp
//--------------------------------------------------------------
void ofApp::setup(){
// window
ofSetWindowTitle("ofxUiEditor - example");
ofSetWindowShape(400,300);
// create scene
sceneRef = make_shared<ofxInterface::Node>();
sceneRef->setSize(ofGetWidth(), ofGetHeight());
sceneRef->setName("ofxUiEditor-example-scene");
loadLayouts("panel.frame");
// setup osc message listener
oscReceiver.setup(8080);
bDrawManager = false;
bDrawDebug = true;
}
void ofApp::update(){
const int MAX_MESSAGES = 20;
for(int i=0; i<MAX_MESSAGES; i++){
if(!oscReceiver.hasWaitingMessages())
break;
ofxOscMessage msg;
oscReceiver.getNextMessage(msg);
meshDataManager.processOscMessage(msg);
}
}
void ofApp::draw(){
ofBackground(ofColor::gray);
cam.begin();
ofScale(100.0f, 100.0f, 100.0f);
if(bDrawManager)
meshDataManager.draw();
sceneRef->render();
if(bDrawDebug)
sceneRef->renderDebug();
cam.end();
}
void ofApp::keyPressed(int key){
if(key == 'd'){
bDrawDebug = !bDrawDebug;
return;
}
if(key == 'm'){
bDrawManager = !bDrawManager;
return;
}
if(key=='l'){
loadLayouts("panel.frame");
return;
}
if(key=='s'){
saveLayouts();
return;
}
}
void ofApp::exit(ofEventArgs &args){
// saveLayouts();
}
bool ofApp::loadLayouts(const string& createSceneNode){
// clear scene
while(sceneRef->getNumChildren() > 0)
sceneRef->removeChild(0);
ofLog() << "Loading layouts from " << layoutFile;
if(!meshDataManager.loadFromFile(layoutFile))
return false;
if(createSceneNode != ""){
auto layoutNode = meshDataManager.generateNode<ofxInterface::Node>(createSceneNode);
if(layoutNode){
layoutNode->setPosition(0,0,0);
sceneRef->addChild(layoutNode);
}
}
return true;
}
bool ofApp::saveLayouts(){
ofLog() << "Saving layouts to " << layoutFile;
return meshDataManager.saveToFile(layoutFile);
}
//--------------------------------------------------------------
// main.cpp
//--------------------------------------------------------------
int main(){
ofSetupOpenGL(1024,768,OF_WINDOW);
ofRunApp(new ofApp());
}
<commit_msg>slash key toggles ofEasyCam (3d/2d mode)<commit_after>//--------------------------------------------------------------
// ofApp.h
//--------------------------------------------------------------
#include "ofMain.h"
// ofxGui addon
#include "ofXml.h"
// ofxOsc addon
#include "ofxOscReceiver.h"
// ofxInterface
#include "ofxInterface.h"
// ofxUiEditor addon
#include "ofxUiEditor.h"
const string paramsFile = "params.xml";
const string layoutFile = "layout.json";
class ofApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
void keyPressed(int key);
void exit(ofEventArgs &args);
bool loadLayouts(const string& createSceneNode="");
bool saveLayouts();
private: // attributes
ofxOscReceiver oscReceiver;
ofxUiEditor::MeshDataManager meshDataManager;
shared_ptr<ofxInterface::Node> sceneRef;
ofEasyCam cam;
bool bDrawDebug, bDrawManager, bCamEnabled;
};
//--------------------------------------------------------------
// ofApp.cpp
//--------------------------------------------------------------
void ofApp::setup(){
// window
ofSetWindowTitle("ofxUiEditor - example");
ofSetWindowShape(800,600);
// create scene
sceneRef = make_shared<ofxInterface::Node>();
sceneRef->setSize(ofGetWidth(), ofGetHeight());
sceneRef->setName("ofxUiEditor-example-scene");
loadLayouts("panel.frame");
// setup osc message listener
oscReceiver.setup(8080);
bDrawManager = false;
bDrawDebug = bCamEnabled = true;
}
void ofApp::update(){
const int MAX_MESSAGES = 20;
for(int i=0; i<MAX_MESSAGES; i++){
if(!oscReceiver.hasWaitingMessages())
break;
ofxOscMessage msg;
oscReceiver.getNextMessage(msg);
meshDataManager.processOscMessage(msg);
}
}
void ofApp::draw(){
ofBackground(ofColor::gray);
if(bCamEnabled)
cam.begin();
ofScale(50.0f, 50.0f, 50.0f);
if(bDrawManager)
meshDataManager.draw();
sceneRef->render();
if(bDrawDebug)
sceneRef->renderDebug();
if(bCamEnabled)
cam.end();
}
void ofApp::keyPressed(int key){
if(key == 'd'){
bDrawDebug = !bDrawDebug;
return;
}
if(key == 'm'){
bDrawManager = !bDrawManager;
return;
}
if(key=='l'){
loadLayouts("panel.frame");
return;
}
if(key=='s'){
saveLayouts();
return;
}
if(key=='/'){
bCamEnabled = !bCamEnabled;
return;
}
}
void ofApp::exit(ofEventArgs &args){
// saveLayouts();
}
bool ofApp::loadLayouts(const string& createSceneNode){
// clear scene
while(sceneRef->getNumChildren() > 0)
sceneRef->removeChild(0);
ofLog() << "Loading layouts from " << layoutFile;
if(!meshDataManager.loadFromFile(layoutFile))
return false;
if(createSceneNode != ""){
auto layoutNode = meshDataManager.generateNode<ofxInterface::Node>(createSceneNode);
if(layoutNode){
layoutNode->setPosition(0,0,0);
sceneRef->addChild(layoutNode);
}
}
return true;
}
bool ofApp::saveLayouts(){
ofLog() << "Saving layouts to " << layoutFile;
return meshDataManager.saveToFile(layoutFile);
}
//--------------------------------------------------------------
// main.cpp
//--------------------------------------------------------------
int main(){
ofSetupOpenGL(1024,768,OF_WINDOW);
ofRunApp(new ofApp());
}
<|endoftext|>
|
<commit_before>/**************************************************************************/
/*!
Adapted from adafruit ADS1015/ADS1115 library
v1.0 - First release
*/
/**************************************************************************/
#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include <Wire.h>
#include "ADS1115_lite.h"
/**************************************************************************/
/*!
@brief Writes 16-bits to the specified destination register
*/
/**************************************************************************/
static void writeRegister(uint8_t i2cAddress, uint8_t reg, uint16_t value) {
Wire.beginTransmission(i2cAddress);
#if ARDUINO >= 100
Wire.write((uint8_t)reg);
Wire.write((uint8_t)(value>>8));
Wire.write((uint8_t)(value & 0xFF));
#else
Wire.send((uint8_t)reg);
Wire.send((uint8_t)(value>>8));
Wire.send((uint8_t)(value & 0xFF));
#endif
Wire.endTransmission();
}
/**************************************************************************/
/*!
@brief Writes 16-bits to the specified destination register
*/
/**************************************************************************/
static uint16_t readRegister(uint8_t i2cAddress, uint8_t reg) {
Wire.beginTransmission(i2cAddress);
#if ARDUINO >= 100
Wire.write((uint8_t)reg);
#else
Wire.send((uint8_t)reg);
#endif
Wire.endTransmission();
Wire.requestFrom(i2cAddress, (uint8_t)2);
#if ARDUINO >= 100
return ((Wire.read() << 8) | Wire.read());
#else
return ((Wire.receive() << 8) | Wire.receive());
#endif
}
/**************************************************************************/
/*!
@brief Instantiates a new ADS1115 class w/appropriate properties
*/
/**************************************************************************/
ADS1115_lite::ADS1115_lite(uint8_t i2cAddress)
{
Wire.begin();
m_i2cAddress = i2cAddress;
m_gain = ADS1115_REG_CONFIG_PGA_6_144V; /* +/- 6.144V range (limited to VDD +0.3V max!) */
m_mux = ADS1115_REG_CONFIG_MUX_DIFF_0_1; /* to default */
m_rate = ADS1115_REG_CONFIG_DR_128SPS; /* to default */
}
/**************************************************************************/
/*!
@brief Sets up the HW (reads coefficients values, etc.)
*/
/**************************************************************************/
bool ADS1115_lite::testConnection() {
Wire.beginTransmission(m_i2cAddress);
#if ARDUINO >= 100
Wire.write(ADS1115_REG_POINTER_CONVERT);
#else
Wire.send(ADS1115_REG_POINTER_CONVERT);
#endif
Wire.endTransmission();
Wire.requestFrom(m_i2cAddress, (uint8_t)2);
if (Wire.available()) {return 1;}
return 0;
}
/**************************************************************************/
/*!
@brief Sets the gain and input voltage range. Valid numbers:
ADS1115_REG_CONFIG_PGA_6_144V (0x0000) // +/-6.144V range = Gain 2/3
ADS1115_REG_CONFIG_PGA_4_096V (0x0200) // +/-4.096V range = Gain 1
ADS1115_REG_CONFIG_PGA_2_048V (0x0400) // +/-2.048V range = Gain 2 (default)
ADS1115_REG_CONFIG_PGA_1_024V (0x0600) // +/-1.024V range = Gain 4
ADS1115_REG_CONFIG_PGA_0_512V (0x0800) // +/-0.512V range = Gain 8
ADS1115_REG_CONFIG_PGA_0_256V (0x0A00) // +/-0.256V range = Gain 16
*/
/**************************************************************************/
void ADS1115_lite::setGain(uint16_t gain)
{
m_gain = gain;
}
/**************************************************************************/
/*!
@brief Sets the mux. Valid numbers:
ADS1115_REG_CONFIG_MUX_DIFF_0_1 (0x0000) // Differential P = AIN0, N = AIN1 (default)
ADS1115_REG_CONFIG_MUX_DIFF_0_3 (0x1000) // Differential P = AIN0, N = AIN3
ADS1115_REG_CONFIG_MUX_DIFF_1_3 (0x2000) // Differential P = AIN1, N = AIN3
ADS1115_REG_CONFIG_MUX_DIFF_2_3 (0x3000) // Differential P = AIN2, N = AIN3
ADS1115_REG_CONFIG_MUX_SINGLE_0 (0x4000) // Single-ended AIN0
ADS1115_REG_CONFIG_MUX_SINGLE_1 (0x5000) // Single-ended AIN1
ADS1115_REG_CONFIG_MUX_SINGLE_2 (0x6000) // Single-ended AIN2
ADS1115_REG_CONFIG_MUX_SINGLE_3 (0x7000) // Single-ended AIN3
*/
/**************************************************************************/
void ADS1115_lite::setMux(uint16_t mux)
{
m_mux = mux;
}
/**************************************************************************/
/*!
@brief Sets the mux. Valid numbers:
ADS1115_REG_CONFIG_MUX_DIFF_0_1 (0x0000) // Differential P = AIN0, N = AIN1 (default)
ADS1115_REG_CONFIG_MUX_DIFF_0_3 (0x1000) // Differential P = AIN0, N = AIN3
ADS1115_REG_CONFIG_MUX_DIFF_1_3 (0x2000) // Differential P = AIN1, N = AIN3
ADS1115_REG_CONFIG_MUX_DIFF_2_3 (0x3000) // Differential P = AIN2, N = AIN3
ADS1115_REG_CONFIG_MUX_SINGLE_0 (0x4000) // Single-ended AIN0
ADS1115_REG_CONFIG_MUX_SINGLE_1 (0x5000) // Single-ended AIN1
ADS1115_REG_CONFIG_MUX_SINGLE_2 (0x6000) // Single-ended AIN2
ADS1115_REG_CONFIG_MUX_SINGLE_3 (0x7000) // Single-ended AIN3
*/
/**************************************************************************/
void ADS1115_lite::setSampleRate(uint8_t rate)
{
m_rate = rate;
}
/**************************************************************************/
/*!
Trigger Conversion to Read later
*/
/**************************************************************************/
void ADS1115_lite::triggerConversion() {
// Start with default values
uint16_t config = ADS1115_REG_CONFIG_CQUE_NONE | // Disable the comparator (default val)
ADS1115_REG_CONFIG_CLAT_NONLAT | // Non-latching (default val)
ADS1115_REG_CONFIG_CPOL_ACTVLOW | // Alert/Rdy active low (default val)
ADS1115_REG_CONFIG_CMODE_TRAD | // Traditional comparator (default val)
m_rate | // Set Sample Rate
ADS1115_REG_CONFIG_MODE_SINGLE; // Single-shot mode (default)
// OR in the PGA/voltage range
config |= m_gain;
// OR in the mux channel
config |= m_mux;
// OR in the start conversion bit
config |= ADS1115_REG_CONFIG_OS_SINGLE;
// Write config register to the ADC
writeRegister(m_i2cAddress, ADS1115_REG_POINTER_CONFIG, config);
}
/**************************************************************************/
/*!
@brief Waits and returns the last conversion results
*/
/**************************************************************************/
int16_t ADS1115_lite::getConversion()
{ // Wait for the conversion to complete
do {
} while(!isConversionDone());
// Read the conversion results
return readRegister(m_i2cAddress, ADS1115_REG_POINTER_CONVERT);
}
/**************************************************************************/
/*!
@brief returns true if the conversion is done
*/
/**************************************************************************/
bool ADS1115_lite::isConversionDone()
{
int16_t test =readRegister(m_i2cAddress, ADS1115_REG_POINTER_CONFIG);
return test>>15 ;
}
<commit_msg>Delete ADS1115_lite.cpp<commit_after><|endoftext|>
|
<commit_before>// Copyright since 2016 : Evgenii Shatunov (github.com/FrankStain/jnipp-test)
// Apache 2.0 License
#include <main.h>
#include <gtest/gtest.h>
<commit_msg>First tests of object handle. Java object creation tested.<commit_after>// Copyright since 2016 : Evgenii Shatunov (github.com/FrankStain/jnipp-test)
// Apache 2.0 License
#include <main.h>
#include <gtest/gtest.h>
TEST( TestObjectHandle, EmptyIsValid )
{
jnipp::ObjectHandle object_handle;
EXPECT_FALSE( object_handle.IsValid() );
};
TEST( TestObjectHandle, NewObject )
{
jnipp::ObjectHandle object_handle;
EXPECT_FALSE( object_handle.IsValid() );
object_handle = jnipp::ObjectHandle::NewObject( { "java/lang/String" } );
EXPECT_TRUE( object_handle.IsValid() );
};
<|endoftext|>
|
<commit_before>/************************************************************
COSC 501
Elliott Plack
19 NOV 2013 Due 25 NOV 2013
Problem: Create a 1-dimensional array with n elements; get
the size of the array as user input (validate!), max size
should be 10 (declared as class constant). Perform a
variety of functions with the array.
Algorithm: Get array size from user, validate, get values,
perform functions.
************************************************************/
#include <iostream>
using namespace std;
struct node
{
int data;
node *next;
};
int main()
{
char runQuestion = 'Y';
cout << "Do you want to start(Y/N): ";
cin >> runQuestion;
while (runQuestion == 'Y' || runQuestion == 'y')
{
node *head = NULL; // set up header null to first pointer
node *pointerP, *pointerQ; // pointers
cout << "Please enter 10 numbers, in numerical order, below:\n";
for (int i = 0; i < 10; i++)
{
// Reserve space for new node and fill it with data
pointerP = new node;
cout << (i + 1) << ". "; // 1. , 2. etc
cin >> pointerP->data; // validate (see #2)
pointerP->next = NULL;
// Set up link to this node
if (head == NULL)
head = pointerP;
else
{
pointerQ = head; // We know this is not NULL - list not empty!
while (pointerQ->next != NULL)
pointerQ = pointerQ->next; // Move to next link in chain
pointerQ->next = pointerP;
}
}
// print
cout << "The node elements are:\n";
pointerP = head;
while (pointerP != NULL)
{
cout << pointerP->data << endl;
pointerP = pointerP->next;
}
// add a number
pointerP = head;
pointerQ = head;
int newNumber = 0;
cout << "Enter a number to insert:\n";
cin >> newNumber;
while (pointerP->data < newNumber)
{
cout << "\nbefore P " << pointerP->data;
pointerQ = pointerP;
pointerP = pointerP->next;
cout << "\nafter P " << pointerP->data;
}
node *pointerT = new node;
pointerT->data = newNumber;
pointerT->next = pointerQ->next;
pointerQ->next = pointerT;
cout << "The node elements are:\n";
pointerP = head;
while (pointerP != NULL)
{
cout << pointerP->data << endl;
pointerP = pointerP->next;
}
cout << "Do you want to continue(Y/N): ";
cin >> runQuestion;
}
return 0;
}
<commit_msg>delete a node working<commit_after>/************************************************************
COSC 501
Elliott Plack
19 NOV 2013 Due 25 NOV 2013
Problem: Create a 1-dimensional array with n elements; get
the size of the array as user input (validate!), max size
should be 10 (declared as class constant). Perform a
variety of functions with the array.
Algorithm: Get array size from user, validate, get values,
perform functions.
************************************************************/
#include <iostream>
using namespace std;
struct node
{
int data;
node *next;
};
int main()
{
char runQuestion = 'Y';
cout << "Do you want to start(Y/N): ";
cin >> runQuestion;
while (runQuestion == 'Y' || runQuestion == 'y')
{
node *head = NULL; // set up header null to first pointer
node *pointerP, *pointerQ; // pointers
cout << "Please enter 10 numbers, in numerical order, below:\n";
for (int i = 0; i < 10; i++)
{
// Reserve space for new node and fill it with data
pointerP = new node;
cout << (i + 1) << ". "; // 1. , 2. etc
cin >> pointerP->data; // validate (see #2)
pointerP->next = NULL;
// Set up link to this node
if (head == NULL)
head = pointerP;
else
{
pointerQ = head; // We know this is not NULL - list not empty!
while (pointerQ->next != NULL)
pointerQ = pointerQ->next; // Move to next link in chain
pointerQ->next = pointerP;
}
}
// print
cout << "The node elements are:\n";
pointerP = head;
while (pointerP != NULL)
{
cout << pointerP->data << endl;
pointerP = pointerP->next;
}
// add a number
pointerP = head;
pointerQ = head;
int newNumber = 0;
cout << "Enter a number to insert: ";
cin >> newNumber;
while (pointerP->data < newNumber)
{
pointerQ = pointerP;
pointerP = pointerP->next;
}
node *pointerT = new node;
pointerT->data = newNumber;
pointerT->next = pointerQ->next;
pointerQ->next = pointerT;
cout << "The node elements are:\n";
pointerP = head;
while (pointerP != NULL)
{
cout << pointerP->data << endl;
pointerP = pointerP->next;
}
// delete a node
int deleteMe = 0;
bool flag = true;
cout << "Enter a number in the list to delete: ";
cin >> deleteMe;
pointerQ = head;
pointerP = pointerQ->next;
flag = true;
do {
if (pointerP->data == deleteMe)
{
pointerQ->next = pointerP->next;
delete pointerP;
flag = false;
}
else
{
pointerQ = pointerP;
pointerP = pointerP->next;
}
} while (flag && (pointerP->next != NULL));
// print
pointerP = head;
while (pointerP != NULL)
{
cout << pointerP->data << endl;
pointerP = pointerP->next;
}
cout << "Do you want to continue(Y/N): ";
cin >> runQuestion;
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Created on: 19 Apr 2014
* Author: Vladimir Ivan
*
* Copyright (c) 2016, University Of Edinburgh
* 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 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.
*
*/
#include <exotica/Problems/UnconstrainedTimeIndexedProblem.h>
#include <exotica/Setup.h>
REGISTER_PROBLEM_TYPE("UnconstrainedTimeIndexedProblem", exotica::UnconstrainedTimeIndexedProblem)
namespace exotica
{
UnconstrainedTimeIndexedProblem::UnconstrainedTimeIndexedProblem()
: T(0), tau(0), Q_rate(0), W_rate(0), H_rate(0)
{
Flags = KIN_FK | KIN_J;
}
UnconstrainedTimeIndexedProblem::~UnconstrainedTimeIndexedProblem()
{
}
void UnconstrainedTimeIndexedProblem::Instantiate(UnconstrainedTimeIndexedProblemInitializer& init)
{
T = init.T;
if (T <= 2)
{
throw_named("Invalid number of timesteps: " << T);
}
tau = init.Tau;
Q_rate = init.Qrate;
H_rate = init.Hrate;
W_rate = init.Wrate;
NumTasks = Tasks.size();
PhiN = 0;
JN = 0;
TaskSpaceVector yref;
for (int i = 0; i < NumTasks; i++)
{
appendVector(yref.map, Tasks[i]->getLieGroupIndices());
PhiN += Tasks[i]->Length;
JN += Tasks[i]->LengthJ;
}
N = scene_->getSolver().getNumControlledJoints();
W = Eigen::MatrixXd::Identity(N, N) * W_rate;
if (init.W.rows() > 0)
{
if (init.W.rows() == N)
{
W.diagonal() = init.W * W_rate;
}
else
{
throw_named("W dimension mismatch! Expected " << N << ", got " << init.W.rows());
}
}
H = Eigen::MatrixXd::Identity(N, N) * Q_rate;
Q = Eigen::MatrixXd::Identity(N, N) * H_rate;
if (init.Rho.rows() == 0)
{
Rho.assign(T, Eigen::VectorXd::Ones(NumTasks));
}
else if (init.Rho.rows() == NumTasks)
{
Rho.assign(T, init.Rho);
}
else if (init.Rho.rows() == NumTasks * T)
{
Rho.resize(T);
for (int i = 0; i < T; i++)
{
Rho[i] = init.Rho.segment(i * NumTasks, NumTasks);
}
}
else
{
throw_named("Invalid task weights rho! " << init.Rho.rows());
}
yref.setZero(PhiN);
y.assign(T, yref);
Phi = y;
ydiff.assign(T, Eigen::VectorXd::Zero(JN));
J.assign(T, Eigen::MatrixXd(JN, N));
S.assign(T, Eigen::MatrixXd::Identity(JN, JN));
// Set initial trajectory
InitialTrajectory.resize(T, getStartState());
}
void UnconstrainedTimeIndexedProblem::preupdate()
{
PlanningProblem::preupdate();
for(int t; t=0; t<T)
{
for (TaskMap_ptr task : Tasks)
{
for (int i = 0; i < task->Length; i++)
{
S[t](i + task->Start, i + task->Start) = Rho[t](task->Id);
}
}
}
}
void UnconstrainedTimeIndexedProblem::setInitialTrajectory(
const std::vector<Eigen::VectorXd> q_init_in)
{
if (q_init_in.size() != T)
throw_pretty("Expected initial trajectory of length "
<< T << " but got " << q_init_in.size());
if (q_init_in[0].rows() != N)
throw_pretty("Expected states to have " << N << " rows but got "
<< q_init_in[0].rows());
InitialTrajectory = q_init_in;
setStartState(q_init_in[0]);
}
std::vector<Eigen::VectorXd> UnconstrainedTimeIndexedProblem::getInitialTrajectory()
{
return InitialTrajectory;
}
double UnconstrainedTimeIndexedProblem::getDuration()
{
return tau * (double)T;
}
void UnconstrainedTimeIndexedProblem::Update(Eigen::VectorXdRefConst x, int t)
{
if (t >= T || t < -1)
{
throw_pretty("Requested t=" << t << " out of range, needs to be 0 =< t < " << T);
}
else if (t == -1)
{
t = T - 1;
}
scene_->Update(x, static_cast<double>(t) * tau);
for (int i = 0; i < NumTasks; i++)
{
// Only update TaskMap if Rho is not 0
if (Rho[t](i) != 0)
Tasks[i]->update(x, Phi[t].data.segment(Tasks[i]->Start, Tasks[i]->Length), J[t].middleRows(Tasks[i]->StartJ, Tasks[i]->LengthJ));
}
ydiff[t] = Phi[t] - y[t];
}
double UnconstrainedTimeIndexedProblem::getScalarCost(int t)
{
return ydiff[t].transpose()*S[t]*ydiff[t];
}
Eigen::VectorXd UnconstrainedTimeIndexedProblem::getScalarJacobian(int t)
{
return J[t].transpose()*S[t]*ydiff[t]*2.0;
}
void UnconstrainedTimeIndexedProblem::setGoal(const std::string& task_name, Eigen::VectorXdRefConst goal, int t)
{
try
{
if (t >= T || t < -1)
{
throw_pretty("Requested t="
<< t
<< " out of range, needs to be 0 =< t < " << T);
}
else if (t == -1)
{
t = T - 1;
}
TaskMap_ptr task = TaskMaps.at(task_name);
y[t].data.segment(task->Start, task->Length) = goal;
}
catch (std::out_of_range& e)
{
throw_pretty("Cannot set Goal. Task map '" << task_name << "' Does not exist.");
}
}
void UnconstrainedTimeIndexedProblem::setRho(const std::string& task_name, const double rho, int t)
{
try
{
if (t >= T || t < -1)
{
throw_pretty("Requested t="
<< t
<< " out of range, needs to be 0 =< t < " << T);
}
else if (t == -1)
{
t = T - 1;
}
TaskMap_ptr task = TaskMaps.at(task_name);
Rho[t](task->Id) = rho;
}
catch (std::out_of_range& e)
{
throw_pretty("Cannot set Rho. Task map '" << task_name << "' Does not exist.");
}
}
Eigen::VectorXd UnconstrainedTimeIndexedProblem::getGoal(const std::string& task_name, int t)
{
try
{
if (t >= T || t < -1)
{
throw_pretty("Requested t="
<< t
<< " out of range, needs to be 0 =< t < " << T);
}
else if (t == -1)
{
t = T - 1;
}
TaskMap_ptr task = TaskMaps.at(task_name);
return y[t].data.segment(task->Start, task->Length);
}
catch (std::out_of_range& e)
{
throw_pretty("Cannot get Goal. Task map '" << task_name << "' Does not exist.");
}
}
double UnconstrainedTimeIndexedProblem::getRho(const std::string& task_name, int t)
{
try
{
if (t >= T || t < -1)
{
throw_pretty("Requested t="
<< t
<< " out of range, needs to be 0 =< t < " << T);
}
else if (t == -1)
{
t = T - 1;
}
TaskMap_ptr task = TaskMaps.at(task_name);
return Rho[t](task->Id);
}
catch (std::out_of_range& e)
{
throw_pretty("Cannot get Rho. Task map '" << task_name << "' Does not exist.");
}
}
}
<commit_msg>Fixed preupdate for time indexed problem<commit_after>/*
* Created on: 19 Apr 2014
* Author: Vladimir Ivan
*
* Copyright (c) 2016, University Of Edinburgh
* 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 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.
*
*/
#include <exotica/Problems/UnconstrainedTimeIndexedProblem.h>
#include <exotica/Setup.h>
REGISTER_PROBLEM_TYPE("UnconstrainedTimeIndexedProblem", exotica::UnconstrainedTimeIndexedProblem)
namespace exotica
{
UnconstrainedTimeIndexedProblem::UnconstrainedTimeIndexedProblem()
: T(0), tau(0), Q_rate(0), W_rate(0), H_rate(0)
{
Flags = KIN_FK | KIN_J;
}
UnconstrainedTimeIndexedProblem::~UnconstrainedTimeIndexedProblem()
{
}
void UnconstrainedTimeIndexedProblem::Instantiate(UnconstrainedTimeIndexedProblemInitializer& init)
{
T = init.T;
if (T <= 2)
{
throw_named("Invalid number of timesteps: " << T);
}
tau = init.Tau;
Q_rate = init.Qrate;
H_rate = init.Hrate;
W_rate = init.Wrate;
NumTasks = Tasks.size();
PhiN = 0;
JN = 0;
TaskSpaceVector yref;
for (int i = 0; i < NumTasks; i++)
{
appendVector(yref.map, Tasks[i]->getLieGroupIndices());
PhiN += Tasks[i]->Length;
JN += Tasks[i]->LengthJ;
}
N = scene_->getSolver().getNumControlledJoints();
W = Eigen::MatrixXd::Identity(N, N) * W_rate;
if (init.W.rows() > 0)
{
if (init.W.rows() == N)
{
W.diagonal() = init.W * W_rate;
}
else
{
throw_named("W dimension mismatch! Expected " << N << ", got " << init.W.rows());
}
}
H = Eigen::MatrixXd::Identity(N, N) * Q_rate;
Q = Eigen::MatrixXd::Identity(N, N) * H_rate;
if (init.Rho.rows() == 0)
{
Rho.assign(T, Eigen::VectorXd::Ones(NumTasks));
}
else if (init.Rho.rows() == NumTasks)
{
Rho.assign(T, init.Rho);
}
else if (init.Rho.rows() == NumTasks * T)
{
Rho.resize(T);
for (int i = 0; i < T; i++)
{
Rho[i] = init.Rho.segment(i * NumTasks, NumTasks);
}
}
else
{
throw_named("Invalid task weights rho! " << init.Rho.rows());
}
yref.setZero(PhiN);
y.assign(T, yref);
Phi = y;
ydiff.assign(T, Eigen::VectorXd::Zero(JN));
J.assign(T, Eigen::MatrixXd(JN, N));
S.assign(T, Eigen::MatrixXd::Identity(JN, JN));
// Set initial trajectory
InitialTrajectory.resize(T, getStartState());
}
void UnconstrainedTimeIndexedProblem::preupdate()
{
PlanningProblem::preupdate();
for(int t=0; t<T; t++)
{
for (TaskMap_ptr task : Tasks)
{
for (int i = 0; i < task->Length; i++)
{
S[t](i + task->Start, i + task->Start) = Rho[t](task->Id);
}
}
}
}
void UnconstrainedTimeIndexedProblem::setInitialTrajectory(
const std::vector<Eigen::VectorXd> q_init_in)
{
if (q_init_in.size() != T)
throw_pretty("Expected initial trajectory of length "
<< T << " but got " << q_init_in.size());
if (q_init_in[0].rows() != N)
throw_pretty("Expected states to have " << N << " rows but got "
<< q_init_in[0].rows());
InitialTrajectory = q_init_in;
setStartState(q_init_in[0]);
}
std::vector<Eigen::VectorXd> UnconstrainedTimeIndexedProblem::getInitialTrajectory()
{
return InitialTrajectory;
}
double UnconstrainedTimeIndexedProblem::getDuration()
{
return tau * (double)T;
}
void UnconstrainedTimeIndexedProblem::Update(Eigen::VectorXdRefConst x, int t)
{
if (t >= T || t < -1)
{
throw_pretty("Requested t=" << t << " out of range, needs to be 0 =< t < " << T);
}
else if (t == -1)
{
t = T - 1;
}
scene_->Update(x, static_cast<double>(t) * tau);
for (int i = 0; i < NumTasks; i++)
{
// Only update TaskMap if Rho is not 0
if (Rho[t](i) != 0)
Tasks[i]->update(x, Phi[t].data.segment(Tasks[i]->Start, Tasks[i]->Length), J[t].middleRows(Tasks[i]->StartJ, Tasks[i]->LengthJ));
}
ydiff[t] = Phi[t] - y[t];
}
double UnconstrainedTimeIndexedProblem::getScalarCost(int t)
{
return ydiff[t].transpose()*S[t]*ydiff[t];
}
Eigen::VectorXd UnconstrainedTimeIndexedProblem::getScalarJacobian(int t)
{
return J[t].transpose()*S[t]*ydiff[t]*2.0;
}
void UnconstrainedTimeIndexedProblem::setGoal(const std::string& task_name, Eigen::VectorXdRefConst goal, int t)
{
try
{
if (t >= T || t < -1)
{
throw_pretty("Requested t="
<< t
<< " out of range, needs to be 0 =< t < " << T);
}
else if (t == -1)
{
t = T - 1;
}
TaskMap_ptr task = TaskMaps.at(task_name);
y[t].data.segment(task->Start, task->Length) = goal;
}
catch (std::out_of_range& e)
{
throw_pretty("Cannot set Goal. Task map '" << task_name << "' Does not exist.");
}
}
void UnconstrainedTimeIndexedProblem::setRho(const std::string& task_name, const double rho, int t)
{
try
{
if (t >= T || t < -1)
{
throw_pretty("Requested t="
<< t
<< " out of range, needs to be 0 =< t < " << T);
}
else if (t == -1)
{
t = T - 1;
}
TaskMap_ptr task = TaskMaps.at(task_name);
Rho[t](task->Id) = rho;
}
catch (std::out_of_range& e)
{
throw_pretty("Cannot set Rho. Task map '" << task_name << "' Does not exist.");
}
}
Eigen::VectorXd UnconstrainedTimeIndexedProblem::getGoal(const std::string& task_name, int t)
{
try
{
if (t >= T || t < -1)
{
throw_pretty("Requested t="
<< t
<< " out of range, needs to be 0 =< t < " << T);
}
else if (t == -1)
{
t = T - 1;
}
TaskMap_ptr task = TaskMaps.at(task_name);
return y[t].data.segment(task->Start, task->Length);
}
catch (std::out_of_range& e)
{
throw_pretty("Cannot get Goal. Task map '" << task_name << "' Does not exist.");
}
}
double UnconstrainedTimeIndexedProblem::getRho(const std::string& task_name, int t)
{
try
{
if (t >= T || t < -1)
{
throw_pretty("Requested t="
<< t
<< " out of range, needs to be 0 =< t < " << T);
}
else if (t == -1)
{
t = T - 1;
}
TaskMap_ptr task = TaskMaps.at(task_name);
return Rho[t](task->Id);
}
catch (std::out_of_range& e)
{
throw_pretty("Cannot get Rho. Task map '" << task_name << "' Does not exist.");
}
}
}
<|endoftext|>
|
<commit_before>//
// Created by Vadim N. on 04/04/2015.
//
//#include <omp.h>
//#include <stdio.h>
//
//int main() {
//#pragma omp parallel
// printf("Hello from thread %d, nthreads %d\n", omp_get_thread_num(), omp_get_num_threads());
//}
#include <ostream>
#include "parser.h"
#include "probabilisticassemblingmodel.h"
using namespace ymir;
/**
* \brief Main function of a script for computing generation probabitilies. It has
* a strict order of input arguments in console:
* argv[0] - name of the script (default);
* argv[1] - path to an input file;
* argv[2] - path to a model;
* argv[3] - path to an output file;
* argv[4] - 0 if model should use stored gene usage; 1 if model should recompute gene usage from the input file.
*/
int main(int argc, char* argv[]) {
std::string in_file_path(argv[1]),
model_path(argv[2]),
out_file_path(argv[3]);
bool recompute_genes = std::stoi(argv[4]);
std::cout << "Input file:\t" << in_file_path << std::endl;
std::cout << "Model path:\t" << model_path << std::endl;
std::cout << "Output file:\t" << out_file_path << std::endl;
std::cout << std::endl;
ProbabilisticAssemblingModel model(model_path);
std::cout << std::endl;
if (model.status()) {
RepertoireParser parser;
Cloneset cloneset;
if (parser.parse(in_file_path, &cloneset, model.gene_segments(),
RepertoireParser::AlignmentColumnOptions()
.setV(RepertoireParser::MAKE_IF_NOT_FOUND)
.setJ(RepertoireParser::MAKE_IF_NOT_FOUND)
.setD(RepertoireParser::OVERWRITE))) {
if (recompute_genes) {
model.updateGeneUsage(cloneset);
}
auto prob_vec = model.computeFullProbabilities(cloneset);
std::ofstream ofs;
ofs.open(out_file_path);
std::cout << std::endl;
std::cout << "Generation probabilities statistics:" << std::endl;
prob_summary(prob_vec);
if (ofs.is_open()) {
for (auto i = 0; i < prob_vec.size(); ++i) {
ofs << prob_vec[i] << std::endl;
}
} else {
std::cout << "Problems with the output stream. Terminating..." << std::endl;
}
ofs.close();
} else {
std::cout << "Problems in parsing the input file. Terminating..." << std::endl;
}
} else {
std::cout << "Problems with the model. Terminating..." << std::endl;
}
return 0;
}<commit_msg>few cosmetic changes...<commit_after>//
// Created by Vadim N. on 04/04/2015.
//
//#include <omp.h>
//#include <stdio.h>
//
//int main() {
//#pragma omp parallel
// printf("Hello from thread %d, nthreads %d\n", omp_get_thread_num(), omp_get_num_threads());
//}
#include <ostream>
#include "parser.h"
#include "probabilisticassemblingmodel.h"
using namespace ymir;
/**
* \brief Main function of a script for computing generation probabitilies. It has
* a strict order of input arguments in console:
* argv[0] - name of the script (default);
* argv[1] - path to an input file;
* argv[2] - path to a model;
* argv[3] - path to an output file;
* argv[4] - 0 if model should use stored gene usage; 1 if model should recompute gene usage from the input file.
*/
int main(int argc, char* argv[]) {
std::string in_file_path(argv[1]),
model_path(argv[2]),
out_file_path(argv[3]);
bool recompute_genes = std::stoi(argv[4]);
std::cout << "Input file:\t" << in_file_path << std::endl;
std::cout << "Model path:\t" << model_path << std::endl;
std::cout << "Output file:\t" << out_file_path << std::endl;
std::cout << std::endl;
ProbabilisticAssemblingModel model(model_path);
std::cout << std::endl;
if (model.status()) {
RepertoireParser parser;
Cloneset cloneset;
if (parser.parse(in_file_path, &cloneset, model.gene_segments(),
RepertoireParser::AlignmentColumnOptions()
.setV(RepertoireParser::MAKE_IF_NOT_FOUND)
.setJ(RepertoireParser::MAKE_IF_NOT_FOUND)
.setD(RepertoireParser::OVERWRITE))) {
if (recompute_genes) {
std::cout << std::endl;
std::cout << "Recomputing gene usage on " << (size_t) cloneset.noncoding().size() << " clonotypes." << std::endl;
model.updateGeneUsage(cloneset);
}
auto prob_vec = model.computeFullProbabilities(cloneset);
std::ofstream ofs;
ofs.open(out_file_path);
std::cout << std::endl;
std::cout << "Generation probabilities statistics:" << std::endl;
prob_summary(prob_vec);
if (ofs.is_open()) {
for (auto i = 0; i < prob_vec.size(); ++i) {
ofs << prob_vec[i] << std::endl;
}
} else {
std::cout << "Problems with the output stream. Terminating..." << std::endl;
}
ofs.close();
} else {
std::cout << "Problems in parsing the input file. Terminating..." << std::endl;
}
} else {
std::cout << "Problems with the model. Terminating..." << std::endl;
}
return 0;
}<|endoftext|>
|
<commit_before>/*-------------------------------------------------------------------------
* Vulkan CTS
* ----------
*
* Copyright (c) 2019 The Khronos Group 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 "deSTLUtil.hpp"
#include "deString.h"
#include "vkQueryUtil.hpp"
#include "vkDeviceFeatures.inl"
#include "vkDeviceFeatures.hpp"
namespace vk
{
DeviceFeatures::DeviceFeatures (const InstanceInterface& vki,
const deUint32 apiVersion,
const VkPhysicalDevice physicalDevice,
const std::vector<std::string>& instanceExtensions,
const std::vector<std::string>& deviceExtensions,
const deBool enableAllFeatures)
{
VkPhysicalDeviceRobustness2FeaturesEXT* robustness2Features = nullptr;
VkPhysicalDeviceImageRobustnessFeaturesEXT* imageRobustnessFeatures = nullptr;
VkPhysicalDeviceFragmentShadingRateFeaturesKHR* fragmentShadingRateFeatures = nullptr;
VkPhysicalDeviceShadingRateImageFeaturesNV* shadingRateImageFeatures = nullptr;
VkPhysicalDeviceFragmentDensityMapFeaturesEXT* fragmentDensityMapFeatures = nullptr;
VkPhysicalDevicePageableDeviceLocalMemoryFeaturesEXT* pageableDeviceLocalMemoryFeatures = nullptr;
m_coreFeatures2 = initVulkanStructure();
m_vulkan11Features = initVulkanStructure();
m_vulkan12Features = initVulkanStructure();
m_vulkan13Features = initVulkanStructure();
if (isInstanceExtensionSupported(apiVersion, instanceExtensions, "VK_KHR_get_physical_device_properties2"))
{
const std::vector<VkExtensionProperties> deviceExtensionProperties = enumerateDeviceExtensionProperties(vki, physicalDevice, DE_NULL);
void** nextPtr = &m_coreFeatures2.pNext;
std::vector<FeatureStructWrapperBase*> featuresToFillFromBlob;
bool vk13Supported = (apiVersion >= VK_API_VERSION_1_3);
bool vk12Supported = (apiVersion >= VK_API_VERSION_1_2);
// since vk12 we have blob structures combining features of couple previously
// available feature structures, that now in vk12+ must be removed from chain
if (vk12Supported)
{
addToChainVulkanStructure(&nextPtr, m_vulkan11Features);
addToChainVulkanStructure(&nextPtr, m_vulkan12Features);
if (vk13Supported)
addToChainVulkanStructure(&nextPtr, m_vulkan13Features);
}
// iterate over data for all feature that are defined in specification
for (const auto& featureStructCreationData : featureStructCreationArray)
{
const char* featureName = featureStructCreationData.name;
// check if this feature is available on current device
if (de::contains(deviceExtensions.begin(), deviceExtensions.end(), featureName) &&
verifyFeatureAddCriteria(featureStructCreationData, deviceExtensionProperties))
{
FeatureStructWrapperBase* p = (*featureStructCreationData.creatorFunction)();
if (p == DE_NULL)
continue;
// if feature struct is part of VkPhysicalDeviceVulkan1{1,2,3}Features
// we dont add it to the chain but store and fill later from blob data
bool featureFilledFromBlob = false;
if (vk12Supported)
{
deUint32 blobApiVersion = getBlobFeaturesVersion(p->getFeatureDesc().sType);
if (blobApiVersion)
featureFilledFromBlob = (apiVersion >= blobApiVersion);
}
if (featureFilledFromBlob)
featuresToFillFromBlob.push_back(p);
else
{
VkStructureType structType = p->getFeatureDesc().sType;
void* rawStructPtr = p->getFeatureTypeRaw();
if (structType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_FEATURES_EXT)
robustness2Features = reinterpret_cast<VkPhysicalDeviceRobustness2FeaturesEXT*>(rawStructPtr);
else if (structType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_ROBUSTNESS_FEATURES_EXT)
imageRobustnessFeatures = reinterpret_cast<VkPhysicalDeviceImageRobustnessFeaturesEXT*>(rawStructPtr);
else if (structType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADING_RATE_FEATURES_KHR)
fragmentShadingRateFeatures = reinterpret_cast<VkPhysicalDeviceFragmentShadingRateFeaturesKHR*>(rawStructPtr);
else if (structType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADING_RATE_IMAGE_FEATURES_NV)
shadingRateImageFeatures = reinterpret_cast<VkPhysicalDeviceShadingRateImageFeaturesNV*>(rawStructPtr);
else if (structType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_DENSITY_MAP_FEATURES_EXT)
fragmentDensityMapFeatures = reinterpret_cast<VkPhysicalDeviceFragmentDensityMapFeaturesEXT*>(rawStructPtr);
else if (structType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PAGEABLE_DEVICE_LOCAL_MEMORY_FEATURES_EXT)
pageableDeviceLocalMemoryFeatures = reinterpret_cast<VkPhysicalDevicePageableDeviceLocalMemoryFeaturesEXT*>(rawStructPtr);
// add to chain
*nextPtr = rawStructPtr;
nextPtr = p->getFeatureTypeNext();
}
m_features.push_back(p);
}
}
vki.getPhysicalDeviceFeatures2(physicalDevice, &m_coreFeatures2);
// fill data from VkPhysicalDeviceVulkan1{1,2,3}Features
if (vk12Supported)
{
AllFeaturesBlobs allBlobs =
{
m_vulkan11Features,
m_vulkan12Features,
m_vulkan13Features,
// add blobs from future vulkan versions here
};
for (auto feature : featuresToFillFromBlob)
feature->initializeFeatureFromBlob(allBlobs);
}
}
else
m_coreFeatures2.features = getPhysicalDeviceFeatures(vki, physicalDevice);
// 'enableAllFeatures' is used to create a complete list of supported features.
if (!enableAllFeatures)
{
// Disable robustness by default, as it has an impact on performance on some HW.
if (robustness2Features)
{
robustness2Features->robustBufferAccess2 = false;
robustness2Features->robustImageAccess2 = false;
robustness2Features->nullDescriptor = false;
}
if (imageRobustnessFeatures)
{
imageRobustnessFeatures->robustImageAccess = false;
}
m_coreFeatures2.features.robustBufferAccess = false;
// Disable VK_EXT_fragment_density_map and VK_NV_shading_rate_image features
// that must: not be enabled if KHR fragment shading rate features are enabled.
if (fragmentShadingRateFeatures &&
(fragmentShadingRateFeatures->pipelineFragmentShadingRate ||
fragmentShadingRateFeatures->primitiveFragmentShadingRate ||
fragmentShadingRateFeatures->attachmentFragmentShadingRate))
{
if (shadingRateImageFeatures)
shadingRateImageFeatures->shadingRateImage = false;
if (fragmentDensityMapFeatures)
fragmentDensityMapFeatures->fragmentDensityMap = false;
}
// Disable pageableDeviceLocalMemory by default since it may modify the behavior
// of device-local, and even host-local, memory allocations for all tests.
// pageableDeviceLocalMemory will use targetted testing on a custom device.
if (pageableDeviceLocalMemoryFeatures)
pageableDeviceLocalMemoryFeatures->pageableDeviceLocalMemory = false;
}
// Disable pageableDeviceLocalMemory by default since it may modify the behavior
// of device-local, and even host-local, memory allocations for all tests.
// pageableDeviceLocalMemory will use targetted testing on a custom device.
if (pageableDeviceLocalMemoryFeatures)
pageableDeviceLocalMemoryFeatures->pageableDeviceLocalMemory = false;
}
bool DeviceFeatures::verifyFeatureAddCriteria (const FeatureStructCreationData& item, const std::vector<VkExtensionProperties>& properties)
{
if (deStringEqual(item.name, VK_KHR_VULKAN_MEMORY_MODEL_EXTENSION_NAME))
{
for (const auto& property : properties)
{
if (deStringEqual(property.extensionName, item.name))
return (property.specVersion == item.specVersion);
}
}
return true;
}
bool DeviceFeatures::contains (const std::string& feature, bool throwIfNotExists) const
{
for (const auto f : m_features)
{
if (deStringEqual(f->getFeatureDesc().name, feature.c_str()))
return true;
}
if (throwIfNotExists)
TCU_THROW(NotSupportedError, "Feature " + feature + " is not supported");
return false;
}
bool DeviceFeatures::isDeviceFeatureInitialized (VkStructureType sType) const
{
for (const auto f : m_features)
{
if (f->getFeatureDesc().sType == sType)
return true;
}
return false;
}
DeviceFeatures::~DeviceFeatures (void)
{
for (auto p : m_features)
delete p;
m_features.clear();
}
} // vk
<commit_msg>Fix bad merge affecting create_device_unsupported_features test<commit_after>/*-------------------------------------------------------------------------
* Vulkan CTS
* ----------
*
* Copyright (c) 2019 The Khronos Group 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 "deSTLUtil.hpp"
#include "deString.h"
#include "vkQueryUtil.hpp"
#include "vkDeviceFeatures.inl"
#include "vkDeviceFeatures.hpp"
namespace vk
{
DeviceFeatures::DeviceFeatures (const InstanceInterface& vki,
const deUint32 apiVersion,
const VkPhysicalDevice physicalDevice,
const std::vector<std::string>& instanceExtensions,
const std::vector<std::string>& deviceExtensions,
const deBool enableAllFeatures)
{
VkPhysicalDeviceRobustness2FeaturesEXT* robustness2Features = nullptr;
VkPhysicalDeviceImageRobustnessFeaturesEXT* imageRobustnessFeatures = nullptr;
VkPhysicalDeviceFragmentShadingRateFeaturesKHR* fragmentShadingRateFeatures = nullptr;
VkPhysicalDeviceShadingRateImageFeaturesNV* shadingRateImageFeatures = nullptr;
VkPhysicalDeviceFragmentDensityMapFeaturesEXT* fragmentDensityMapFeatures = nullptr;
VkPhysicalDevicePageableDeviceLocalMemoryFeaturesEXT* pageableDeviceLocalMemoryFeatures = nullptr;
m_coreFeatures2 = initVulkanStructure();
m_vulkan11Features = initVulkanStructure();
m_vulkan12Features = initVulkanStructure();
m_vulkan13Features = initVulkanStructure();
if (isInstanceExtensionSupported(apiVersion, instanceExtensions, "VK_KHR_get_physical_device_properties2"))
{
const std::vector<VkExtensionProperties> deviceExtensionProperties = enumerateDeviceExtensionProperties(vki, physicalDevice, DE_NULL);
void** nextPtr = &m_coreFeatures2.pNext;
std::vector<FeatureStructWrapperBase*> featuresToFillFromBlob;
bool vk13Supported = (apiVersion >= VK_API_VERSION_1_3);
bool vk12Supported = (apiVersion >= VK_API_VERSION_1_2);
// since vk12 we have blob structures combining features of couple previously
// available feature structures, that now in vk12+ must be removed from chain
if (vk12Supported)
{
addToChainVulkanStructure(&nextPtr, m_vulkan11Features);
addToChainVulkanStructure(&nextPtr, m_vulkan12Features);
if (vk13Supported)
addToChainVulkanStructure(&nextPtr, m_vulkan13Features);
}
// iterate over data for all feature that are defined in specification
for (const auto& featureStructCreationData : featureStructCreationArray)
{
const char* featureName = featureStructCreationData.name;
// check if this feature is available on current device
if (de::contains(deviceExtensions.begin(), deviceExtensions.end(), featureName) &&
verifyFeatureAddCriteria(featureStructCreationData, deviceExtensionProperties))
{
FeatureStructWrapperBase* p = (*featureStructCreationData.creatorFunction)();
if (p == DE_NULL)
continue;
// if feature struct is part of VkPhysicalDeviceVulkan1{1,2,3}Features
// we dont add it to the chain but store and fill later from blob data
bool featureFilledFromBlob = false;
if (vk12Supported)
{
deUint32 blobApiVersion = getBlobFeaturesVersion(p->getFeatureDesc().sType);
if (blobApiVersion)
featureFilledFromBlob = (apiVersion >= blobApiVersion);
}
if (featureFilledFromBlob)
featuresToFillFromBlob.push_back(p);
else
{
VkStructureType structType = p->getFeatureDesc().sType;
void* rawStructPtr = p->getFeatureTypeRaw();
if (structType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_FEATURES_EXT)
robustness2Features = reinterpret_cast<VkPhysicalDeviceRobustness2FeaturesEXT*>(rawStructPtr);
else if (structType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_ROBUSTNESS_FEATURES_EXT)
imageRobustnessFeatures = reinterpret_cast<VkPhysicalDeviceImageRobustnessFeaturesEXT*>(rawStructPtr);
else if (structType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADING_RATE_FEATURES_KHR)
fragmentShadingRateFeatures = reinterpret_cast<VkPhysicalDeviceFragmentShadingRateFeaturesKHR*>(rawStructPtr);
else if (structType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADING_RATE_IMAGE_FEATURES_NV)
shadingRateImageFeatures = reinterpret_cast<VkPhysicalDeviceShadingRateImageFeaturesNV*>(rawStructPtr);
else if (structType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_DENSITY_MAP_FEATURES_EXT)
fragmentDensityMapFeatures = reinterpret_cast<VkPhysicalDeviceFragmentDensityMapFeaturesEXT*>(rawStructPtr);
else if (structType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PAGEABLE_DEVICE_LOCAL_MEMORY_FEATURES_EXT)
pageableDeviceLocalMemoryFeatures = reinterpret_cast<VkPhysicalDevicePageableDeviceLocalMemoryFeaturesEXT*>(rawStructPtr);
// add to chain
*nextPtr = rawStructPtr;
nextPtr = p->getFeatureTypeNext();
}
m_features.push_back(p);
}
}
vki.getPhysicalDeviceFeatures2(physicalDevice, &m_coreFeatures2);
// fill data from VkPhysicalDeviceVulkan1{1,2,3}Features
if (vk12Supported)
{
AllFeaturesBlobs allBlobs =
{
m_vulkan11Features,
m_vulkan12Features,
m_vulkan13Features,
// add blobs from future vulkan versions here
};
for (auto feature : featuresToFillFromBlob)
feature->initializeFeatureFromBlob(allBlobs);
}
}
else
m_coreFeatures2.features = getPhysicalDeviceFeatures(vki, physicalDevice);
// 'enableAllFeatures' is used to create a complete list of supported features.
if (!enableAllFeatures)
{
// Disable robustness by default, as it has an impact on performance on some HW.
if (robustness2Features)
{
robustness2Features->robustBufferAccess2 = false;
robustness2Features->robustImageAccess2 = false;
robustness2Features->nullDescriptor = false;
}
if (imageRobustnessFeatures)
{
imageRobustnessFeatures->robustImageAccess = false;
}
m_coreFeatures2.features.robustBufferAccess = false;
// Disable VK_EXT_fragment_density_map and VK_NV_shading_rate_image features
// that must: not be enabled if KHR fragment shading rate features are enabled.
if (fragmentShadingRateFeatures &&
(fragmentShadingRateFeatures->pipelineFragmentShadingRate ||
fragmentShadingRateFeatures->primitiveFragmentShadingRate ||
fragmentShadingRateFeatures->attachmentFragmentShadingRate))
{
if (shadingRateImageFeatures)
shadingRateImageFeatures->shadingRateImage = false;
if (fragmentDensityMapFeatures)
fragmentDensityMapFeatures->fragmentDensityMap = false;
}
// Disable pageableDeviceLocalMemory by default since it may modify the behavior
// of device-local, and even host-local, memory allocations for all tests.
// pageableDeviceLocalMemory will use targetted testing on a custom device.
if (pageableDeviceLocalMemoryFeatures)
pageableDeviceLocalMemoryFeatures->pageableDeviceLocalMemory = false;
}
}
bool DeviceFeatures::verifyFeatureAddCriteria (const FeatureStructCreationData& item, const std::vector<VkExtensionProperties>& properties)
{
if (deStringEqual(item.name, VK_KHR_VULKAN_MEMORY_MODEL_EXTENSION_NAME))
{
for (const auto& property : properties)
{
if (deStringEqual(property.extensionName, item.name))
return (property.specVersion == item.specVersion);
}
}
return true;
}
bool DeviceFeatures::contains (const std::string& feature, bool throwIfNotExists) const
{
for (const auto f : m_features)
{
if (deStringEqual(f->getFeatureDesc().name, feature.c_str()))
return true;
}
if (throwIfNotExists)
TCU_THROW(NotSupportedError, "Feature " + feature + " is not supported");
return false;
}
bool DeviceFeatures::isDeviceFeatureInitialized (VkStructureType sType) const
{
for (const auto f : m_features)
{
if (f->getFeatureDesc().sType == sType)
return true;
}
return false;
}
DeviceFeatures::~DeviceFeatures (void)
{
for (auto p : m_features)
delete p;
m_features.clear();
}
} // vk
<|endoftext|>
|
<commit_before>/***************************************************************************
adash@cern.ch - last modified on 03/04/2013
// General macro to configure the RSN analysis task.
// It calls all configs desired by the user, by means
// of the boolean switches defined in the first lines.
// ---
// Inputs:
// 1) flag to know if running on MC or data
// 2) path where all configs are stored
// ---
// Returns:
// kTRUE --> initialization successful
// kFALSE --> initialization failed (some config gave errors)
//
****************************************************************************/
AliRsnMiniAnalysisTask * AddTaskPhiPP5TeV
(
Bool_t isMC = kFALSE,
Bool_t isPP = kTRUE,
Int_t Strcut = 2011,
TString outNameSuffix = "tpc2s",
Int_t customQualityCutsID = AliRsnCutSetDaughterParticle::kDisableCustom,
AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutKaCandidate=AliRsnCutSetDaughterParticle::kFastTPCpidNsigma,
Float_t nsigmaK = 3.0,
Bool_t enableMonitor = kTRUE,
Int_t nmix = 5,
Float_t maxDiffVzMix = 1.0,
Float_t maxDiffMultMix = 5.0
)
{
UInt_t triggerMask = AliVEvent::kINT7;
Bool_t rejectPileUp = kTRUE;
Double_t vtxZcut = 10.0;//cm, default cut on vtx z
if(!isPP || isMC) rejectPileUp = kFALSE;
//
// -- INITIALIZATION ----------------------------------------------------------------------------
// retrieve analysis manager
//
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskPhiPP5TeV", "No analysis manager to connect to.");
return NULL;
}
// create the task and configure
TString taskName = Form("TPCPhiMeson%s%s", (isPP? "pp" : "PbPb"), (isMC ? "MC" : "Data"));
AliRsnMiniAnalysisTask *task = new AliRsnMiniAnalysisTask(taskName.Data(), isMC);
//task->SelectCollisionCandidates(AliVEvent::kMB);
//task->UseESDTriggerMask(AliVEvent::kINT7);
task->UseESDTriggerMask(triggerMask);
if (isPP)
task->UseMultiplicity("QUALITY");
else
task->UseCentrality("V0M");
// set event mixing options
task->UseContinuousMix();
//task->UseBinnedMix();
task->SetNMix(nmix);
task->SetMaxDiffVz(maxDiffVzMix);
task->SetMaxDiffMult(maxDiffMultMix);
task->UseMC(isMC);
::Info("AddTaskPhiPP5TeV", Form("Event mixing configuration: \n events to mix = %i \n max diff. vtxZ = cm %5.3f \n max diff multi = %5.3f \n", nmix, maxDiffVzMix, maxDiffMultMix));
mgr->AddTask(task);
//
// -- EVENT CUTS (same for all configs) ---------------------------------------------------------
//
// cut on primary vertex:
// - 2nd argument --> |Vz| range
// - 3rd argument --> minimum required number of contributors
// - 4th argument --> tells if TPC stand-alone vertexes must be accepted
AliRsnCutPrimaryVertex *cutVertex = new AliRsnCutPrimaryVertex("cutVertex", 10.0, 0, kFALSE);
if (isPP && (!isMC)) cutVertex->SetCheckPileUp(rejectPileUp); // set the check for pileup
cutVertex->SetCheckZResolutionSPD();
cutVertex->SetCheckDispersionSPD();
cutVertex->SetCheckZDifferenceSPDTrack();
AliRsnCutEventUtils* cutEventUtils=new AliRsnCutEventUtils("cutEventUtils",kTRUE,rejectPileUp);
cutEventUtils->SetCheckIncompleteDAQ();
cutEventUtils->SetCheckSPDClusterVsTrackletBG();
// define and fill cut set for event cut
AliRsnCutSet *eventCuts = new AliRsnCutSet("eventCuts", AliRsnTarget::kEvent);
eventCuts->AddCut(cutEventUtils);
eventCuts->AddCut(cutVertex);
eventCuts->SetCutScheme(Form("%s&%s",cutEventUtils->GetName(),cutVertex->GetName()));
// set cuts in task
task->SetEventCuts(eventCuts);
// set cuts in task
task->SetEventCuts(eventCuts);
//
// -- EVENT-ONLY COMPUTATIONS -------------------------------------------------------------------
//
//vertex
Int_t vtxID = task->CreateValue(AliRsnMiniValue::kVz, kFALSE);
AliRsnMiniOutput *outVtx = task->CreateOutput("eventVtx", "HIST", "EVENT");
outVtx->AddAxis(vtxID, 400, -20.0, 20.0);
//multiplicity or centrality
Int_t multID = task->CreateValue(AliRsnMiniValue::kMult, kFALSE);
AliRsnMiniOutput *outMult = task->CreateOutput("eventMult", "HIST", "EVENT");
if (isPP)
outMult->AddAxis(multID, 400, 0.0, 400.0);
else
outMult->AddAxis(multID, 100, 0.0, 100.0);
//
// -- PAIR CUTS (common to all resonances) ------------------------------------------------------
//
AliRsnCutMiniPair *cutY = new AliRsnCutMiniPair("cutRapidity", AliRsnCutMiniPair::kRapidityRange);
cutY->SetRangeD(-0.5, 0.5);
AliRsnCutSet *cutsPair = new AliRsnCutSet("pairCuts", AliRsnTarget::kMother);
cutsPair->AddCut(cutY);
cutsPair->SetCutScheme(cutY->GetName());
//
// -- CONFIG ANALYSIS --------------------------------------------------------------------------
//
gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigPhiPP5TeV.C");
if (!ConfigPhiPP5TeV(task, isMC, isPP, "", cutsPair, Strcut, customQualityCutsID,cutKaCandidate,nsigmaK, enableMonitor)) return 0x0;
//
// -- CONTAINERS --------------------------------------------------------------------------------
//
TString outputFileName = AliAnalysisManager::GetCommonFileName();
// outputFileName += ":Rsn";
Printf("AddTaskPhiPP5TeV - Set OutputFileName : \n %s\n", outputFileName.Data() );
AliAnalysisDataContainer *output = mgr->CreateContainer(Form("RsnOut_%s",outNameSuffix.Data()),
TList::Class(),
AliAnalysisManager::kOutputContainer,
outputFileName);
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 1, output);
return task;
}
<commit_msg>Add event cuts for phi analysis in pp at 5 TeV<commit_after>/***************************************************************************
adash@cern.ch - last modified on 03/04/2013
last modification by rsingh@cern.ch 30/04/2017
// General macro to configure the RSN analysis task.
// It calls all configs desired by the user, by means
// of the boolean switches defined in the first lines.
// ---
// Inputs:
// 1) flag to know if running on MC or data
// 2) path where all configs are stored
// ---
// Returns:
// kTRUE --> initialization successful
// kFALSE --> initialization failed (some config gave errors)
//
****************************************************************************/
AliRsnMiniAnalysisTask * AddTaskPhiPP5TeV
(
Bool_t isMC = kFALSE,
Bool_t isPP = kTRUE,
Int_t Strcut = 2011,
TString outNameSuffix = "tpc2s",
Int_t customQualityCutsID = AliRsnCutSetDaughterParticle::kDisableCustom,
AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutKaCandidate=AliRsnCutSetDaughterParticle::kFastTPCpidNsigma,
Float_t nsigmaK = 3.0,
Bool_t enableMonitor = kTRUE,
Int_t nmix = 5,
Float_t maxDiffVzMix = 1.0,
Float_t maxDiffMultMix = 5.0
)
{
UInt_t triggerMask = AliVEvent::kINT7;
Bool_t rejectPileUp = kTRUE;
Double_t vtxZcut = 10.0;//cm, default cut on vtx z
if(!isPP || isMC) rejectPileUp = kFALSE;
//
// -- INITIALIZATION ----------------------------------------------------------------------------
// retrieve analysis manager
//
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskPhiPP5TeV", "No analysis manager to connect to.");
return NULL;
}
// create the task and configure
TString taskName = Form("TPCPhiMeson%s%s", (isPP? "pp" : "PbPb"), (isMC ? "MC" : "Data"));
AliRsnMiniAnalysisTask *task = new AliRsnMiniAnalysisTask(taskName.Data(), isMC);
//task->SelectCollisionCandidates(AliVEvent::kMB);
//task->UseESDTriggerMask(AliVEvent::kINT7);
task->UseESDTriggerMask(triggerMask);
if (isPP)
task->UseMultiplicity("QUALITY");
else
task->UseCentrality("V0M");
// set event mixing options
task->UseContinuousMix();
//task->UseBinnedMix();
task->SetNMix(nmix);
task->SetMaxDiffVz(maxDiffVzMix);
task->SetMaxDiffMult(maxDiffMultMix);
task->UseMC(isMC);
::Info("AddTaskPhiPP5TeV", Form("Event mixing configuration: \n events to mix = %i \n max diff. vtxZ = cm %5.3f \n max diff multi = %5.3f \n", nmix, maxDiffVzMix, maxDiffMultMix));
mgr->AddTask(task);
//
// -- EVENT CUTS (same for all configs) ---------------------------------------------------------
//
// cut on primary vertex:
// - 2nd argument --> |Vz| range
// - 3rd argument --> minimum required number of contributors
// - 4th argument --> tells if TPC stand-alone vertexes must be accepted
AliRsnCutPrimaryVertex *cutVertex = new AliRsnCutPrimaryVertex("cutVertex", 10.0, 0, kFALSE);
if (isPP && (!isMC)) cutVertex->SetCheckPileUp(rejectPileUp); // set the check for pileup
cutVertex->SetCheckZResolutionSPD();
cutVertex->SetCheckDispersionSPD();
cutVertex->SetCheckZDifferenceSPDTrack();
AliRsnCutEventUtils* cutEventUtils=new AliRsnCutEventUtils("cutEventUtils",kTRUE,rejectPileUp);
cutEventUtils->SetCheckIncompleteDAQ();
cutEventUtils->SetCheckSPDClusterVsTrackletBG();
// define and fill cut set for event cut
AliRsnCutSet *eventCuts = new AliRsnCutSet("eventCuts", AliRsnTarget::kEvent);
eventCuts->AddCut(cutEventUtils);
eventCuts->AddCut(cutVertex);
eventCuts->SetCutScheme(Form("%s&%s",cutEventUtils->GetName(),cutVertex->GetName()));
// set cuts in task
task->SetEventCuts(eventCuts);
//
// -- EVENT-ONLY COMPUTATIONS -------------------------------------------------------------------
//
//vertex
Int_t vtxID = task->CreateValue(AliRsnMiniValue::kVz, kFALSE);
AliRsnMiniOutput *outVtx = task->CreateOutput("eventVtx", "HIST", "EVENT");
outVtx->AddAxis(vtxID, 400, -20.0, 20.0);
//multiplicity or centrality
Int_t multID = task->CreateValue(AliRsnMiniValue::kMult, kFALSE);
AliRsnMiniOutput *outMult = task->CreateOutput("eventMult", "HIST", "EVENT");
if (isPP)
outMult->AddAxis(multID, 400, 0.0, 400.0);
else
outMult->AddAxis(multID, 100, 0.0, 100.0);
//
// -- PAIR CUTS (common to all resonances) ------------------------------------------------------
//
AliRsnCutMiniPair *cutY = new AliRsnCutMiniPair("cutRapidity", AliRsnCutMiniPair::kRapidityRange);
cutY->SetRangeD(-0.5, 0.5);
AliRsnCutSet *cutsPair = new AliRsnCutSet("pairCuts", AliRsnTarget::kMother);
cutsPair->AddCut(cutY);
cutsPair->SetCutScheme(cutY->GetName());
//
// -- CONFIG ANALYSIS --------------------------------------------------------------------------
//
gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigPhiPP5TeV.C");
if (!ConfigPhiPP5TeV(task, isMC, isPP, "", cutsPair, Strcut, customQualityCutsID,cutKaCandidate,nsigmaK, enableMonitor)) return 0x0;
//
// -- CONTAINERS --------------------------------------------------------------------------------
//
TString outputFileName = AliAnalysisManager::GetCommonFileName();
// outputFileName += ":Rsn";
Printf("AddTaskPhiPP5TeV - Set OutputFileName : \n %s\n", outputFileName.Data() );
AliAnalysisDataContainer *output = mgr->CreateContainer(Form("RsnOut_%s",outNameSuffix.Data()),
TList::Class(),
AliAnalysisManager::kOutputContainer,
outputFileName);
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 1, output);
return task;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2016, Egor Pugin
* 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 "common.h"
#include "command.h"
#include "stamp.h"
#include <boost/algorithm/string.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <fstream>
#include <random>
#include <regex>
#ifdef WIN32
#include <windows.h>
#endif
#ifdef __APPLE__
#include <libproc.h>
#include <unistd.h>
#endif
String get_program_version()
{
String s;
s +=
std::to_string(VERSION_MAJOR) + "." +
std::to_string(VERSION_MINOR) + "." +
std::to_string(VERSION_PATCH);
return s;
}
String get_program_version_string(const String &prog_name)
{
auto t = static_cast<time_t>(std::stoll(cppan_stamp));
auto tm = localtime(&t);
std::ostringstream ss;
ss << prog_name << " version " << get_program_version() << "\n" <<
"assembled " << std::put_time(tm, "%F %T");
return ss.str();
}
path get_program()
{
#ifdef _WIN32
WCHAR fn[8192] = { 0 };
GetModuleFileNameW(NULL, fn, sizeof(fn) * sizeof(WCHAR));
return fn;
#elif __APPLE__
auto pid = getpid();
char dest[PROC_PIDPATHINFO_MAXSIZE] = { 0 };
auto ret = proc_pidpath(pid, dest, sizeof(dest));
if (ret <= 0)
throw std::runtime_error("Cannot get program path");
return dest;
#else
char dest[PATH_MAX];
if (readlink("/proc/self/exe", dest, PATH_MAX) == -1)
{
perror("readlink");
throw std::runtime_error("Cannot get program path");
}
return dest;
#endif
}
Strings split_string(const String &s, const String &delims)
{
std::vector<String> v, lines;
boost::split(v, s, boost::is_any_of(delims));
for (auto &l : v)
{
boost::trim(l);
if (!l.empty())
lines.push_back(l);
}
return lines;
}
Strings split_lines(const String &s)
{
return split_string(s, "\r\n");
}
String get_cmake_version()
{
static const auto err = "Cannot get cmake version";
static const std::regex r("cmake version (\\S+)");
auto ret = command::execute_and_capture({ "cmake", "--version" });
if (ret.rc != 0)
throw std::runtime_error(err);
std::smatch m;
if (std::regex_search(ret.out, m, r))
{
if (m[0].first != ret.out.begin())
throw std::runtime_error(err);
return m[1].str();
}
throw std::runtime_error(err);
}
int get_end_of_string_block(const String &s, int i)
{
auto c = s[i - 1];
int n_curly = c == '(';
int n_square = c == '[';
int n_quotes = c == '\"';
auto sz = (int)s.size();
while ((n_curly > 0 || n_square > 0 || n_quotes > 0) && i < sz)
{
c = s[i];
if (c == '\"')
{
if (n_quotes == 0)
i = get_end_of_string_block(s.c_str(), i + 1) - 1;
else if (s[i - 1] == '\\')
;
else
n_quotes--;
}
else
{
switch (c)
{
case '(':
case '[':
i = get_end_of_string_block(s.c_str(), i + 1) - 1;
break;
case ')':
n_curly--;
break;
case ']':
n_square--;
break;
}
}
i++;
}
return i;
}
<commit_msg>Fix resolving current prog name.<commit_after>/*
* Copyright (c) 2016, Egor Pugin
* 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 "common.h"
#include "command.h"
#include "stamp.h"
#include <boost/algorithm/string.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <fstream>
#include <random>
#include <regex>
#ifdef WIN32
#include <windows.h>
#endif
#ifdef __APPLE__
#include <libproc.h>
#include <unistd.h>
#endif
String get_program_version()
{
String s;
s +=
std::to_string(VERSION_MAJOR) + "." +
std::to_string(VERSION_MINOR) + "." +
std::to_string(VERSION_PATCH);
return s;
}
String get_program_version_string(const String &prog_name)
{
auto t = static_cast<time_t>(std::stoll(cppan_stamp));
auto tm = localtime(&t);
std::ostringstream ss;
ss << prog_name << " version " << get_program_version() << "\n" <<
"assembled " << std::put_time(tm, "%F %T");
return ss.str();
}
path get_program()
{
#ifdef _WIN32
WCHAR fn[8192] = { 0 };
GetModuleFileNameW(NULL, fn, sizeof(fn) * sizeof(WCHAR));
return fn;
#elif __APPLE__
auto pid = getpid();
char dest[PROC_PIDPATHINFO_MAXSIZE] = { 0 };
auto ret = proc_pidpath(pid, dest, sizeof(dest));
if (ret <= 0)
throw std::runtime_error("Cannot get program path");
return dest;
#else
char dest[PATH_MAX] = { 0 };
if (readlink("/proc/self/exe", dest, PATH_MAX) == -1)
{
perror("readlink");
throw std::runtime_error("Cannot get program path");
}
return dest;
#endif
}
Strings split_string(const String &s, const String &delims)
{
std::vector<String> v, lines;
boost::split(v, s, boost::is_any_of(delims));
for (auto &l : v)
{
boost::trim(l);
if (!l.empty())
lines.push_back(l);
}
return lines;
}
Strings split_lines(const String &s)
{
return split_string(s, "\r\n");
}
String get_cmake_version()
{
static const auto err = "Cannot get cmake version";
static const std::regex r("cmake version (\\S+)");
auto ret = command::execute_and_capture({ "cmake", "--version" });
if (ret.rc != 0)
throw std::runtime_error(err);
std::smatch m;
if (std::regex_search(ret.out, m, r))
{
if (m[0].first != ret.out.begin())
throw std::runtime_error(err);
return m[1].str();
}
throw std::runtime_error(err);
}
int get_end_of_string_block(const String &s, int i)
{
auto c = s[i - 1];
int n_curly = c == '(';
int n_square = c == '[';
int n_quotes = c == '\"';
auto sz = (int)s.size();
while ((n_curly > 0 || n_square > 0 || n_quotes > 0) && i < sz)
{
c = s[i];
if (c == '\"')
{
if (n_quotes == 0)
i = get_end_of_string_block(s.c_str(), i + 1) - 1;
else if (s[i - 1] == '\\')
;
else
n_quotes--;
}
else
{
switch (c)
{
case '(':
case '[':
i = get_end_of_string_block(s.c_str(), i + 1) - 1;
break;
case ')':
n_curly--;
break;
case ']':
n_square--;
break;
}
}
i++;
}
return i;
}
<|endoftext|>
|
<commit_before>#pragma once
#include "pch.hpp"
namespace Plang
{
class Construct;
template <class T>
class Reference
{
public:
inline Reference() : count(nullptr), ptr(nullptr) { }
inline Reference(const T& Value) : count(new size_t(1)), ptr(new T(Value)) { }
inline Reference(const Reference& Ref) : count(Ref.count), ptr(Ref.ptr) { AddRef(); }
inline Reference(Reference&& Ref) : count(Ref.count), ptr(Ref.ptr) { Ref.ptr = nullptr; Ref.count = nullptr; }
inline Reference& operator = (const Reference& Ref)
{
if (ptr != Ref.ptr)
{
FreeRef();
ptr = Ref.ptr;
count = Ref.count;
AddRef();
}
return *this;
}
inline Reference& operator = (Reference&& Ref)
{
if (ptr != Ref.ptr)
{
FreeRef();
ptr = Ref.ptr;
count = Ref.count;
Ref.ptr = nullptr;
Ref.count = nullptr;
}
return *this;
}
inline ~Reference()
{
FreeRef();
}
inline T& operator *() { return *ptr; }
inline const T& operator *() const { return *ptr; }
inline T* operator ->() { return ptr; }
inline const T* operator ->() const { return ptr; }
inline size_t RefCount() const { return *count; }
template <class U>
inline operator Reference<U>() noexcept
{
Reference<U> u;
u.ptr = static_cast<U*>(ptr);
u.count = count;
u.AddRef();
return u;
}
protected:
//assumes reference is not nullptr
inline void AddRef() { if (count != nullptr) (*count)++; }
inline void FreeRef()
{
if (count != nullptr && ptr != nullptr && --(*count) < 1)
{
delete ptr;
ptr = nullptr;
delete count;
count = nullptr;
}
}
size_t* count;
T* ptr;
template <typename>
friend class Reference;
};
using AnyRef = Reference<Construct>;
static AnyRef Undefined;
static AnyRef Null;
};<commit_msg>add null type to ref<commit_after>#pragma once
#include "pch.hpp"
namespace Plang
{
class Construct;
template <class T>
class Reference
{
public:
inline Reference() : count(nullptr), ptr(nullptr) { }
inline Reference(const nullptr_t& Null) : count(nullptr), ptr(nullptr) { }
inline Reference(const T& Value) : count(new size_t(1)), ptr(new T(Value)) { }
inline Reference(const Reference& Ref) : count(Ref.count), ptr(Ref.ptr) { AddRef(); }
inline Reference(Reference&& Ref) : count(Ref.count), ptr(Ref.ptr) { Ref.ptr = nullptr; Ref.count = nullptr; }
inline Reference& operator = (const Reference& Ref)
{
if (ptr != Ref.ptr)
{
FreeRef();
ptr = Ref.ptr;
count = Ref.count;
AddRef();
}
return *this;
}
inline Reference& operator = (Reference&& Ref)
{
if (ptr != Ref.ptr)
{
FreeRef();
ptr = Ref.ptr;
count = Ref.count;
Ref.ptr = nullptr;
Ref.count = nullptr;
}
return *this;
}
inline ~Reference()
{
FreeRef();
}
inline T& operator *() { return *ptr; }
inline const T& operator *() const { return *ptr; }
inline T* operator ->() { return ptr; }
inline const T* operator ->() const { return ptr; }
inline size_t RefCount() const { return *count; }
template <class U>
inline operator Reference<U>() noexcept
{
Reference<U> u;
u.ptr = static_cast<U*>(ptr);
u.count = count;
u.AddRef();
return u;
}
protected:
//assumes reference is not nullptr
inline void AddRef() { if (count != nullptr) (*count)++; }
inline void FreeRef()
{
if (count != nullptr && ptr != nullptr && --(*count) < 1)
{
delete ptr;
ptr = nullptr;
delete count;
count = nullptr;
}
}
size_t* count;
T* ptr;
template <typename>
friend class Reference;
};
using AnyRef = Reference<Construct>;
static AnyRef Undefined;
static AnyRef Null;
};<|endoftext|>
|
<commit_before>// Copyright 2022 Google LLC
//
// 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 <cstdio>
#include <memory>
#if defined(CURL_ETHERNET)
#include "libs/base/ethernet.h"
#elif defined(CURL_WIFI)
#include "libs/base/wifi.h"
#endif
#include "libs/base/check.h"
#include "libs/base/gpio.h"
#include "third_party/freertos_kernel/include/FreeRTOS.h"
#include "third_party/freertos_kernel/include/task.h"
#include "third_party/nxp/rt1176-sdk/middleware/lwip/src/include/lwip/dns.h"
#include "third_party/nxp/rt1176-sdk/middleware/lwip/src/include/lwip/tcpip.h"
/* clang-format off */
#include "libs/curl/curl.h"
/* clang-format on */
// Demonstrates how to connect to the internet using either Wi-Fi or ethernet.
// Be sure you have either the Coral Wireless Add-on Board or PoE Add-on Board
// connected.
//
// When flashing this example, you must specify the "subapp" module name for
// the flashtool, which you can see in the local CMakeLists.txt file.
// For example, here's how to flash the Wi-Fi version of this example:
/*
python3 scripts/flashtool.py -b build -e curl --subapp curl_wifi \
--wifi_ssid network-name --wifi_psk network-password
*/
namespace coralmicro {
namespace {
struct DnsCallbackArg {
SemaphoreHandle_t sema;
const char* hostname;
ip_addr_t* ip_addr;
};
size_t curl_writefunction(void* contents, size_t size, size_t nmemb,
void* param) {
size_t* bytes_curled = reinterpret_cast<size_t*>(param);
*bytes_curled = *bytes_curled + (size * nmemb);
return size * nmemb;
}
void CURLRequest(const char* url) {
CURL* curl;
CURLcode res;
curl = curl_easy_init();
printf("Curling %s\r\n", url);
if (curl) {
size_t bytes_curled = 0;
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 0);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &bytes_curled);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_writefunction);
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
printf("curl_easy_perform failed: %s\r\n", curl_easy_strerror(res));
} else {
printf("Curling of %s successful! (%d bytes curled)\r\n", url,
bytes_curled);
}
curl_easy_cleanup(curl);
}
}
bool PerformDnsLookup(const char* hostname, ip_addr_t* addr) {
DnsCallbackArg dns_arg;
dns_arg.ip_addr = addr;
dns_arg.sema = xSemaphoreCreateBinary();
dns_arg.hostname = hostname;
tcpip_callback(
[](void* ctx) {
DnsCallbackArg* dns_arg = static_cast<DnsCallbackArg*>(ctx);
dns_gethostbyname(
dns_arg->hostname, dns_arg->ip_addr,
[](const char* name, const ip_addr_t* ipaddr, void* callback_arg) {
DnsCallbackArg* dns_arg =
reinterpret_cast<DnsCallbackArg*>(callback_arg);
if (ipaddr) {
memcpy(dns_arg->ip_addr, ipaddr, sizeof(*ipaddr));
}
xSemaphoreGive(dns_arg->sema);
},
dns_arg);
},
&dns_arg);
xSemaphoreTake(dns_arg.sema, portMAX_DELAY);
vSemaphoreDelete(dns_arg.sema);
return true;
}
void Main() {
std::optional<std::string> our_ip_addr = std::nullopt;
#if defined(CURL_ETHERNET)
printf("Attempting to use ethernet...\r\n");
CHECK(coralmicro::EthernetInit(/*default_iface=*/true));
our_ip_addr = coralmicro::EthernetGetIp();
#elif defined(CURL_WIFI)
printf("Attempting to use Wi-Fi...\r\n");
// Uncomment me to use the external antenna.
// coralmicro::SetWiFiAntenna(coralmicro::WiFiAntenna::kExternal);
bool success = false;
success = coralmicro::WiFiTurnOn();
if (!success) {
printf("Failed to turn on Wi-Fi\r\n");
return;
}
success = coralmicro::WiFiConnect();
if (!success) {
printf("Failed to connect to Wi-Fi\r\n");
return;
}
printf("Wi-Fi connected\r\n");
our_ip_addr = coralmicro::WiFiGetIp();
#endif
if (our_ip_addr.has_value()) {
printf("DHCP succeeded, our IP is %s.\r\n", our_ip_addr.value().c_str());
} else {
printf("We didn't get an IP via DHCP, not progressing further.\r\n");
return;
}
const char* hostname = "www.example.com";
ip_addr_t dns_ip_addr;
PerformDnsLookup(hostname, &dns_ip_addr);
printf("%s -> %s\r\n", hostname, ipaddr_ntoa(&dns_ip_addr));
curl_global_init(CURL_GLOBAL_ALL);
const char* uri_fmt = "http://%s:80/";
int size = snprintf(nullptr, 0, uri_fmt, hostname);
auto uri = std::make_unique<char>(size + 1);
snprintf(uri.get(), size + 1, uri_fmt, hostname);
CURLRequest(uri.get());
curl_global_cleanup();
printf("Done.\r\n");
vTaskSuspend(nullptr);
}
} // namespace
} // namespace coralmicro
extern "C" void app_main(void* param) {
(void)param;
coralmicro::Main();
vTaskSuspend(nullptr);
}
<commit_msg>Cleanup Curl example<commit_after>// Copyright 2022 Google LLC
//
// 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 <cstdio>
#include <memory>
#if defined(CURL_ETHERNET)
#include "libs/base/ethernet.h"
#elif defined(CURL_WIFI)
#include "libs/base/wifi.h"
#endif
#include "libs/base/check.h"
#include "libs/base/gpio.h"
#include "libs/base/strings.h"
#include "third_party/freertos_kernel/include/FreeRTOS.h"
#include "third_party/freertos_kernel/include/task.h"
#include "third_party/nxp/rt1176-sdk/middleware/lwip/src/include/lwip/dns.h"
#include "third_party/nxp/rt1176-sdk/middleware/lwip/src/include/lwip/tcpip.h"
/* clang-format off */
#include "libs/curl/curl.h"
/* clang-format on */
// Demonstrates how to connect to the internet using either Wi-Fi or ethernet.
// Be sure you have either the Coral Wireless Add-on Board or PoE Add-on Board
// connected.
//
// When flashing this example, you must specify the "subapp" module name for
// the flashtool, which you can see in the local CMakeLists.txt file.
// For example, here's how to flash the Wi-Fi version of this example:
/*
python3 scripts/flashtool.py -b build -e curl --subapp curl_wifi \
--wifi_ssid network-name --wifi_psk network-password
*/
namespace coralmicro {
namespace {
struct DnsCallbackArg {
SemaphoreHandle_t sema;
const char* hostname;
ip_addr_t* ip_addr;
};
size_t CurlWrite(void* contents, size_t size, size_t nmemb, void* param) {
auto* bytes_curled = static_cast<size_t*>(param);
*bytes_curled += size * nmemb;
return size * nmemb;
}
void CurlRequest(const char* url) {
CURL* curl = curl_easy_init();
printf("Curling %s\r\n", url);
if (curl) {
size_t bytes_curled = 0;
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 0);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &bytes_curled);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWrite);
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK) {
printf("curl_easy_perform failed: %s\r\n", curl_easy_strerror(res));
} else {
printf("Curling of %s successful! (%d bytes curled)\r\n", url,
bytes_curled);
}
curl_easy_cleanup(curl);
}
}
void PerformDnsLookup(const char* hostname, ip_addr_t* addr) {
DnsCallbackArg arg;
arg.ip_addr = addr;
arg.sema = xSemaphoreCreateBinary();
arg.hostname = hostname;
CHECK(arg.sema);
tcpip_callback(
[](void* ctx) {
auto* arg = static_cast<DnsCallbackArg*>(ctx);
dns_gethostbyname(
arg->hostname, arg->ip_addr,
[](const char* name, const ip_addr_t* ipaddr, void* callback_arg) {
auto* arg = static_cast<DnsCallbackArg*>(callback_arg);
if (ipaddr != nullptr) {
ip4_addr_copy(*arg->ip_addr, *ipaddr);
}
CHECK(xSemaphoreGive(arg->sema) == pdTRUE);
},
arg);
},
&arg);
CHECK(xSemaphoreTake(arg.sema, portMAX_DELAY) == pdTRUE);
vSemaphoreDelete(arg.sema);
}
void Main() {
std::optional<std::string> our_ip_addr;
#if defined(CURL_ETHERNET)
printf("Attempting to use ethernet...\r\n");
CHECK(coralmicro::EthernetInit(/*default_iface=*/true));
our_ip_addr = coralmicro::EthernetGetIp();
#elif defined(CURL_WIFI)
printf("Attempting to use Wi-Fi...\r\n");
// Uncomment me to use the external antenna.
// coralmicro::SetWiFiAntenna(coralmicro::WiFiAntenna::kExternal);
bool success = coralmicro::WiFiTurnOn();
if (!success) {
printf("Failed to turn on Wi-Fi\r\n");
return;
}
success = coralmicro::WiFiConnect();
if (!success) {
printf("Failed to connect to Wi-Fi\r\n");
return;
}
printf("Wi-Fi connected\r\n");
our_ip_addr = coralmicro::WiFiGetIp();
#endif
if (our_ip_addr.has_value()) {
printf("DHCP succeeded, our IP is %s.\r\n", our_ip_addr.value().c_str());
} else {
printf("We didn't get an IP via DHCP, not progressing further.\r\n");
return;
}
const char* hostname = "www.example.com";
ip_addr_t dns_ip_addr;
ip4_addr_set_any(&dns_ip_addr);
PerformDnsLookup(hostname, &dns_ip_addr);
if (!ip4_addr_isany(&dns_ip_addr)) {
printf("%s -> %s\r\n", hostname, ipaddr_ntoa(&dns_ip_addr));
} else {
printf("Cannot resolve %s host name\r\n", hostname);
return;
}
curl_global_init(CURL_GLOBAL_ALL);
std::string uri;
StrAppend(&uri, "http://%s:80/", hostname);
CurlRequest(uri.c_str());
curl_global_cleanup();
printf("Done.\r\n");
}
} // namespace
} // namespace coralmicro
extern "C" void app_main(void* param) {
(void)param;
coralmicro::Main();
vTaskSuspend(nullptr);
}
<|endoftext|>
|
<commit_before>#pragma ident "$Id$"
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// any later version.
//
// The GPSTk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
// release, distribution is unlimited.
//
//=============================================================================
#include <EpochClockModel.hpp>
#include <vector>
#include <set>
#include "gps_constants.hpp"
#include "OrdApp.hpp"
#include "OrdApp.cpp"
#include "EphReader.hpp"
#include "BCEphemerisStore.hpp"
using namespace std;
using namespace gpstk;
using namespace gpstk::StringUtils;
class OrdEdit : public OrdApp
{
public:
OrdEdit() throw();
bool initialize(int argc, char *argv[]) throw();
protected:
virtual void process();
private:
CommandOptionNoArg clkOpt, noClockOpt;
CommandOptionWithNumberArg elvOpt, prnOpt, wartsOpt;
CommandOptionWithAnyArg ephSourceOpt, startOpt, endOpt, clkResOpt, ordLimitOpt;
double elMask, clkResidLimit, ordLimit;
set<int> prnSet, wartSet; // prns to exclude from analysis
vector<string> ephFilesVector;
DayTime tStart, tEnd;
};
//-----------------------------------------------------------------------------
// The constructor basically just sets up all the command line options
//-----------------------------------------------------------------------------
OrdEdit::OrdEdit() throw()
: OrdApp("ordEdit", "Edits an ord file based on various criteria."),
elMask(0),clkResidLimit(0),
ephSourceOpt('e',"be-file","Remove data for unhealthy SVs by "
"providing broadcast ephemeris source: RINEX nav or FIC file." ),
elvOpt('m',"elev","Remove data for SVs below a given elevation mask."),
clkOpt('k',"clock-est", "Remove ords that do not have corresponding "
"clock estimates."),
clkResOpt('s',"size","Remove clock residuals with absolute values "
"greater than this size (meters)."),
ordLimitOpt('l',"ord-limit","Remove ords with absolute valies "
"greater than this size (meters)."),
prnOpt('p',"PRN","Filter data by PRN number. Repeat option for multiple"
" satellites. Negative PRN numbers mean exclude these PRNs. "
"Positive PRN numbers mean only include these satellites. Zero "
"removes all."),
noClockOpt('c',"no-clock", "Remove all clock offset estimate warts. Give"
" this option twice to remove all clock data. "),
wartsOpt('w', "warts", "Include/Exclude warts from the indicated PRN. "
"Repeat option for multiple PRNs. Negative numbers exclude, "
"positive numbers include, zero excludes warts from all PRNs. "
"The default is to include all warts."),
startOpt('\0',"start","Throw out data before this time. Format as "
"string: \"MO/DD/YYYY HH:MM:SS\" "),
endOpt('\0',"end","Throw out data after this time. Format as string:"
" \"MO/DD/YYYY HH:MM:SS\" ")
{}
//-----------------------------------------------------------------------------
bool OrdEdit::initialize(int argc, char *argv[]) throw()
{
return OrdApp::initialize(argc,argv);
}
//-----------------------------------------------------------------------------
void OrdEdit::process()
{
//-- Get ephemeris data
EphReader ephReader;
ephReader.verboseLevel = verboseLevel;
for (int i=0; i<ephSourceOpt.getCount(); i++)
ephReader.read(ephSourceOpt.getValue()[i]);
gpstk::EphemerisStore& eph = *ephReader.eph;
//-- Make sure that the eph data provided is broadcast eph
if (ephSourceOpt.getCount()&&(typeid(eph)!=typeid(BCEphemerisStore)))
{
cout << "You provided an eph source that was not broadcast ephemeris.\n"
"(Precise ephemeris does not contain health info and can't be \n"
" used with this program.) Exiting... \n";
exit(0);
}
//-- get which PRNs to be excluded
bool excludePRNs = false;
bool includePRNs = false;
for (int index = 0; index < prnOpt.getCount(); index++)
{
int prn = asInt(prnOpt.getValue()[index]);
if (prn < 0)
excludePRNs = true;
else if (prn > 0)
includePRNs = true;
else
excludePRNs = true;
}
if (excludePRNs && includePRNs)
{
cout << "You PRN filtering arguments don't make sense.\n"
<< "Either filter by specifically excluding or \n"
<< "including, but not both. Exiting...\n";
exit(0);
}
else if (excludePRNs)
{
for (int index = 0; index < prnOpt.getCount(); index++)
{
int prn = asInt(prnOpt.getValue()[index]);
if (prn < 0)
prnSet.insert(-prn);
else if (prn == 0)
{
prnSet.clear();
for (int i=1; i<=gpstk::MAX_PRN; i++)
prnSet.insert(i);
}
}
}
else if (includePRNs)
{
set<int> includeSet;
for (int index = 0; index < prnOpt.getCount(); index++)
{
int prn = asInt(prnOpt.getValue()[index]);
includeSet.insert(prn);
}
prnSet.clear();
for (int i=1; i<=gpstk::MAX_PRN; i++)
{
set<int>::const_iterator iter = includeSet.find(i);
if (iter == includeSet.end())
prnSet.insert(i);
}
}
//-- get which PRNs from which to ignore warts
for (int i=0; i < wartsOpt.getCount(); i++)
{
int prn = asInt(wartsOpt.getValue()[i]);
if (prn < 0)
wartSet.insert(-prn);
else if (prn > 0)
wartSet.erase(prn);
else
{
wartSet.clear();
for (int i=1; i<=gpstk::MAX_PRN; i++)
wartSet.insert(i);
}
}
//-- get ephemeris sources, if given
int numBEFiles = ephSourceOpt.getCount();
for (int index = 0; index < numBEFiles; index++)
ephFilesVector.push_back(asString(ephSourceOpt.getValue()[index]));
//-- remove data below a given elevation mask?
if (elvOpt.getCount())
elMask = asDouble(elvOpt.getValue().front());
//-- discard clock residuals that are too large?
if (clkResOpt.getCount())
clkResidLimit = asDouble(clkResOpt.getValue().front());
//-- discard ords that are too large?
if (ordLimitOpt.getCount())
ordLimit = asDouble(ordLimitOpt.getValue().front());
//-- if a time span was specified, get it
double ss;
int mm,dd,yy,hh,minu;
if (startOpt.getCount())
{
sscanf(startOpt.getValue().front().c_str(),"%d/%d/%d %d:%d:%lf",
&mm,&dd,&yy,&hh,&minu,&ss);
tStart.setYMDHMS((short)yy,(short)mm,(short)dd,(short)hh,
(short)minu,(double)ss);
}
if (endOpt.getCount())
{
sscanf(endOpt.getValue().front().c_str(), "%d/%d/%d %d:%d:%lf",
&mm,&dd,&yy,&hh,&minu,&ss);
tEnd.setYMDHMS((short)yy,(short)mm,(short)dd,(short)hh,
(short)minu, (double)ss);
}
//-- too lazy?
if (verboseLevel || debugLevel)
{
cout << "# So, according to you, ordEdit should be... \n";
if (clkOpt.getCount())
cout << "# Removing ords that do not have corresponding "
<< "clock estimates.\n";
else
cout << "# Leaving in ords without corresponding clock "
<< "estimates.\n";
if (elMask)
cout << "# Elevation mask set to " << elMask << " deg.\n";
else
cout << "# Keeping data for all SVs above the horizon. \n";
if (startOpt.getCount())
cout << "# Tossing data before " << tStart << endl;
else
cout << "# Start time is beginning of file. \n";
if (endOpt.getCount())
cout << "# Tossing data after " << tEnd << endl;
else
cout << "# End time is end of file. \n";
if (prnSet.size())
{
cout << "# Ignoring ords from PRNs: ";
set<int>::const_iterator i;
if (prnSet.size() == gpstk::MAX_PRN)
cout << "all";
else
for (i = prnSet.begin(); i != prnSet.end(); i++)
cout << *i << " ";
cout << endl;
}
if (wartSet.size())
{
cout << "# Ignoring warts from PRNs: ";
set<int>::const_iterator i;
if (wartSet.size() == gpstk::MAX_PRN)
cout << "all";
else
for (i = wartSet.begin(); i != wartSet.end(); i++)
cout << *i << " ";
cout << endl;
}
if (clkResidLimit)
cout << "# Tossing clk resids > " << clkResidLimit << " m.\n";
else
cout << "# Keeping all clock residuals.\n";
if (ordLimit)
cout << "# Tossing ords > " << ordLimit << " m.\n";
else
cout << "# No ORD limit given.\n";
if (numBEFiles)
{
for (int index = 0; index < numBEFiles; index++)
cout << "# Eph source: " << ephSourceOpt.getValue()[index]
<< endl;
}
if (noClockOpt.getCount() == 1)
cout << "# Removing clock offset warts from ord file.\n";
else if (noClockOpt.getCount() > 1)
cout << "# Removing all clock data from ord file.\n";
}
while (input)
{
ORDEpoch ordEpoch = read(input);
if (clkOpt.getCount() && !(ordEpoch.clockOffset.is_valid()))
continue;
else if (startOpt.getCount() && (ordEpoch.time < tStart))
continue;
else if (endOpt.getCount() && (ordEpoch.time > tEnd))
continue;
if (numBEFiles)
{
const BCEphemerisStore& bce = dynamic_cast<const BCEphemerisStore&>(eph);
ORDEpoch::ORDMap::iterator iter = ordEpoch.ords.begin();
while (iter!= ordEpoch.ords.end())
{
const SatID& satId = iter->first;
ObsRngDev& ord = iter->second;
iter++;
try
{
const EngEphemeris& eph = bce.findEphemeris(satId, ordEpoch.time);
ord.health = eph.getHealth();
if (ord.health.is_valid() && ord.health != 0)
ordEpoch.removeORD(satId);
}
catch (gpstk::Exception &exc)
{ cout << " # Error caught in ordEdit - probably missing eph data\n"; }
}
}
if (elMask)
{
ORDEpoch::ORDMap::const_iterator iter = ordEpoch.ords.begin();
while (iter!= ordEpoch.ords.end())
{
const SatID& satId = iter->first;
const ObsRngDev& ord = iter->second;
iter++;
if ((ord.getElevation()< elMask))
ordEpoch.removeORD(satId);
}
}
if (noClockOpt.getCount() == 1)
{
// removing receiver clock offset estimate warts (type 70 lines)
if (ordEpoch.clockOffset.is_valid() && ordEpoch.wonky)
ordEpoch.clockOffset.set_valid(false);
}
else if (noClockOpt.getCount() > 1)
{
// removing all clock data (line types 50, 51, and 70)
ordEpoch.clockOffset.set_valid(false);
ordEpoch.clockResidual.set_valid(false);
}
if (prnSet.size() || wartSet.size())
{
// removing good obs (the type 0 lines)
ORDEpoch::ORDMap::const_iterator iter = ordEpoch.ords.begin();
while (iter!= ordEpoch.ords.end())
{
const SatID& satId = iter->first;
const ObsRngDev& ord = iter->second;
iter++;
if (prnSet.count(satId.id) ||
(ord.wonky && wartSet.count(satId.id)))
ordEpoch.removeORD(satId);
}
}
if (clkResOpt.getCount() &&
(std::abs(ordEpoch.clockResidual)>clkResidLimit))
ordEpoch.clockResidual.set_valid(false);
if (ordLimitOpt.getCount())
{
ORDEpoch::ORDMap::const_iterator iter = ordEpoch.ords.begin();
while (iter!= ordEpoch.ords.end())
{
const SatID& satId = iter->first;
const ObsRngDev& ord = iter->second;
iter++;
if (ord.getORD() < ordLimit)
ordEpoch.removeORD(satId);
}
}
write(output, ordEpoch);
}
if (verboseLevel || debugLevel)
cout << "# Doneskies.\n";
}
//-----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
try
{
OrdEdit crap;
if (!crap.initialize(argc, argv))
exit(0);
crap.run();
}
catch (gpstk::Exception &exc)
{ cout << exc << endl; }
catch (std::exception &exc)
{ cerr << "Caught std::exception " << exc.what() << endl; }
catch (...)
{ cerr << "Caught unknown exception" << endl; }
}
<commit_msg>Made the time format specifier match the default time format for the ord file<commit_after>#pragma ident "$Id$"
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// any later version.
//
// The GPSTk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
// release, distribution is unlimited.
//
//=============================================================================
#include <EpochClockModel.hpp>
#include <vector>
#include <set>
#include "gps_constants.hpp"
#include "OrdApp.hpp"
#include "OrdApp.cpp"
#include "EphReader.hpp"
#include "BCEphemerisStore.hpp"
using namespace std;
using namespace gpstk;
using namespace gpstk::StringUtils;
class OrdEdit : public OrdApp
{
public:
OrdEdit() throw();
bool initialize(int argc, char *argv[]) throw();
protected:
virtual void process();
private:
CommandOptionNoArg clkOpt, noClockOpt;
CommandOptionWithNumberArg elvOpt, prnOpt, wartsOpt;
CommandOptionWithAnyArg ephSourceOpt, startOpt, endOpt, clkResOpt, ordLimitOpt;
double elMask, clkResidLimit, ordLimit;
set<int> prnSet, wartSet; // prns to exclude from analysis
vector<string> ephFilesVector;
DayTime tStart, tEnd;
};
//-----------------------------------------------------------------------------
// The constructor basically just sets up all the command line options
//-----------------------------------------------------------------------------
OrdEdit::OrdEdit() throw()
: OrdApp("ordEdit", "Edits an ord file based on various criteria."),
elMask(0),clkResidLimit(0),
ephSourceOpt('e',"be-file","Remove data for unhealthy SVs by "
"providing broadcast ephemeris source: RINEX nav or FIC file." ),
elvOpt('m',"elev","Remove data for SVs below a given elevation mask."),
clkOpt('k',"clock-est", "Remove ords that do not have corresponding "
"clock estimates."),
clkResOpt('s',"size","Remove clock residuals with absolute values "
"greater than this size (meters)."),
ordLimitOpt('l',"ord-limit","Remove ords with absolute valies "
"greater than this size (meters)."),
prnOpt('p',"PRN","Filter data by PRN number. Repeat option for multiple"
" satellites. Negative PRN numbers mean exclude these PRNs. "
"Positive PRN numbers mean only include these satellites. Zero "
"removes all."),
noClockOpt('c',"no-clock", "Remove all clock offset estimate warts. Give"
" this option twice to remove all clock data. "),
wartsOpt('w', "warts", "Include/Exclude warts from the indicated PRN. "
"Repeat option for multiple PRNs. Negative numbers exclude, "
"positive numbers include, zero excludes warts from all PRNs. "
"The default is to include all warts."),
startOpt('\0',"start","Throw out data before this time. Format as "
"string: \"yyyy ddd HH:MM:SS\" "),
endOpt('\0',"end","Throw out data after this time. Format as string:"
" \"yyyy ddd HH:MM:SS\" ")
{}
//-----------------------------------------------------------------------------
bool OrdEdit::initialize(int argc, char *argv[]) throw()
{
return OrdApp::initialize(argc,argv);
}
//-----------------------------------------------------------------------------
void OrdEdit::process()
{
//-- Get ephemeris data
EphReader ephReader;
ephReader.verboseLevel = verboseLevel;
for (int i=0; i<ephSourceOpt.getCount(); i++)
ephReader.read(ephSourceOpt.getValue()[i]);
gpstk::EphemerisStore& eph = *ephReader.eph;
//-- Make sure that the eph data provided is broadcast eph
if (ephSourceOpt.getCount()&&(typeid(eph)!=typeid(BCEphemerisStore)))
{
cout << "You provided an eph source that was not broadcast ephemeris.\n"
"(Precise ephemeris does not contain health info and can't be \n"
" used with this program.) Exiting... \n";
exit(0);
}
//-- get which PRNs to be excluded
bool excludePRNs = false;
bool includePRNs = false;
for (int index = 0; index < prnOpt.getCount(); index++)
{
int prn = asInt(prnOpt.getValue()[index]);
if (prn < 0)
excludePRNs = true;
else if (prn > 0)
includePRNs = true;
else
excludePRNs = true;
}
if (excludePRNs && includePRNs)
{
cout << "You PRN filtering arguments don't make sense.\n"
<< "Either filter by specifically excluding or \n"
<< "including, but not both. Exiting...\n";
exit(0);
}
else if (excludePRNs)
{
for (int index = 0; index < prnOpt.getCount(); index++)
{
int prn = asInt(prnOpt.getValue()[index]);
if (prn < 0)
prnSet.insert(-prn);
else if (prn == 0)
{
prnSet.clear();
for (int i=1; i<=gpstk::MAX_PRN; i++)
prnSet.insert(i);
}
}
}
else if (includePRNs)
{
set<int> includeSet;
for (int index = 0; index < prnOpt.getCount(); index++)
{
int prn = asInt(prnOpt.getValue()[index]);
includeSet.insert(prn);
}
prnSet.clear();
for (int i=1; i<=gpstk::MAX_PRN; i++)
{
set<int>::const_iterator iter = includeSet.find(i);
if (iter == includeSet.end())
prnSet.insert(i);
}
}
//-- get which PRNs from which to ignore warts
for (int i=0; i < wartsOpt.getCount(); i++)
{
int prn = asInt(wartsOpt.getValue()[i]);
if (prn < 0)
wartSet.insert(-prn);
else if (prn > 0)
wartSet.erase(prn);
else
{
wartSet.clear();
for (int i=1; i<=gpstk::MAX_PRN; i++)
wartSet.insert(i);
}
}
//-- get ephemeris sources, if given
int numBEFiles = ephSourceOpt.getCount();
for (int index = 0; index < numBEFiles; index++)
ephFilesVector.push_back(asString(ephSourceOpt.getValue()[index]));
//-- remove data below a given elevation mask?
if (elvOpt.getCount())
elMask = asDouble(elvOpt.getValue().front());
//-- discard clock residuals that are too large?
if (clkResOpt.getCount())
clkResidLimit = asDouble(clkResOpt.getValue().front());
//-- discard ords that are too large?
if (ordLimitOpt.getCount())
ordLimit = asDouble(ordLimitOpt.getValue().front());
//-- if a time span was specified, get it
if (startOpt.getCount())
tStart.setToString(startOpt.getValue().front().c_str(),"%Y %j %H:%M:%S");
if (endOpt.getCount())
tEnd.setToString(endOpt.getValue().front().c_str(),"%Y %j %H:%M:%S");
//-- too lazy?
if (verboseLevel || debugLevel)
{
cout << "# So, according to you, ordEdit should be... \n";
if (clkOpt.getCount())
cout << "# Removing ords that do not have corresponding "
<< "clock estimates.\n";
else
cout << "# Leaving in ords without corresponding clock "
<< "estimates.\n";
if (elMask)
cout << "# Elevation mask set to " << elMask << " deg.\n";
else
cout << "# Keeping data for all SVs above the horizon. \n";
if (startOpt.getCount())
cout << "# Tossing data before " << tStart << endl;
else
cout << "# Start time is beginning of file. \n";
if (endOpt.getCount())
cout << "# Tossing data after " << tEnd << endl;
else
cout << "# End time is end of file. \n";
if (prnSet.size())
{
cout << "# Ignoring ords from PRNs: ";
set<int>::const_iterator i;
if (prnSet.size() == gpstk::MAX_PRN)
cout << "all";
else
for (i = prnSet.begin(); i != prnSet.end(); i++)
cout << *i << " ";
cout << endl;
}
if (wartSet.size())
{
cout << "# Ignoring warts from PRNs: ";
set<int>::const_iterator i;
if (wartSet.size() == gpstk::MAX_PRN)
cout << "all";
else
for (i = wartSet.begin(); i != wartSet.end(); i++)
cout << *i << " ";
cout << endl;
}
if (clkResidLimit)
cout << "# Tossing clk resids > " << clkResidLimit << " m.\n";
else
cout << "# Keeping all clock residuals.\n";
if (ordLimit)
cout << "# Tossing ords > " << ordLimit << " m.\n";
else
cout << "# No ORD limit given.\n";
if (numBEFiles)
{
for (int index = 0; index < numBEFiles; index++)
cout << "# Eph source: " << ephSourceOpt.getValue()[index]
<< endl;
}
if (noClockOpt.getCount() == 1)
cout << "# Removing clock offset warts from ord file.\n";
else if (noClockOpt.getCount() > 1)
cout << "# Removing all clock data from ord file.\n";
}
while (input)
{
ORDEpoch ordEpoch = read(input);
if (clkOpt.getCount() && !(ordEpoch.clockOffset.is_valid()))
continue;
else if (startOpt.getCount() && (ordEpoch.time < tStart))
continue;
else if (endOpt.getCount() && (ordEpoch.time > tEnd))
continue;
if (numBEFiles)
{
const BCEphemerisStore& bce = dynamic_cast<const BCEphemerisStore&>(eph);
ORDEpoch::ORDMap::iterator iter = ordEpoch.ords.begin();
while (iter!= ordEpoch.ords.end())
{
const SatID& satId = iter->first;
ObsRngDev& ord = iter->second;
iter++;
try
{
const EngEphemeris& eph = bce.findEphemeris(satId, ordEpoch.time);
ord.health = eph.getHealth();
if (ord.health.is_valid() && ord.health != 0)
ordEpoch.removeORD(satId);
}
catch (gpstk::Exception &exc)
{ cout << " # Error caught in ordEdit - probably missing eph data\n"; }
}
}
if (elMask)
{
ORDEpoch::ORDMap::const_iterator iter = ordEpoch.ords.begin();
while (iter!= ordEpoch.ords.end())
{
const SatID& satId = iter->first;
const ObsRngDev& ord = iter->second;
iter++;
if ((ord.getElevation()< elMask))
ordEpoch.removeORD(satId);
}
}
if (noClockOpt.getCount() == 1)
{
// removing receiver clock offset estimate warts (type 70 lines)
if (ordEpoch.clockOffset.is_valid() && ordEpoch.wonky)
ordEpoch.clockOffset.set_valid(false);
}
else if (noClockOpt.getCount() > 1)
{
// removing all clock data (line types 50, 51, and 70)
ordEpoch.clockOffset.set_valid(false);
ordEpoch.clockResidual.set_valid(false);
}
if (prnSet.size() || wartSet.size())
{
// removing good obs (the type 0 lines)
ORDEpoch::ORDMap::const_iterator iter = ordEpoch.ords.begin();
while (iter!= ordEpoch.ords.end())
{
const SatID& satId = iter->first;
const ObsRngDev& ord = iter->second;
iter++;
if (prnSet.count(satId.id) ||
(ord.wonky && wartSet.count(satId.id)))
ordEpoch.removeORD(satId);
}
}
if (clkResOpt.getCount() &&
(std::abs(ordEpoch.clockResidual)>clkResidLimit))
ordEpoch.clockResidual.set_valid(false);
if (ordLimitOpt.getCount())
{
ORDEpoch::ORDMap::const_iterator iter = ordEpoch.ords.begin();
while (iter!= ordEpoch.ords.end())
{
const SatID& satId = iter->first;
const ObsRngDev& ord = iter->second;
iter++;
if (ord.getORD() < ordLimit)
ordEpoch.removeORD(satId);
}
}
write(output, ordEpoch);
}
if (verboseLevel || debugLevel)
cout << "# Doneskies.\n";
}
//-----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
try
{
OrdEdit crap;
if (!crap.initialize(argc, argv))
exit(0);
crap.run();
}
catch (gpstk::Exception &exc)
{ cout << exc << endl; }
catch (std::exception &exc)
{ cerr << "Caught std::exception " << exc.what() << endl; }
catch (...)
{ cerr << "Caught unknown exception" << endl; }
}
<|endoftext|>
|
<commit_before>#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cstdarg>
#include <cerrno>
#include <vector>
#include <map>
#include <string>
#include <functional>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include "riscv-types.h"
#include "riscv-endian.h"
#include "riscv-processor.h"
#include "riscv-format.h"
#include "riscv-opcodes.h"
#include "riscv-util.h"
#include "riscv-imm.h"
#include "riscv-decode.h"
#include "riscv-csr.h"
#include "riscv-elf.h"
#include "riscv-elf-file.h"
#include "riscv-elf-format.h"
void rv64_exec(riscv_decode &dec, riscv_proc_state *proc)
{
riscv_ptr next_pc = riscv_decode_instruction(dec, proc->pc);
switch (dec.op) {
case riscv_op_addi:
proc->i_reg[dec.rd].lu = proc->i_reg[dec.rs1].lu + dec.imm;
proc->pc = next_pc;
break;
case riscv_op_auipc:
proc->i_reg[dec.rd].lu = riscv_lu(proc->pc) + dec.imm;
proc->pc = next_pc;
break;
case riscv_op_lui:
proc->i_reg[dec.rd].lu = dec.imm;
proc->pc = next_pc;
break;
case riscv_op_scall:
switch (proc->i_reg[riscv_ireg_a7].lu) {
case 64: /* sys_write */
proc->i_reg[riscv_ireg_a0].lu = write(proc->i_reg[riscv_ireg_a0].lu,
(void*)proc->i_reg[riscv_ireg_a1].lu, proc->i_reg[riscv_ireg_a2].lu);
break;
case 93: /* sys_exit */
exit(proc->i_reg[riscv_ireg_a0].lu);
break;
default:
panic("illegal syscall: %d", proc->i_reg[riscv_ireg_a7].lu);
}
proc->pc = next_pc;
break;
default:
panic("illegal instruciton: %s", riscv_instruction_name[dec.op]);
}
}
void rv64_run(riscv_ptr entry)
{
riscv_decode dec;
riscv_proc_state proc = { 0 };
proc.p_type = riscv_proc_type_rv64i;
proc.pc = entry;
while (true) {
rv64_exec(dec, &proc);
}
}
void* map_executable(const char* filename, void *vaddr, size_t len, size_t offset)
{
int fd = open(filename, O_RDONLY);
if (fd < 0) {
panic("error: open: %s: %s", filename, strerror(errno));
}
void *addr = mmap(vaddr, len, PROT_READ | PROT_EXEC, MAP_FIXED | MAP_PRIVATE, fd, offset);
if (addr == MAP_FAILED) {
panic("error: mmap: %s: %s", filename, strerror(errno));
}
close(fd);
return addr;
}
int main(int argc, char *argv[])
{
elf_file elf;
if (argc != 2) panic("usage: %s <elf_file>", argv[0]);
elf.load(argv[1]);
for (size_t i = 0; i < elf.phdrs.size(); i++) {
Elf64_Phdr &phdr = elf.phdrs[i];
if (phdr.p_flags & PT_LOAD) {
map_executable(argv[1], (void*)phdr.p_vaddr, phdr.p_memsz, phdr.p_offset);
rv64_run(riscv_ptr(elf.ehdr.e_entry));
break;
}
}
// TODO : munmap
return 0;
}
<commit_msg>Add some comments regarding POC limitations<commit_after>#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cstdarg>
#include <cerrno>
#include <vector>
#include <map>
#include <string>
#include <functional>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include "riscv-types.h"
#include "riscv-endian.h"
#include "riscv-processor.h"
#include "riscv-format.h"
#include "riscv-opcodes.h"
#include "riscv-util.h"
#include "riscv-imm.h"
#include "riscv-decode.h"
#include "riscv-csr.h"
#include "riscv-elf.h"
#include "riscv-elf-file.h"
#include "riscv-elf-format.h"
void rv64_exec(riscv_decode &dec, riscv_proc_state *proc)
{
riscv_ptr next_pc = riscv_decode_instruction(dec, proc->pc);
switch (dec.op) {
case riscv_op_addi:
proc->i_reg[dec.rd].lu = proc->i_reg[dec.rs1].lu + dec.imm;
proc->pc = next_pc;
break;
case riscv_op_auipc:
proc->i_reg[dec.rd].lu = riscv_lu(proc->pc) + dec.imm;
proc->pc = next_pc;
break;
case riscv_op_lui:
proc->i_reg[dec.rd].lu = dec.imm;
proc->pc = next_pc;
break;
case riscv_op_scall:
switch (proc->i_reg[riscv_ireg_a7].lu) {
case 64: /* sys_write */
proc->i_reg[riscv_ireg_a0].lu = write(proc->i_reg[riscv_ireg_a0].lu,
(void*)proc->i_reg[riscv_ireg_a1].lu, proc->i_reg[riscv_ireg_a2].lu);
break;
case 93: /* sys_exit */
exit(proc->i_reg[riscv_ireg_a0].lu);
break;
default:
panic("illegal syscall: %d", proc->i_reg[riscv_ireg_a7].lu);
}
proc->pc = next_pc;
break;
default:
panic("illegal instruciton: %s", riscv_instruction_name[dec.op]);
}
}
void rv64_run(riscv_ptr entry)
{
riscv_decode dec;
riscv_proc_state proc = { 0 };
proc.p_type = riscv_proc_type_rv64i;
proc.pc = entry;
while (true) {
rv64_exec(dec, &proc);
}
}
void* map_executable(const char* filename, void *vaddr, size_t len, size_t offset)
{
int fd = open(filename, O_RDONLY);
if (fd < 0) {
panic("error: open: %s: %s", filename, strerror(errno));
}
void *addr = mmap(vaddr, len, PROT_READ | PROT_EXEC, MAP_FIXED | MAP_PRIVATE, fd, offset);
if (addr == MAP_FAILED) {
panic("error: mmap: %s: %s", filename, strerror(errno));
}
close(fd);
return addr;
}
int main(int argc, char *argv[])
{
elf_file elf;
if (argc != 2) panic("usage: %s <elf_file>", argv[0]);
// load ELF headers
// NOTE: This POC code presently loads the whole ELF into RAM.
// TODO: Add flag to only load headers
elf.load(argv[1]);
// Find the LOAD segment and mmap it into memory
// NOTE: This POC code presently only handles on PT_LOAD segment
for (size_t i = 0; i < elf.phdrs.size(); i++) {
Elf64_Phdr &phdr = elf.phdrs[i];
if (phdr.p_flags & PT_LOAD) {
map_executable(argv[1], (void*)phdr.p_vaddr, phdr.p_memsz, phdr.p_offset);
rv64_run(riscv_ptr(elf.ehdr.e_entry));
break;
}
}
// TODO : munmap
return 0;
}
<|endoftext|>
|
<commit_before>/**
* Copyright (C) 2003-2006 Funambol
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include "base/fscapi.h"
#include "base/Log.h"
#include "base/util/XMLProcessor.h"
#include "base/quoted-printable.h"
#include "syncml/formatter/Formatter.h"
#include "spds/EmailData.h"
#define EMAIL_READ T("read")
#define EMAIL_FORW T("forwarded")
#define EMAIL_REPL T("replied")
#define EMAIL_TREC T("received")
#define EMAIL_TCRE T("created")
#define EMAIL_TMOD T("modified")
#define EMAIL_DELE T("deleted")
#define EMAIL_FLAG T("flagged")
#define EMAIL_ITEM T("emailitem")
static inline bool checkFlag(const char *xml, const char *field)
{
size_t start = 0, end = 0;
bool ret = false;
if( XMLProcessor::getElementContent(xml, field, NULL, &start, &end) ) {
ret = ( bstrncmp(xml+start, T("true"), end-start) == 0 ) ;
}
return ret;
}
EmailData::EmailData()
{
read = false;
forwarded = false;
replied = false;
deleted = false;
flagged = false;
}
int EmailData::parse(const BCHAR *msg, size_t len)
{
int ret = 0;
size_t start, end;
// Get attributes
read = checkFlag(msg, EMAIL_READ);
forwarded = checkFlag(msg, EMAIL_FORW);
replied = checkFlag(msg, EMAIL_REPL);
deleted = checkFlag(msg, EMAIL_DELE);
flagged = checkFlag(msg, EMAIL_FLAG);
if( XMLProcessor::getElementContent (msg, EMAIL_TREC, NULL, &start, &end) ) {
received = StringBuffer(msg+start, end-start);
}
else received = T("");
if( XMLProcessor::getElementContent (msg, EMAIL_TCRE, NULL, &start, &end) ) {
created = StringBuffer(msg+start, end-start);
}
else created = T("");
if( XMLProcessor::getElementContent (msg, EMAIL_TMOD, NULL, &start, &end) ) {
modified = StringBuffer(msg+start, end-start);
}
else modified = T("");
// Get content
if( XMLProcessor::getElementContent(msg, EMAIL_ITEM, NULL, &start, &end) ) {
StringBuffer item(msg+start, end-start);
unsigned int startAttr=0, endAttr=0;
size_t itemlen = end-start;
if(XMLProcessor::getElementAttributes(msg, EMAIL_ITEM, &startAttr, &endAttr, false)){ //currently emailitem is not escaped so false!!
StringBuffer attrlist(msg+startAttr, endAttr-startAttr);
if(attrlist.ifind("quoted-printable") != StringBuffer::npos) {
char *decoded = qp_decode(item);
item = decoded;
delete [] decoded;
}
}
// item must start with CDATA
size_t item_start = item.find("![CDATA");
if(item_start > 10){
LOG.error(T("EMailData: can't find inner CDATA section."));
return -1;
}
size_t item_end = item.rfind("]]>");
// In emailitem the last > close the CDATA of emailitem tag and is escaped, so it is needed
// to be found the follow. Usually the first is skipped
//
if(item.length() - item_end > 10){
item_end = item.rfind("]]>");
if(item.length() - item_end > 10){
LOG.error(T("EMailData: can't find CDATA end tag."));
return -1;
}
}
// okay, move the start pointer to the end of
item_start += bstrlen("![CDATA[");
ret=emailItem.parse( item.c_str()+item_start, item_end - item_start );
}
else {
LOG.info(T("EMailData: no <emailitem> tag."));
// It is not an error, just log it for info.
}
return ret;
}
BCHAR *EmailData::format() {
StringBuffer out;
out.reserve(150);
out = T("<Email>\n");
out += XMLProcessor::makeElement(EMAIL_READ, read);
out += XMLProcessor::makeElement(EMAIL_FORW, forwarded);
out += XMLProcessor::makeElement(EMAIL_REPL, replied);
out += XMLProcessor::makeElement(EMAIL_TREC, received);
out += XMLProcessor::makeElement(EMAIL_TCRE, created);
out += XMLProcessor::makeElement(EMAIL_TMOD, modified);
out += XMLProcessor::makeElement(EMAIL_DELE, deleted);
out += XMLProcessor::makeElement(EMAIL_FLAG, flagged);
BCHAR *item = emailItem.format();
if ( item ) {
out += T("<emailitem>\n<![CDATA[");
out += item;
delete [] item;
out += T("]]>\n</emailitem>\n");
}
out += T("</Email>\n");
return stringdup(out.c_str());
}
<commit_msg>added return code of emailData<commit_after>/**
* Copyright (C) 2003-2006 Funambol
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include "base/fscapi.h"
#include "base/Log.h"
#include "base/util/XMLProcessor.h"
#include "base/quoted-printable.h"
#include "syncml/formatter/Formatter.h"
#include "spds/EmailData.h"
#define EMAIL_READ T("read")
#define EMAIL_FORW T("forwarded")
#define EMAIL_REPL T("replied")
#define EMAIL_TREC T("received")
#define EMAIL_TCRE T("created")
#define EMAIL_TMOD T("modified")
#define EMAIL_DELE T("deleted")
#define EMAIL_FLAG T("flagged")
#define EMAIL_ITEM T("emailitem")
static inline bool checkFlag(const char *xml, const char *field)
{
size_t start = 0, end = 0;
bool ret = false;
if( XMLProcessor::getElementContent(xml, field, NULL, &start, &end) ) {
ret = ( bstrncmp(xml+start, T("true"), end-start) == 0 ) ;
}
return ret;
}
EmailData::EmailData()
{
read = false;
forwarded = false;
replied = false;
deleted = false;
flagged = false;
}
/*
* The parse method returns:
* -1: it means the <emailitem> doesn't containt CDATA section. This could be right
* if the <email> is an update from server of flags only, as <read>, <forwarded>...
The rightness must be choosen by the caller. It could be or not an error
*
* -2: it means there is an error into the format of the <emailitem>. It must be treated as an error
*
*/
int EmailData::parse(const BCHAR *msg, size_t len)
{
int ret = 0;
size_t start, end;
// Get attributes
read = checkFlag(msg, EMAIL_READ);
forwarded = checkFlag(msg, EMAIL_FORW);
replied = checkFlag(msg, EMAIL_REPL);
deleted = checkFlag(msg, EMAIL_DELE);
flagged = checkFlag(msg, EMAIL_FLAG);
if( XMLProcessor::getElementContent (msg, EMAIL_TREC, NULL, &start, &end) ) {
received = StringBuffer(msg+start, end-start);
}
else received = T("");
if( XMLProcessor::getElementContent (msg, EMAIL_TCRE, NULL, &start, &end) ) {
created = StringBuffer(msg+start, end-start);
}
else created = T("");
if( XMLProcessor::getElementContent (msg, EMAIL_TMOD, NULL, &start, &end) ) {
modified = StringBuffer(msg+start, end-start);
}
else modified = T("");
// Get content
if( XMLProcessor::getElementContent(msg, EMAIL_ITEM, NULL, &start, &end) ) {
StringBuffer item(msg+start, end-start);
unsigned int startAttr=0, endAttr=0;
size_t itemlen = end-start;
if(XMLProcessor::getElementAttributes(msg, EMAIL_ITEM, &startAttr, &endAttr, false)){ //currently emailitem is not escaped so false!!
StringBuffer attrlist(msg+startAttr, endAttr-startAttr);
if(attrlist.ifind("quoted-printable") != StringBuffer::npos) {
char *decoded = qp_decode(item);
item = decoded;
delete [] decoded;
}
}
// item must start with CDATA
size_t item_start = item.find("![CDATA");
if(item_start > 10){
LOG.error(T("EMailData: can't find inner CDATA section."));
return -1;
}
size_t item_end = item.rfind("]]>");
// In emailitem the last > close the CDATA of emailitem tag and is escaped, so it is needed
// to be found the follow. Usually the first is skipped
//
if(item.length() - item_end > 10){
item_end = item.rfind("]]>");
if(item.length() - item_end > 10){
LOG.error(T("EMailData: can't find CDATA end tag."));
return -2;
}
}
// okay, move the start pointer to the end of
item_start += bstrlen("![CDATA[");
ret=emailItem.parse( item.c_str()+item_start, item_end - item_start );
}
else {
LOG.info(T("EMailData: no <emailitem> tag."));
// It is not an error, just log it for info.
}
return ret;
}
BCHAR *EmailData::format() {
StringBuffer out;
out.reserve(150);
out = T("<Email>\n");
out += XMLProcessor::makeElement(EMAIL_READ, read);
out += XMLProcessor::makeElement(EMAIL_FORW, forwarded);
out += XMLProcessor::makeElement(EMAIL_REPL, replied);
out += XMLProcessor::makeElement(EMAIL_TREC, received);
out += XMLProcessor::makeElement(EMAIL_TCRE, created);
out += XMLProcessor::makeElement(EMAIL_TMOD, modified);
out += XMLProcessor::makeElement(EMAIL_DELE, deleted);
out += XMLProcessor::makeElement(EMAIL_FLAG, flagged);
BCHAR *item = emailItem.format();
if ( item ) {
out += T("<emailitem>\n<![CDATA[");
out += item;
delete [] item;
out += T("]]>\n</emailitem>\n");
}
out += T("</Email>\n");
return stringdup(out.c_str());
}
<|endoftext|>
|
<commit_before>// Copyright 2020 Google LLC
//
// 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
//
// https://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 "generator/internal/metadata_decorator_generator.h"
#include "google/cloud/internal/absl_str_cat_quiet.h"
#include "absl/memory/memory.h"
#include "absl/strings/str_split.h"
#include "generator/internal/codegen_utils.h"
#include "generator/internal/predicate_utils.h"
#include "generator/internal/printer.h"
#include <google/protobuf/descriptor.h>
namespace google {
namespace cloud {
namespace generator_internal {
MetadataDecoratorGenerator::MetadataDecoratorGenerator(
google::protobuf::ServiceDescriptor const* service_descriptor,
VarsDictionary service_vars,
std::map<std::string, VarsDictionary> service_method_vars,
google::protobuf::compiler::GeneratorContext* context)
: ServiceCodeGenerator("metadata_header_path", "metadata_cc_path",
service_descriptor, std::move(service_vars),
std::move(service_method_vars), context) {}
Status MetadataDecoratorGenerator::GenerateHeader() {
HeaderPrint(CopyrightLicenseFileHeader());
HeaderPrint( // clang-format off
"\n"
"// Generated by the Codegen C++ plugin.\n"
"// If you make any local changes, they will be lost.\n"
"// source: $proto_file_name$\n"
"\n"
"#ifndef $header_include_guard$\n"
"#define $header_include_guard$\n");
// clang-format on
// includes
HeaderPrint("\n");
HeaderLocalIncludes({vars("stub_header_path"), "google/cloud/version.h"});
HeaderSystemIncludes(
{HasLongrunningMethod() ? "google/longrunning/operations.grpc.pb.h" : "",
"memory", "string"});
auto result = HeaderOpenNamespaces(NamespaceType::kInternal);
if (!result.ok()) return result;
// metadata decorator class
HeaderPrint( // clang-format off
"\n"
"class $metadata_class_name$ : public $stub_class_name$ {\n"
" public:\n"
" ~$metadata_class_name$() override = default;\n"
" explicit $metadata_class_name$(std::shared_ptr<$stub_class_name$> child);\n");
// clang-format on
for (auto const& method : methods()) {
if (IsStreamingWrite(method)) {
HeaderPrintMethod(method, __FILE__, __LINE__,
R"""(
std::unique_ptr<::google::cloud::internal::StreamingWriteRpc<
$request_type$,
$response_type$>>
$method_name$(
std::unique_ptr<grpc::ClientContext> context) override;
)""");
continue;
}
if (IsBidirStreaming(method)) {
HeaderPrintMethod(method, __FILE__, __LINE__,
R"""(
std::unique_ptr<::google::cloud::AsyncStreamingReadWriteRpc<
$request_type$,
$response_type$>>
Async$method_name$(
google::cloud::CompletionQueue const& cq,
std::unique_ptr<grpc::ClientContext> context) override;
)""");
continue;
}
HeaderPrintMethod(
method,
{MethodPattern({{IsResponseTypeEmpty,
// clang-format off
"\n Status $method_name$(\n",
"\n StatusOr<$response_type$> $method_name$(\n"},
{" grpc::ClientContext& context,\n"
" $request_type$ const& request) override;\n"
// clang-format on
}},
And(IsNonStreaming, Not(IsLongrunningOperation))),
MethodPattern({{R"""(
future<StatusOr<google::longrunning::Operation>> Async$method_name$(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
$request_type$ const& request) override;
)"""}},
IsLongrunningOperation),
MethodPattern(
{ // clang-format off
{"\n"
" std::unique_ptr<google::cloud::internal::StreamingReadRpc<$response_type$>>\n"
" $method_name$(\n"
" std::unique_ptr<grpc::ClientContext> context,\n"
" $request_type$ const& request) override;\n"
// clang-format on
}},
IsStreamingRead)},
__FILE__, __LINE__);
}
for (auto const& method : async_methods()) {
if (IsStreamingRead(method)) {
auto constexpr kDeclaration = R"""(
std::unique_ptr<::google::cloud::internal::AsyncStreamingReadRpc<
$response_type$>>
Async$method_name$(
google::cloud::CompletionQueue const& cq,
std::unique_ptr<grpc::ClientContext> context,
$request_type$ const& request) override;
)""";
HeaderPrintMethod(method, __FILE__, __LINE__, kDeclaration);
continue;
}
if (IsStreamingWrite(method)) {
auto constexpr kDeclaration = R"""(
std::unique_ptr<::google::cloud::internal::AsyncStreamingWriteRpc<
$request_type$, $response_type$>>
Async$method_name$(
google::cloud::CompletionQueue const& cq,
std::unique_ptr<grpc::ClientContext> context) override;
)""";
HeaderPrintMethod(method, __FILE__, __LINE__, kDeclaration);
continue;
}
HeaderPrintMethod(
method,
{MethodPattern(
{{IsResponseTypeEmpty,
// clang-format off
"\n future<Status> Async$method_name$(\n",
"\n future<StatusOr<$response_type$>> Async$method_name$(\n"},
{" google::cloud::CompletionQueue& cq,\n"
" std::unique_ptr<grpc::ClientContext> context,\n"
" $request_type$ const& request) override;\n"
// clang-format on
}},
And(IsNonStreaming, Not(IsLongrunningOperation)))},
__FILE__, __LINE__);
}
if (HasLongrunningMethod()) {
HeaderPrint(
R"""(
future<StatusOr<google::longrunning::Operation>> AsyncGetOperation(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
google::longrunning::GetOperationRequest const& request) override;
future<Status> AsyncCancelOperation(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
google::longrunning::CancelOperationRequest const& request) override;
)""");
}
HeaderPrint(R"""(
private:
void SetMetadata(grpc::ClientContext& context,
std::string const& request_params);
void SetMetadata(grpc::ClientContext& context);
std::shared_ptr<$stub_class_name$> child_;
std::string api_client_header_;
};
)""");
HeaderCloseNamespaces();
// close header guard
HeaderPrint("\n#endif // $header_include_guard$\n");
return {};
}
Status MetadataDecoratorGenerator::GenerateCc() {
CcPrint(CopyrightLicenseFileHeader());
CcPrint( // clang-format off
"\n"
"// Generated by the Codegen C++ plugin.\n"
"// If you make any local changes, they will be lost.\n"
"// source: $proto_file_name$\n");
// clang-format on
// includes
CcPrint("\n");
CcLocalIncludes({vars("metadata_header_path"),
"google/cloud/internal/api_client_header.h",
"google/cloud/common_options.h",
"google/cloud/status_or.h"});
CcSystemIncludes({vars("proto_grpc_header_path"), "memory"});
auto result = CcOpenNamespaces(NamespaceType::kInternal);
if (!result.ok()) return result;
// constructor
CcPrint( // clang-format off
"\n"
"$metadata_class_name$::$metadata_class_name$(\n"
" std::shared_ptr<$stub_class_name$> child)\n"
" : child_(std::move(child)),\n"
" api_client_header_(google::cloud::internal::ApiClientHeader(\"generator\")) {}\n");
// clang-format on
// metadata decorator class member methods
for (auto const& method : methods()) {
if (IsStreamingWrite(method)) {
CcPrintMethod(method, __FILE__, __LINE__,
R"""(
std::unique_ptr<::google::cloud::internal::StreamingWriteRpc<
$request_type$,
$response_type$>>
$metadata_class_name$::$method_name$(
std::unique_ptr<grpc::ClientContext> context) {
SetMetadata(*context);
return child_->$method_name$(std::move(context));
}
)""");
continue;
}
if (IsBidirStreaming(method)) {
CcPrintMethod(method, __FILE__, __LINE__,
R"""(
std::unique_ptr<::google::cloud::AsyncStreamingReadWriteRpc<
$request_type$,
$response_type$>>
$metadata_class_name$::Async$method_name$(
google::cloud::CompletionQueue const& cq,
std::unique_ptr<grpc::ClientContext> context) {
SetMetadata(*context);
return child_->Async$method_name$(cq, std::move(context));
}
)""");
continue;
}
CcPrintMethod(
method,
{MethodPattern(
{
{IsResponseTypeEmpty,
// clang-format off
"\nStatus\n",
"\nStatusOr<$response_type$>\n"},
{"$metadata_class_name$::$method_name$(\n"
" grpc::ClientContext& context,\n"
" $request_type$ const& request) {\n"},
{HasRoutingHeader,
" SetMetadata(context, \"$method_request_param_key$=\" + request.$method_request_param_value$);\n",
" SetMetadata(context);\n"},
{" return child_->$method_name$(context, request);\n"
"}\n",}
// clang-format on
},
And(IsNonStreaming, Not(IsLongrunningOperation))),
MethodPattern({{HasRoutingHeader,
R"""(
future<StatusOr<google::longrunning::Operation>>
$metadata_class_name$::Async$method_name$(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
$request_type$ const& request) {
SetMetadata(*context, "$method_request_param_key$=" + request.$method_request_param_value$);
return child_->Async$method_name$(cq, std::move(context), request);
}
)""",
R"""(
future<StatusOr<google::longrunning::Operation>>
$metadata_class_name$::Async$method_name$(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
$request_type$ const& request) {
SetMetadata(*context);
return child_->Async$method_name$(cq, std::move(context), request);
}
)"""}},
IsLongrunningOperation),
MethodPattern(
{
// clang-format off
{"\n"
"std::unique_ptr<google::cloud::internal::StreamingReadRpc<$response_type$>>\n"
"$metadata_class_name$::$method_name$(\n"
" std::unique_ptr<grpc::ClientContext> context,\n"
" $request_type$ const& request) {\n"},
{HasRoutingHeader,
" SetMetadata(*context, \"$method_request_param_key$=\" + request.$method_request_param_value$);\n",
" SetMetadata(*context);\n"},
{" return child_->$method_name$(std::move(context), request);\n"
"}\n",}
// clang-format on
},
IsStreamingRead)},
__FILE__, __LINE__);
}
for (auto const& method : async_methods()) {
auto const* set_metadata_stanza = R"""(
SetMetadata(*context);)""";
if (HasRoutingHeader(method)) {
set_metadata_stanza = R"""(
SetMetadata(
*context,
"$method_request_param_key$=" + request.$method_request_param_value$);)""";
}
if (IsStreamingRead(method)) {
auto const definition = absl::StrCat(
R"""(
std::unique_ptr<::google::cloud::internal::AsyncStreamingReadRpc<
$response_type$>>
$metadata_class_name$::Async$method_name$(
google::cloud::CompletionQueue const& cq,
std::unique_ptr<grpc::ClientContext> context,
$request_type$ const& request) {)""",
set_metadata_stanza,
R"""(
return child_->Async$method_name$(cq, std::move(context), request);
}
)""");
CcPrintMethod(method, __FILE__, __LINE__, definition);
continue;
}
if (IsStreamingWrite(method)) {
auto const definition = absl::StrCat(
R"""(
std::unique_ptr<::google::cloud::internal::AsyncStreamingWriteRpc<
$request_type$, $response_type$>>
$metadata_class_name$::Async$method_name$(
google::cloud::CompletionQueue const& cq,
std::unique_ptr<grpc::ClientContext> context) {)""",
set_metadata_stanza,
R"""(
return child_->Async$method_name$(cq, std::move(context));
}
)""");
CcPrintMethod(method, __FILE__, __LINE__, definition);
continue;
}
CcPrintMethod(
method,
{MethodPattern(
{{IsResponseTypeEmpty,
// clang-format off
"\nfuture<Status>\n",
"\nfuture<StatusOr<$response_type$>>\n"},
{R"""($metadata_class_name$::Async$method_name$(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
$request_type$ const& request) {)"""},
{HasRoutingHeader, R"""(
SetMetadata(*context, "$method_request_param_key$=" + request.$method_request_param_value$);)""",
R"""(
SetMetadata(*context);)"""}, {R"""(
return child_->Async$method_name$(cq, std::move(context), request);
}
)"""}},
// clang-format on
And(IsNonStreaming, Not(IsLongrunningOperation)))},
__FILE__, __LINE__);
}
// long running operation support methods
if (HasLongrunningMethod()) {
CcPrint(R"""(
future<StatusOr<google::longrunning::Operation>>
$metadata_class_name$::AsyncGetOperation(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
google::longrunning::GetOperationRequest const& request) {
SetMetadata(*context, "name=" + request.name());
return child_->AsyncGetOperation(cq, std::move(context), request);
}
future<Status> $metadata_class_name$::AsyncCancelOperation(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
google::longrunning::CancelOperationRequest const& request) {
SetMetadata(*context, "name=" + request.name());
return child_->AsyncCancelOperation(cq, std::move(context), request);
}
)""");
}
CcPrint(R"""(
void $metadata_class_name$::SetMetadata(grpc::ClientContext& context,
std::string const& request_params) {
context.AddMetadata("x-goog-request-params", request_params);
SetMetadata(context);
}
void $metadata_class_name$::SetMetadata(grpc::ClientContext& context) {
context.AddMetadata("x-goog-api-client", api_client_header_);
auto const& options = internal::CurrentOptions();
if (options.has<UserProjectOption>()) {
context.AddMetadata(
"x-goog-user-project", options.get<UserProjectOption>());
}
auto const& authority = options.get<AuthorityOption>();
if (!authority.empty()) context.set_authority(authority);
}
)""");
CcCloseNamespaces();
return {};
}
} // namespace generator_internal
} // namespace cloud
} // namespace google
<commit_msg>refactor(generator): organize metadata generator a bit (#9355)<commit_after>// Copyright 2020 Google LLC
//
// 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
//
// https://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 "generator/internal/metadata_decorator_generator.h"
#include "google/cloud/internal/absl_str_cat_quiet.h"
#include "absl/memory/memory.h"
#include "absl/strings/str_split.h"
#include "generator/internal/codegen_utils.h"
#include "generator/internal/predicate_utils.h"
#include "generator/internal/printer.h"
#include <google/protobuf/descriptor.h>
namespace google {
namespace cloud {
namespace generator_internal {
namespace {
enum ContextType { kPointer, kReference };
std::string SetMetadataText(google::protobuf::MethodDescriptor const& method,
ContextType context_type) {
std::string const context = context_type == kPointer ? "*context" : "context";
if (HasRoutingHeader(method)) {
return " SetMetadata(" + context +
", \"$method_request_param_key$=\" + "
"request.$method_request_param_value$);";
}
// If the method does not have a `google.api.http` annotation, we do not send
// the "x-goog-request-params" header.
return " SetMetadata(" + context + ");";
}
} // namespace
MetadataDecoratorGenerator::MetadataDecoratorGenerator(
google::protobuf::ServiceDescriptor const* service_descriptor,
VarsDictionary service_vars,
std::map<std::string, VarsDictionary> service_method_vars,
google::protobuf::compiler::GeneratorContext* context)
: ServiceCodeGenerator("metadata_header_path", "metadata_cc_path",
service_descriptor, std::move(service_vars),
std::move(service_method_vars), context) {}
Status MetadataDecoratorGenerator::GenerateHeader() {
HeaderPrint(CopyrightLicenseFileHeader());
HeaderPrint( // clang-format off
"\n"
"// Generated by the Codegen C++ plugin.\n"
"// If you make any local changes, they will be lost.\n"
"// source: $proto_file_name$\n"
"\n"
"#ifndef $header_include_guard$\n"
"#define $header_include_guard$\n");
// clang-format on
// includes
HeaderPrint("\n");
HeaderLocalIncludes({vars("stub_header_path"), "google/cloud/version.h"});
HeaderSystemIncludes(
{HasLongrunningMethod() ? "google/longrunning/operations.grpc.pb.h" : "",
"memory", "string"});
auto result = HeaderOpenNamespaces(NamespaceType::kInternal);
if (!result.ok()) return result;
// metadata decorator class
HeaderPrint( // clang-format off
"\n"
"class $metadata_class_name$ : public $stub_class_name$ {\n"
" public:\n"
" ~$metadata_class_name$() override = default;\n"
" explicit $metadata_class_name$(std::shared_ptr<$stub_class_name$> child);\n");
// clang-format on
for (auto const& method : methods()) {
if (IsStreamingWrite(method)) {
HeaderPrintMethod(method, __FILE__, __LINE__,
R"""(
std::unique_ptr<::google::cloud::internal::StreamingWriteRpc<
$request_type$,
$response_type$>>
$method_name$(
std::unique_ptr<grpc::ClientContext> context) override;
)""");
continue;
}
if (IsBidirStreaming(method)) {
HeaderPrintMethod(method, __FILE__, __LINE__,
R"""(
std::unique_ptr<::google::cloud::AsyncStreamingReadWriteRpc<
$request_type$,
$response_type$>>
Async$method_name$(
google::cloud::CompletionQueue const& cq,
std::unique_ptr<grpc::ClientContext> context) override;
)""");
continue;
}
HeaderPrintMethod(
method,
{MethodPattern({{IsResponseTypeEmpty,
// clang-format off
"\n Status $method_name$(\n",
"\n StatusOr<$response_type$> $method_name$(\n"},
{" grpc::ClientContext& context,\n"
" $request_type$ const& request) override;\n"
// clang-format on
}},
And(IsNonStreaming, Not(IsLongrunningOperation))),
MethodPattern({{R"""(
future<StatusOr<google::longrunning::Operation>> Async$method_name$(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
$request_type$ const& request) override;
)"""}},
IsLongrunningOperation),
MethodPattern(
{ // clang-format off
{"\n"
" std::unique_ptr<google::cloud::internal::StreamingReadRpc<$response_type$>>\n"
" $method_name$(\n"
" std::unique_ptr<grpc::ClientContext> context,\n"
" $request_type$ const& request) override;\n"
// clang-format on
}},
IsStreamingRead)},
__FILE__, __LINE__);
}
for (auto const& method : async_methods()) {
if (IsStreamingRead(method)) {
auto constexpr kDeclaration = R"""(
std::unique_ptr<::google::cloud::internal::AsyncStreamingReadRpc<
$response_type$>>
Async$method_name$(
google::cloud::CompletionQueue const& cq,
std::unique_ptr<grpc::ClientContext> context,
$request_type$ const& request) override;
)""";
HeaderPrintMethod(method, __FILE__, __LINE__, kDeclaration);
continue;
}
if (IsStreamingWrite(method)) {
auto constexpr kDeclaration = R"""(
std::unique_ptr<::google::cloud::internal::AsyncStreamingWriteRpc<
$request_type$, $response_type$>>
Async$method_name$(
google::cloud::CompletionQueue const& cq,
std::unique_ptr<grpc::ClientContext> context) override;
)""";
HeaderPrintMethod(method, __FILE__, __LINE__, kDeclaration);
continue;
}
HeaderPrintMethod(
method,
{MethodPattern(
{{IsResponseTypeEmpty,
// clang-format off
"\n future<Status> Async$method_name$(\n",
"\n future<StatusOr<$response_type$>> Async$method_name$(\n"},
{" google::cloud::CompletionQueue& cq,\n"
" std::unique_ptr<grpc::ClientContext> context,\n"
" $request_type$ const& request) override;\n"
// clang-format on
}},
And(IsNonStreaming, Not(IsLongrunningOperation)))},
__FILE__, __LINE__);
}
if (HasLongrunningMethod()) {
HeaderPrint(
R"""(
future<StatusOr<google::longrunning::Operation>> AsyncGetOperation(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
google::longrunning::GetOperationRequest const& request) override;
future<Status> AsyncCancelOperation(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
google::longrunning::CancelOperationRequest const& request) override;
)""");
}
HeaderPrint(R"""(
private:
void SetMetadata(grpc::ClientContext& context,
std::string const& request_params);
void SetMetadata(grpc::ClientContext& context);
std::shared_ptr<$stub_class_name$> child_;
std::string api_client_header_;
};
)""");
HeaderCloseNamespaces();
// close header guard
HeaderPrint("\n#endif // $header_include_guard$\n");
return {};
}
Status MetadataDecoratorGenerator::GenerateCc() {
CcPrint(CopyrightLicenseFileHeader());
CcPrint( // clang-format off
"\n"
"// Generated by the Codegen C++ plugin.\n"
"// If you make any local changes, they will be lost.\n"
"// source: $proto_file_name$\n");
// clang-format on
// includes
CcPrint("\n");
CcLocalIncludes({vars("metadata_header_path"),
"google/cloud/internal/api_client_header.h",
"google/cloud/common_options.h",
"google/cloud/status_or.h"});
CcSystemIncludes({vars("proto_grpc_header_path"), "memory"});
auto result = CcOpenNamespaces(NamespaceType::kInternal);
if (!result.ok()) return result;
// constructor
CcPrint( // clang-format off
"\n"
"$metadata_class_name$::$metadata_class_name$(\n"
" std::shared_ptr<$stub_class_name$> child)\n"
" : child_(std::move(child)),\n"
" api_client_header_(google::cloud::internal::ApiClientHeader(\"generator\")) {}\n");
// clang-format on
// metadata decorator class member methods
for (auto const& method : methods()) {
if (IsStreamingWrite(method)) {
CcPrintMethod(method, __FILE__, __LINE__,
R"""(
std::unique_ptr<::google::cloud::internal::StreamingWriteRpc<
$request_type$,
$response_type$>>
$metadata_class_name$::$method_name$(
std::unique_ptr<grpc::ClientContext> context) {
SetMetadata(*context);
return child_->$method_name$(std::move(context));
}
)""");
continue;
}
if (IsBidirStreaming(method)) {
CcPrintMethod(method, __FILE__, __LINE__,
R"""(
std::unique_ptr<::google::cloud::AsyncStreamingReadWriteRpc<
$request_type$,
$response_type$>>
$metadata_class_name$::Async$method_name$(
google::cloud::CompletionQueue const& cq,
std::unique_ptr<grpc::ClientContext> context) {
SetMetadata(*context);
return child_->Async$method_name$(cq, std::move(context));
}
)""");
continue;
}
CcPrintMethod(
method,
{MethodPattern(
{
{IsResponseTypeEmpty,
// clang-format off
"\nStatus\n",
"\nStatusOr<$response_type$>\n"},
{"$metadata_class_name$::$method_name$(\n"
" grpc::ClientContext& context,\n"
" $request_type$ const& request) {\n"},
{SetMetadataText(method, kReference)},
{"\n return child_->$method_name$(context, request);\n"
"}\n",}
// clang-format on
},
And(IsNonStreaming, Not(IsLongrunningOperation))),
MethodPattern({{R"""(
future<StatusOr<google::longrunning::Operation>>
$metadata_class_name$::Async$method_name$(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
$request_type$ const& request) {
)"""},
{SetMetadataText(method, kPointer)},
{R"""(
return child_->Async$method_name$(cq, std::move(context), request);
}
)"""}},
IsLongrunningOperation),
MethodPattern(
{
// clang-format off
{"\n"
"std::unique_ptr<google::cloud::internal::StreamingReadRpc<$response_type$>>\n"
"$metadata_class_name$::$method_name$(\n"
" std::unique_ptr<grpc::ClientContext> context,\n"
" $request_type$ const& request) {\n"},
{SetMetadataText(method, kPointer)},
{"\n return child_->$method_name$(std::move(context), request);\n"
"}\n",}
// clang-format on
},
IsStreamingRead)},
__FILE__, __LINE__);
}
for (auto const& method : async_methods()) {
if (IsStreamingRead(method)) {
auto const definition = absl::StrCat(
R"""(
std::unique_ptr<::google::cloud::internal::AsyncStreamingReadRpc<
$response_type$>>
$metadata_class_name$::Async$method_name$(
google::cloud::CompletionQueue const& cq,
std::unique_ptr<grpc::ClientContext> context,
$request_type$ const& request) {
)""",
SetMetadataText(method, kPointer),
R"""(
return child_->Async$method_name$(cq, std::move(context), request);
}
)""");
CcPrintMethod(method, __FILE__, __LINE__, definition);
continue;
}
if (IsStreamingWrite(method)) {
auto const definition = absl::StrCat(
R"""(
std::unique_ptr<::google::cloud::internal::AsyncStreamingWriteRpc<
$request_type$, $response_type$>>
$metadata_class_name$::Async$method_name$(
google::cloud::CompletionQueue const& cq,
std::unique_ptr<grpc::ClientContext> context) {
)""",
SetMetadataText(method, kPointer),
R"""(
return child_->Async$method_name$(cq, std::move(context));
}
)""");
CcPrintMethod(method, __FILE__, __LINE__, definition);
continue;
}
CcPrintMethod(
method,
{MethodPattern(
{{IsResponseTypeEmpty,
// clang-format off
"\nfuture<Status>\n",
"\nfuture<StatusOr<$response_type$>>\n"},
{R"""($metadata_class_name$::Async$method_name$(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
$request_type$ const& request) {
)"""},
{SetMetadataText(method, kPointer)}, {R"""(
return child_->Async$method_name$(cq, std::move(context), request);
}
)"""}},
// clang-format on
And(IsNonStreaming, Not(IsLongrunningOperation)))},
__FILE__, __LINE__);
}
// long running operation support methods
if (HasLongrunningMethod()) {
CcPrint(R"""(
future<StatusOr<google::longrunning::Operation>>
$metadata_class_name$::AsyncGetOperation(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
google::longrunning::GetOperationRequest const& request) {
SetMetadata(*context, "name=" + request.name());
return child_->AsyncGetOperation(cq, std::move(context), request);
}
future<Status> $metadata_class_name$::AsyncCancelOperation(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
google::longrunning::CancelOperationRequest const& request) {
SetMetadata(*context, "name=" + request.name());
return child_->AsyncCancelOperation(cq, std::move(context), request);
}
)""");
}
CcPrint(R"""(
void $metadata_class_name$::SetMetadata(grpc::ClientContext& context,
std::string const& request_params) {
context.AddMetadata("x-goog-request-params", request_params);
SetMetadata(context);
}
void $metadata_class_name$::SetMetadata(grpc::ClientContext& context) {
context.AddMetadata("x-goog-api-client", api_client_header_);
auto const& options = internal::CurrentOptions();
if (options.has<UserProjectOption>()) {
context.AddMetadata(
"x-goog-user-project", options.get<UserProjectOption>());
}
auto const& authority = options.get<AuthorityOption>();
if (!authority.empty()) context.set_authority(authority);
}
)""");
CcCloseNamespaces();
return {};
}
} // namespace generator_internal
} // namespace cloud
} // namespace google
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: ViewShellBase.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2004-06-03 11:55:35 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SD_VIEW_SHELL_BASE_HXX
#define SD_VIEW_SHELL_BASE_HXX
#ifndef SD_GLOB_HXX
#include "glob.hxx"
#endif
#ifndef _SFXVIEWSH_HXX
#include <sfx2/viewsh.hxx>
#endif
#ifndef _VIEWFAC_HXX
#include <sfx2/viewfac.hxx>
#endif
#ifndef SD_SUB_SHELL_MANAGER_HXX
#include "SubShellManager.hxx"
#endif
#ifndef SD_PRINT_MANAGER_HXX
#include "PrintManager.hxx"
#endif
#include <memory>
class SdDrawDocument;
class SfxRequest;
namespace sd {
class DrawController;
class DrawDocShell;
class ObjectBarManager;
class ViewShell;
/** SfxViewShell descendant that the stacked Draw/Impress shells are
based on.
<p>The "base" part of the name does not mean that this is a base
class of some class hierarchy. It rather is the base of the
stacked shells.</p>
<p>This class starts as a new and relatively small class. Over
time as much code as possible should be moved from the stacked
shells to this class.</p>
*/
class ViewShellBase
: public SfxViewShell
{
public:
TYPEINFO();
SFX_DECL_VIEWFACTORY(ViewShellBase);
SFX_DECL_INTERFACE(SD_IF_SDVIEWSHELLBASE);
// ViewShellBase (SfxViewFrame *pFrame, USHORT nFlags);
/** This constructor is used by the view factory of the SFX
macros.
*/
ViewShellBase (SfxViewFrame *pFrame, SfxViewShell* pOldShell,
ViewShell::ShellType eDefaultSubShell = ViewShell::ST_IMPRESS);
virtual ~ViewShellBase (void);
SubShellManager& GetSubShellManager (void) const;
ObjectBarManager& GetObjectBarManager (void) const;
/** When given a view frame this static method returns the
corresponding sd::ViewShell object. In the old Impress this
is the single view shell associated with this frame. In the
new Impress this will be one that corresponds with the central
pane.
*/
static ViewShell* GetMainViewShell (SfxViewFrame* pFrame);
DrawDocShell* GetDocShell (void) const;
SdDrawDocument* GetDocument (void) const;
/** Callback function for slots related to changing the view or
edit mode.
*/
void ExecuteModeChange (SfxRequest& rRequest);
/** Callback function for retrieving item values related to menu entries.
*/
void GetMenuState (SfxItemSet& rSet);
/** Make sure that mpMainController points to a controller that matches
the current stacked view shell. If that is not the case the current
controller is replaced by a new one. Otherwise this method returns
without changing anything.
*/
void UpdateController (void);
/** This call is forwarded to the main sub-shell.
*/
virtual ErrCode DoVerb (long nVerb);
/// Forwarded to the print manager.
virtual SfxPrinter* GetPrinter (BOOL bCreate = FALSE);
/// Forwarded to the print manager.
virtual USHORT SetPrinter (
SfxPrinter* pNewPrinter,
USHORT nDiffFlags = SFX_PRINTER_ALL);
/// Forwarded to the print manager.
virtual PrintDialog* CreatePrintDialog (::Window *pParent);
/// Forwarded to the print manager.
virtual SfxTabPage* CreatePrintOptionsPage (
::Window *pParent,
const SfxItemSet &rOptions);
/// Forwarded to the print manager.
virtual USHORT Print (SfxProgress& rProgress, PrintDialog* pDialog);
/// Forwarded to the print manager.
virtual ErrCode DoPrint (
SfxPrinter *pPrinter,
PrintDialog *pPrintDialog,
BOOL bSilent);
/// Forwarded to the print manager.
USHORT SetPrinterOptDlg (
SfxPrinter* pNewPrinter,
USHORT nDiffFlags = SFX_PRINTER_ALL,
BOOL _bShowDialog = TRUE);
virtual void PreparePrint (PrintDialog* pPrintDialog);
/// Forward methods to main sub shell.
virtual void WriteUserDataSequence (
::com::sun::star::uno::Sequence <
::com::sun::star::beans::PropertyValue >&,
sal_Bool bBrowse = sal_False);
virtual void ReadUserDataSequence (
const ::com::sun::star::uno::Sequence <
::com::sun::star::beans::PropertyValue >&,
sal_Bool bBrowse = sal_False);
virtual void UIActivate (SvInPlaceObject *pIPObj);
virtual void UIDeactivate (SvInPlaceObject *pIPObj);
virtual void SetZoomFactor (
const Fraction &rZoomX,
const Fraction &rZoomY);
virtual USHORT PrepareClose (BOOL bUI = TRUE, BOOL bForBrowsing = FALSE);
virtual void WriteUserData (String&, BOOL bBrowse = FALSE);
virtual void ReadUserData (const String&, BOOL bBrowse = FALSE);
virtual SdrView* GetDrawView (void) const;
virtual void AdjustPosSizePixel (const Point &rOfs, const Size &rSize);
protected:
virtual void SFX_NOTIFY(SfxBroadcaster& rBC,
const TypeId& rBCType,
const SfxHint& rHint,
const TypeId& rHintType);
virtual void InnerResizePixel (const Point &rOfs, const Size &rSize);
virtual void OuterResizePixel (const Point &rOfs, const Size &rSize);
private:
osl::Mutex maMutex;
::std::auto_ptr<SubShellManager> mpSubShellManager;
DrawDocShell* mpDocShell;
SdDrawDocument* mpDocument;
/** Main controller of the view shell. During the switching from one
stacked shell to another this pointer may be NULL.
*/
DrawController* mpController;
/// The print manager is responsible for printing documents.
PrintManager maPrintManager;
/** Code common to all constructors.
*/
void Construct (ViewShell::ShellType eDefaultSubShell);
};
} // end of namespace sd
#endif
<commit_msg>INTEGRATION: CWS impress2 (1.2.26); FILE MERGED 2004/07/09 07:06:12 af 1.2.26.18: #i22705# Added ResizePixel() method that implements the common code of Outer- and InnerResizePixel(). 2004/07/01 11:20:23 af 1.2.26.17: #i22705# Added SetBusyState() method. 2004/06/29 07:14:17 af 1.2.26.16: #i22705# Made LateInit() virtual. Moved maMutex and mpViewTabBar to protected: section. 2004/06/22 11:12:14 af 1.2.26.15: #i22705# Moved mpController member to ViewShell. Added Activate() and Deactivate() methods. 2004/06/18 00:19:13 af 1.2.26.14: RESYNC: (1.3-1.4); FILE MERGED 2004/06/12 12:21:19 af 1.2.26.13: #i22705# Added GetBorder() method to support Inner- and OuterResizePixel(). 2004/05/23 13:29:58 af 1.2.26.12: #i22705# Moved pane related code to new PaneManager class. 2004/05/20 11:10:13 af 1.2.26.11: #i22705# Added Execute() and GetState() method for the handling of slots. 2004/04/27 12:39:47 af 1.2.26.10: #i22705# Moved view tab bar from ViewShell. Added ArrangeGUI() method for placing it. Added GetPaneOfViewShell() method. 2004/04/23 14:25:10 af 1.2.26.9: #i22705# Moved definition of EventId from ViewShellBase to ViewShellBaseEvent. Moved CallEventListeners() to impl class. 2004/04/23 11:26:11 af 1.2.26.8: #i22705# Removed edit-, master-,and layer button. 2004/04/21 15:15:29 af 1.2.26.7: #i22705# Added new PT_RIGHT pane. Moved pane handling to implementation class. 2004/03/05 12:13:35 af 1.2.26.6: #i22705# Added support for events and listeners. 2004/03/02 13:21:38 af 1.2.26.5: #i22705# Replaced bool argument in ViewShellBase::RequestViewShellChange() by more specific enum CallMode. 2004/03/02 12:04:04 af 1.2.26.4: #i22705# Added new method InitPanes(). 2004/03/02 09:48:30 af 1.2.26.3: #i22705# Moved printing to PrintManager. 2004/02/25 16:41:56 af 1.2.26.2: #i22705# Introdcution of member class PaneDescriptor. 2004/02/19 14:18:03 af 1.2.26.1: #i22705# Changed several method signatures.<commit_after>/*************************************************************************
*
* $RCSfile: ViewShellBase.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2004-07-13 14:04:15 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SD_VIEW_SHELL_BASE_HXX
#define SD_VIEW_SHELL_BASE_HXX
#include "ViewShell.hxx"
#ifndef SD_GLOB_HXX
#include "glob.hxx"
#endif
#ifndef _SFXVIEWSH_HXX
#include <sfx2/viewsh.hxx>
#endif
#ifndef _VIEWFAC_HXX
#include <sfx2/viewfac.hxx>
#endif
#ifndef SD_PRINT_MANAGER_HXX
#include "PrintManager.hxx"
#endif
#include <memory>
class SdDrawDocument;
class SfxRequest;
namespace sd {
class DrawDocShell;
class FormShellManager;
class PaneManager;
class ViewShell;
class ViewShellManager;
/** SfxViewShell descendant that the stacked Draw/Impress shells are
based on.
<p>The "base" part of the name does not mean that this is a base
class of some class hierarchy. It rather is the base of the
stacked shells.</p>
<p>This class starts as a new and relatively small class. Over
time as much code as possible should be moved from the stacked
shells to this class.</p>
*/
class ViewShellBase
: public SfxViewShell
{
public:
TYPEINFO();
SFX_DECL_VIEWFACTORY(ViewShellBase);
SFX_DECL_INTERFACE(SD_IF_SDVIEWSHELLBASE);
// ViewShellBase (SfxViewFrame *pFrame, USHORT nFlags);
/** This constructor is used by the view factory of the SFX macros.
Note that LateInit() has to be called after the constructor
terminates and before doing anything else.
*/
ViewShellBase (
SfxViewFrame *pFrame,
SfxViewShell* pOldShell,
ViewShell::ShellType eDefaultSubShell = ViewShell::ST_IMPRESS);
virtual ~ViewShellBase (void);
/** This method is part of the object construction. It HAS to be called
after the constructor has created a new object.
*/
virtual void LateInit (void);
ViewShellManager& GetViewShellManager (void) const;
/** Return the main view shell stacked on the called ViewShellBase
object. This is usually the view shell displayed in the center
pane.
*/
ViewShell* GetMainViewShell (void) const;
PaneManager& GetPaneManager (void);
/** When given a view frame this static method returns the
corresponding sd::ViewShellBase object.
@return
When the SfxViewShell of the given frame is not a
ViewShellBase object then NULL is returned.
*/
static ViewShellBase* GetViewShellBase (SfxViewFrame* pFrame);
DrawDocShell* GetDocShell (void) const;
SdDrawDocument* GetDocument (void) const;
/** Callback function for retrieving item values related to menu entries.
*/
void GetMenuState (SfxItemSet& rSet);
/** Callback function for general slot calls. At the moment these are
slots for switching the pane docking windows on and off.
*/
void Execute (SfxRequest& rRequest);
/** Callback function for retrieving item values related to certain
slots. This is the companion of Execute() and handles the slots
concerned with showing the pane docking windows.
*/
void GetState (SfxItemSet& rSet);
/** Make sure that mpMainController points to a controller that matches
the current stacked view shell. If that is not the case the current
controller is replaced by a new one. Otherwise this method returns
without changing anything.
*/
void UpdateController (void);
SvBorder GetBorder (bool bOuterResize);
virtual void InnerResizePixel (const Point& rOrigin, const Size& rSize);
virtual void OuterResizePixel (const Point& rOrigin, const Size& rSize);
/** This call is forwarded to the main sub-shell.
*/
virtual ErrCode DoVerb (long nVerb);
/// Forwarded to the print manager.
virtual SfxPrinter* GetPrinter (BOOL bCreate = FALSE);
/// Forwarded to the print manager.
virtual USHORT SetPrinter (
SfxPrinter* pNewPrinter,
USHORT nDiffFlags = SFX_PRINTER_ALL);
/// Forwarded to the print manager.
virtual PrintDialog* CreatePrintDialog (::Window *pParent);
/// Forwarded to the print manager.
virtual SfxTabPage* CreatePrintOptionsPage (
::Window *pParent,
const SfxItemSet &rOptions);
/// Forwarded to the print manager.
virtual USHORT Print (SfxProgress& rProgress, PrintDialog* pDialog);
/// Forwarded to the print manager.
virtual ErrCode DoPrint (
SfxPrinter *pPrinter,
PrintDialog *pPrintDialog,
BOOL bSilent);
/// Forwarded to the print manager.
USHORT SetPrinterOptDlg (
SfxPrinter* pNewPrinter,
USHORT nDiffFlags = SFX_PRINTER_ALL,
BOOL _bShowDialog = TRUE);
virtual void PreparePrint (PrintDialog* pPrintDialog);
/// Forward methods to main sub shell.
virtual void WriteUserDataSequence (
::com::sun::star::uno::Sequence <
::com::sun::star::beans::PropertyValue >&,
sal_Bool bBrowse = sal_False);
virtual void ReadUserDataSequence (
const ::com::sun::star::uno::Sequence <
::com::sun::star::beans::PropertyValue >&,
sal_Bool bBrowse = sal_False);
virtual void Activate (BOOL IsMDIActivate);
virtual void Deactivate (BOOL IsMDIActivate);
virtual void UIActivate (SvInPlaceObject *pIPObj);
virtual void UIDeactivate (SvInPlaceObject *pIPObj);
virtual void SetZoomFactor (
const Fraction &rZoomX,
const Fraction &rZoomY);
virtual USHORT PrepareClose (BOOL bUI = TRUE, BOOL bForBrowsing = FALSE);
virtual void WriteUserData (String&, BOOL bBrowse = FALSE);
virtual void ReadUserData (const String&, BOOL bBrowse = FALSE);
virtual SdrView* GetDrawView (void) const;
virtual void AdjustPosSizePixel (const Point &rOfs, const Size &rSize);
/** Arrange GUI elements of the pane which shows the given view shell.
@return
The returned border contains the controls placed by the method.
*/
SvBorder ArrangeGUIElements (const Point& rOrigin, const Size& rSize);
/** When <TRUE/> is given, then the mouse shape is set to hour glass (or
whatever the busy shape looks like on the system.)
*/
void SetBusyState (bool bBusy);
protected:
osl::Mutex maMutex;
/** The view tab bar is the control for switching between different
views in one pane.
*/
::std::auto_ptr<ViewTabBar> mpViewTabBar;
virtual void SFX_NOTIFY(SfxBroadcaster& rBC,
const TypeId& rBCType,
const SfxHint& rHint,
const TypeId& rHintType);
private:
::std::auto_ptr<ViewShellManager> mpViewShellManager;
::std::auto_ptr<PaneManager> mpPaneManager;
DrawDocShell* mpDocShell;
SdDrawDocument* mpDocument;
/// The print manager is responsible for printing documents.
PrintManager maPrintManager;
::std::auto_ptr<FormShellManager> mpFormShellManager;
/** Common code of OuterResizePixel() and InnerResizePixel().
*/
void ResizePixel (
const Point& rOrigin,
const Size& rSize,
bool bOuterResize);
};
} // end of namespace sd
#endif
<|endoftext|>
|
<commit_before>#include <cstdlib>
#include <string>
#include <iostream>
#include <luna/server.h>
//int print_out_key (void *cls, enum MHD_ValueKind kind,
// const char *key, const char *value)
//{
// std::cout << key << ": " << value << std::endl;
// return MHD_YES;
//}
//static int answer_to_connection(void *cls,
// struct MHD_Connection *connection,
// const char *url,
// const char *method,
// const char *version,
// const char *upload_data,
// size_t *upload_data_size,
// void **con_cls)
//{
// std::cout << "New " << method << " request for " << url << " using version " << version << std::endl;
// MHD_get_connection_values (connection, MHD_HEADER_KIND, &print_out_key, NULL);
//
// return MHD_NO;
//}
using namespace luna;
int main(void)
{
auto port_str = std::getenv("PORT");
const uint16_t PORT = port_str ? std::stoi(port_str) : 8888;
server server{server::port{PORT}};
server.handle_response(request_method::GET, "/ohyeah", [](std::vector<std::string> matches, query_params params, response& response) -> status_code
{
std::cout << "oh yeah!" << std::endl;
for (const auto &match : matches)
{
std::cout << " " << match << std::endl;
}
response = {"text/json", "{\"foo\": true}"};
return 200;
});
server.handle_response(request_method::GET, "^/documents/(i[0-9a-f]{6})(?:/([0-9]*))?", [](std::vector<std::string> matches, query_params params, response& response) -> status_code
{
std::cout << "documents" << std::endl;
for (const auto &match : matches)
{
std::cout << " " << match << std::endl;
}
response = {"text/json", "Yes"};
return 200;
});
server.start();
// struct MHD_Daemon *daemon;
//
// daemon = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY, PORT, NULL, NULL,
// &answer_to_connection, NULL, MHD_OPTION_END);
// if (NULL == daemon) return 1;
//
while (1); //TODO HAHAHAHAHAH
//
// MHD_stop_daemon (daemon);
// return 0;
}<commit_msg>Make the first example match the README<commit_after>#include <string>
#include <iostream>
#include <luna/server.h>
using namespace luna;
int main(void)
{
server server{server::port{8443}};
server.handle_response(request_method::GET, "/ohyeah", [](std::vector<std::string> matches, query_params params, response& response) -> status_code
{
response = {"text/json", "{\"koolade\": true}"};
return 200;
});
server.handle_response(request_method::GET, "^/documents/(i[0-9a-f]{6})", [](std::vector<std::string> matches, query_params params, response& response) -> status_code
{
auto document_id = matches[1];
response = {"text/html", "<h1>Serving up document "+document_id+"</h1>"};
return 200;
});
server.start();
while (1); //run until you get killed. Not the best way.
}<|endoftext|>
|
<commit_before>#include "statefs.hpp"
#include "config.hpp"
#include <statefs/provider.h>
#include <statefs/util.h>
#include <cor/so.hpp>
#include <cor/util.h>
#include <cor/util.hpp>
#include <sys/eventfd.h>
#include <iostream>
#include <stdio.h>
#include <stdbool.h>
#include <poll.h>
namespace config
{
namespace fs = boost::filesystem;
template <typename ReceiverT>
void from_dir(std::string const &cfg_src, ReceiverT receiver)
{
trace() << "Config dir " << cfg_src << std::endl;
std::for_each(fs::directory_iterator(cfg_src),
fs::directory_iterator(),
[&receiver](fs::directory_entry const &d) {
if (d.path().extension() == file_ext())
from_file(d.path().string(), receiver);
});
}
template <typename ReceiverT>
void load(std::string const &cfg_src, ReceiverT receiver)
{
if (cfg_src.empty())
return;
if (fs::is_regular_file(cfg_src))
return from_file(cfg_src, receiver);
if (fs::is_directory(cfg_src))
return from_dir(cfg_src, receiver);
throw cor::Error("Unknown configuration source %s", cfg_src.c_str());
}
namespace nl = cor::notlisp;
void to_property(nl::expr_ptr expr, property_type &dst)
{
if (!expr)
throw cor::Error("to_property: Null");
switch(expr->type()) {
case nl::Expr::String:
dst = expr->value();
break;
case nl::Expr::Integer:
dst = (long)*expr;
break;
case nl::Expr::Real:
dst = (double)*expr;
break;
default:
throw cor::Error("%s is not compatible with Any",
expr->value().c_str());
}
}
std::string to_string(property_type const &p)
{
std::string res;
boost::apply_visitor(AnyToString(res), p);
return res;
}
Property::Property(std::string const &name,
property_type const &defval,
unsigned access)
: ObjectExpr(name), defval_(defval), access_(access)
{}
AnyToString::AnyToString(std::string &res) : dst(res) {}
void AnyToString::operator () (std::string const &v) const
{
dst = v;
}
Namespace::Namespace(std::string const &name, storage_type &&props)
: ObjectExpr(name), props_(props)
{}
Plugin::Plugin(std::string const &name, std::string const &path,
storage_type &&namespaces)
: ObjectExpr(name)
, path(path)
, mtime_(fs::last_write_time(path))
, namespaces_(namespaces)
{}
struct PropertyInt : public boost::static_visitor<>
{
long &dst;
PropertyInt(long &res) : dst(res) {}
void operator () (long v) const
{
dst = v;
}
template <typename OtherT>
void operator () (OtherT &v) const
{
throw cor::Error("Wrong property type");
}
};
long to_integer(property_type const &src)
{
long res;
boost::apply_visitor(PropertyInt(res), src);
return res;
}
std::string Property::defval() const
{
return to_string(defval_);
}
int Property::mode(int umask) const
{
int res = 0;
if (access_ & Read)
res |= 0444;
if (access_ & Write)
res |= 0222;
return res & ~umask;
}
nl::env_ptr mk_parse_env()
{
using nl::env_ptr;
nl::lambda_type plugin = [](env_ptr, nl::expr_list_type ¶ms) {
nl::ListAccessor src(params);
std::string name, path;
src.required(nl::to_string, name).required(nl::to_string, path);
Plugin::storage_type namespaces;
push_rest_casted(src, namespaces);
return nl::expr_ptr(new Plugin(name, path, std::move(namespaces)));
};
nl::lambda_type prop = [](env_ptr, nl::expr_list_type ¶ms) {
nl::ListAccessor src(params);
std::string name;
property_type defval;
src.required(nl::to_string, name).required(to_property, defval);
std::unordered_map<std::string, property_type> options = {
// default option values
{"behavior", "discrete"},
{"access", (long)Property::Read}
};
nl::rest(src, [](nl::expr_ptr &) {},
[&options](nl::expr_ptr &k, nl::expr_ptr &v) {
auto &p = options[k->value()];
to_property(v, p);
});
unsigned access = to_integer(options["access"]);
if (to_string(options["behavior"]) == "discrete")
access |= Property::Subscribe;
nl::expr_ptr res(new Property(name, defval, access));
return res;
};
nl::lambda_type ns = [](env_ptr, nl::expr_list_type ¶ms) {
nl::ListAccessor src(params);
std::string name;
src.required(nl::to_string, name);
Namespace::storage_type props;
nl::push_rest_casted(src, props);
nl::expr_ptr res(new Namespace(name, std::move(props)));
return res;
};
using nl::mk_record;
using nl::mk_const;
env_ptr env(new nl::Env({
mk_record("provider", plugin),
mk_record("ns", ns),
mk_record("prop", prop),
mk_const("false", 0),
mk_const("true", 0),
mk_const("discrete", Property::Subscribe),
mk_const("continuous", 0),
mk_const("rw", Property::Write | Property::Read),
}));
return env;
}
namespace inotify = cor::inotify;
Monitor::Monitor
(std::string const &path, on_changed_type on_changed)
: path_([](std::string const &path) {
trace() << "Config monitor for " << path << std::endl;
if (!ensure_dir_exists(path))
throw cor::Error("No config dir %s", path.c_str());
return path;
}(path))
, event_(eventfd(0, 0), cor::only_valid_handle)
, on_changed_(on_changed)
, watch_(new inotify::Watch
(inotify_, path, IN_CREATE | IN_DELETE | IN_MODIFY))
// run thread before loading config to avoid missing configuration
, mon_thread_(std::bind(std::mem_fn(&Monitor::watch_thread), this))
{
using namespace std::placeholders;
config::load(path_, std::bind(std::mem_fn(&Monitor::plugin_add),
this, _1, _2));
}
Monitor::~Monitor()
{
uint64_t v = 1;
::write(event_.value(), &v, sizeof(v));
trace() << "config monitor: waiting to be stopped\n";
mon_thread_.join();
}
void Monitor::plugin_add(std::string const &cfg_path,
std::shared_ptr<config::Plugin> p)
{
auto fname = fs::path(cfg_path).filename().string();
files_providers_[fname] = p;
on_changed_(Added, p);
}
int Monitor::watch_thread()
{
try {
return watch();
} catch (std::exception const &e) {
std::cerr << "Config watcher caught " << e.what() << std::endl;
}
return -1;
}
bool Monitor::process_poll()
{
if (fds_[1].revents) {
uint64_t v;
::read(event_.value(), &v, sizeof(v));
watch_.reset(nullptr);
return false;
}
if (!fds_[0].revents)
return true;
char buf[sizeof(inotify_event) + 256];
int rc;
// read all events
while ((rc = inotify_.read(buf, sizeof(buf))) > (int)sizeof(buf)) {}
// configuration is changed rarely (only on
// un/installation of plugins), so it is simplier and more
// robust just to iterate through 'em and calculate
// changes each time anything changed in the configuration
// directory
std::unordered_map<std::string, std::string> cur_config_paths;
typedef std::pair<std::string, std::time_t> file_info_type;
std::set<file_info_type> cur, prev;
std::for_each
(fs::directory_iterator(path_), fs::directory_iterator(),
[&](fs::directory_entry const &d) {
auto p = d.path();
if (d.path().extension() == file_ext())
cur_config_paths[p.filename().string()]
= fs::canonical(p).string();
});
for (auto &kv : cur_config_paths) {
auto const& fname = kv.first;
auto mtime = fs::last_write_time(fs::path(path_) / fname);
cur.insert({fname, mtime});
}
for (auto &kv : files_providers_) {
auto const& fname = kv.first;
auto mtime = fs::last_write_time(kv.second->path);
prev.insert({fname, mtime});
}
std::list<file_info_type> added, removed;
std::set_difference(cur.begin(), cur.end(),
prev.begin(), prev.end(),
std::back_inserter(added));
std::set_difference(prev.begin(), prev.end(),
cur.begin(), cur.end(),
std::back_inserter(removed));
for (auto &nt : added) {
auto const& v = nt.first;
using namespace std::placeholders;
from_file(cur_config_paths[v],
std::bind(std::mem_fn(&Monitor::plugin_add), this, _1, _2));
}
for (auto &nt : removed) {
auto const& v = nt.first;
on_changed_(Removed, files_providers_[v]);
}
return true;
}
int Monitor::watch()
{
int rc;
fds_.fill({-1, POLLIN | POLLPRI, 0});
fds_[0].fd = inotify_.fd();
fds_[1].fd = event_.value();
while ((rc = poll(&fds_[0], fds_.size(), -1)) >= 0
&& process_poll()) {}
std::cerr << "exiting config watch poll rc=" << rc << std::endl;
return rc;
}
static std::string statefs_variant_2str(struct statefs_variant const *src)
{
std::stringstream ss;
switch (src->tag)
{
case statefs_variant_int:
ss << src->i;
break;
case statefs_variant_uint:
ss << src->u;
break;
case statefs_variant_bool:
ss << (src->b ? "1" : "0");
break;
case statefs_variant_real:
ss << src->r;
break;
case statefs_variant_cstr:
ss << "\"" << src->s << "\"";
break;
default:
return "\"\"";
}
return ss.str();
}
class Dump
{
public:
Dump(std::ostream &out, provider_handle_type &&provider)
: out(out), provider_(std::move(provider)) {}
std::string dump(std::string const&);
private:
Dump(Dump const&);
Dump & operator = (Dump const&);
void dump_info(int level, statefs_node const *node);
void dump_prop(int level, statefs_property const *prop);
void dump_ns(int level, statefs_namespace const *ns);
std::ostream &out;
provider_handle_type provider_;
};
void Dump::dump_info(int level, statefs_node const *node)
{
if (!node->info)
return;
auto info = node->info;
while (info->name) {
out << " :" << info->name << " "
<< statefs_variant_2str(&info->value);
++info;
}
}
void Dump::dump_prop(int level, statefs_property const *prop)
{
out << "\n";
out << "(" << "prop" << " \"" << prop->node.name << "\" "
<< statefs_variant_2str(&prop->default_value);
dump_info(level, &prop->node);
int attr = provider_->io.getattr(prop);
if (!(attr & STATEFS_ATTR_DISCRETE))
out << " :behavior continuous";
out << ")";
}
typedef cor::Handle<
cor::GenericHandleTraits<
intptr_t, 0> > branch_handle_type;
void Dump::dump_ns(int level, statefs_namespace const *ns)
{
out << "\n";
out << "(" << "ns" << " \"" << ns->node.name << "\"";
dump_info(level, &ns->node);
branch_handle_type iter
(statefs_first(&ns->branch),
[&ns](intptr_t v) {
statefs_branch_release(&ns->branch, v);
});
auto next = [&ns, &iter]() {
return mk_property_handle(statefs_prop_get(&ns->branch, iter.value()));
};
auto prop = next();
while (prop) {
dump_prop(level + 1, prop.get());
statefs_next(&ns->branch, &iter.ref());
prop = next();
}
out << ")";
}
std::string Dump::dump(std::string const& path)
{
auto const &root = provider_->root;
auto provider_name = root.node.name;
out << "(" << "provider" << " \"" << provider_name << "\"";
dump_info(0, &root.node);
out << " \"" << path << "\"";
branch_handle_type iter
(statefs_first(&root.branch),
[&root](intptr_t v) {
statefs_branch_release(&root.branch, v);
});
auto next = [&root, &iter]() {
return mk_namespace_handle
(statefs_ns_get(&root.branch, iter.value()));
};
auto ns = next();
while (ns) {
dump_ns(1, ns.get());
statefs_next(&root.branch, &iter.ref());
ns = next();
}
out << ")\n";
return provider_name;
}
static std::string mk_provider_path(std::string const &path)
{
namespace fs = boost::filesystem;
auto provider_path = fs::path(path);
provider_path = fs::canonical(provider_path);
return provider_path.generic_string();
}
std::string dump(std::ostream &dst, std::string const &path)
{
auto full_path = mk_provider_path(path);
cor::SharedLib lib(full_path, RTLD_LAZY);
if (!lib.is_loaded()) {
throw cor::Error("Can't load library %s: %s"
, path.c_str(), ::dlerror());
}
return Dump(dst, mk_provider_handle(lib)).dump(full_path);
}
void save(std::string const &cfg_dir, std::string const &provider_fname)
{
namespace fs = boost::filesystem;
std::stringstream ss;
auto name = dump(ss, provider_fname);
auto cfg_path = fs::path(cfg_dir);
cfg_path /= (name + config::file_ext());
std::ofstream out(cfg_path.generic_string());
out << ss.str();
out.close();
// touch configuration directory, be sure dir monitor watch will
// observe changes
std::time_t n = std::time(0);
fs::last_write_time(cfg_dir, n);
}
} // config
<commit_msg>[config] first removing provider, then adding<commit_after>#include "statefs.hpp"
#include "config.hpp"
#include <statefs/provider.h>
#include <statefs/util.h>
#include <cor/so.hpp>
#include <cor/util.h>
#include <cor/util.hpp>
#include <sys/eventfd.h>
#include <iostream>
#include <stdio.h>
#include <stdbool.h>
#include <poll.h>
namespace config
{
namespace fs = boost::filesystem;
template <typename ReceiverT>
void from_dir(std::string const &cfg_src, ReceiverT receiver)
{
trace() << "Config dir " << cfg_src << std::endl;
std::for_each(fs::directory_iterator(cfg_src),
fs::directory_iterator(),
[&receiver](fs::directory_entry const &d) {
if (d.path().extension() == file_ext())
from_file(d.path().string(), receiver);
});
}
template <typename ReceiverT>
void load(std::string const &cfg_src, ReceiverT receiver)
{
if (cfg_src.empty())
return;
if (fs::is_regular_file(cfg_src))
return from_file(cfg_src, receiver);
if (fs::is_directory(cfg_src))
return from_dir(cfg_src, receiver);
throw cor::Error("Unknown configuration source %s", cfg_src.c_str());
}
namespace nl = cor::notlisp;
void to_property(nl::expr_ptr expr, property_type &dst)
{
if (!expr)
throw cor::Error("to_property: Null");
switch(expr->type()) {
case nl::Expr::String:
dst = expr->value();
break;
case nl::Expr::Integer:
dst = (long)*expr;
break;
case nl::Expr::Real:
dst = (double)*expr;
break;
default:
throw cor::Error("%s is not compatible with Any",
expr->value().c_str());
}
}
std::string to_string(property_type const &p)
{
std::string res;
boost::apply_visitor(AnyToString(res), p);
return res;
}
Property::Property(std::string const &name,
property_type const &defval,
unsigned access)
: ObjectExpr(name), defval_(defval), access_(access)
{}
AnyToString::AnyToString(std::string &res) : dst(res) {}
void AnyToString::operator () (std::string const &v) const
{
dst = v;
}
Namespace::Namespace(std::string const &name, storage_type &&props)
: ObjectExpr(name), props_(props)
{}
Plugin::Plugin(std::string const &name, std::string const &path,
storage_type &&namespaces)
: ObjectExpr(name)
, path(path)
, mtime_(fs::last_write_time(path))
, namespaces_(namespaces)
{}
struct PropertyInt : public boost::static_visitor<>
{
long &dst;
PropertyInt(long &res) : dst(res) {}
void operator () (long v) const
{
dst = v;
}
template <typename OtherT>
void operator () (OtherT &v) const
{
throw cor::Error("Wrong property type");
}
};
long to_integer(property_type const &src)
{
long res;
boost::apply_visitor(PropertyInt(res), src);
return res;
}
std::string Property::defval() const
{
return to_string(defval_);
}
int Property::mode(int umask) const
{
int res = 0;
if (access_ & Read)
res |= 0444;
if (access_ & Write)
res |= 0222;
return res & ~umask;
}
nl::env_ptr mk_parse_env()
{
using nl::env_ptr;
nl::lambda_type plugin = [](env_ptr, nl::expr_list_type ¶ms) {
nl::ListAccessor src(params);
std::string name, path;
src.required(nl::to_string, name).required(nl::to_string, path);
Plugin::storage_type namespaces;
push_rest_casted(src, namespaces);
return nl::expr_ptr(new Plugin(name, path, std::move(namespaces)));
};
nl::lambda_type prop = [](env_ptr, nl::expr_list_type ¶ms) {
nl::ListAccessor src(params);
std::string name;
property_type defval;
src.required(nl::to_string, name).required(to_property, defval);
std::unordered_map<std::string, property_type> options = {
// default option values
{"behavior", "discrete"},
{"access", (long)Property::Read}
};
nl::rest(src, [](nl::expr_ptr &) {},
[&options](nl::expr_ptr &k, nl::expr_ptr &v) {
auto &p = options[k->value()];
to_property(v, p);
});
unsigned access = to_integer(options["access"]);
if (to_string(options["behavior"]) == "discrete")
access |= Property::Subscribe;
nl::expr_ptr res(new Property(name, defval, access));
return res;
};
nl::lambda_type ns = [](env_ptr, nl::expr_list_type ¶ms) {
nl::ListAccessor src(params);
std::string name;
src.required(nl::to_string, name);
Namespace::storage_type props;
nl::push_rest_casted(src, props);
nl::expr_ptr res(new Namespace(name, std::move(props)));
return res;
};
using nl::mk_record;
using nl::mk_const;
env_ptr env(new nl::Env({
mk_record("provider", plugin),
mk_record("ns", ns),
mk_record("prop", prop),
mk_const("false", 0),
mk_const("true", 0),
mk_const("discrete", Property::Subscribe),
mk_const("continuous", 0),
mk_const("rw", Property::Write | Property::Read),
}));
return env;
}
namespace inotify = cor::inotify;
Monitor::Monitor
(std::string const &path, on_changed_type on_changed)
: path_([](std::string const &path) {
trace() << "Config monitor for " << path << std::endl;
if (!ensure_dir_exists(path))
throw cor::Error("No config dir %s", path.c_str());
return path;
}(path))
, event_(eventfd(0, 0), cor::only_valid_handle)
, on_changed_(on_changed)
, watch_(new inotify::Watch
(inotify_, path, IN_CREATE | IN_DELETE | IN_MODIFY))
// run thread before loading config to avoid missing configuration
, mon_thread_(std::bind(std::mem_fn(&Monitor::watch_thread), this))
{
using namespace std::placeholders;
config::load(path_, std::bind(std::mem_fn(&Monitor::plugin_add),
this, _1, _2));
}
Monitor::~Monitor()
{
uint64_t v = 1;
::write(event_.value(), &v, sizeof(v));
trace() << "config monitor: waiting to be stopped\n";
mon_thread_.join();
}
void Monitor::plugin_add(std::string const &cfg_path,
std::shared_ptr<config::Plugin> p)
{
auto fname = fs::path(cfg_path).filename().string();
files_providers_[fname] = p;
on_changed_(Added, p);
}
int Monitor::watch_thread()
{
try {
return watch();
} catch (std::exception const &e) {
std::cerr << "Config watcher caught " << e.what() << std::endl;
}
return -1;
}
bool Monitor::process_poll()
{
std::cerr << "Providers config is maybe changed" << std::endl;
if (fds_[1].revents) {
uint64_t v;
::read(event_.value(), &v, sizeof(v));
watch_.reset(nullptr);
return false;
}
if (!fds_[0].revents)
return true;
char buf[sizeof(inotify_event) + 256];
int rc;
// read all events
while ((rc = inotify_.read(buf, sizeof(buf))) > (int)sizeof(buf)) {}
// configuration is changed rarely (only on
// un/installation of plugins), so it is simplier and more
// robust just to iterate through 'em and calculate
// changes each time anything changed in the configuration
// directory
std::unordered_map<std::string, std::string> cur_config_paths;
typedef std::pair<std::string, std::time_t> file_info_type;
std::set<file_info_type> cur, prev;
std::for_each
(fs::directory_iterator(path_), fs::directory_iterator(),
[&](fs::directory_entry const &d) {
auto p = d.path();
if (d.path().extension() == file_ext())
cur_config_paths[p.filename().string()]
= fs::canonical(p).string();
});
for (auto &kv : cur_config_paths) {
auto const& fname = kv.first;
auto mtime = fs::last_write_time(fs::path(path_) / fname);
cur.insert({fname, mtime});
}
for (auto &kv : files_providers_) {
auto const& fname = kv.first;
auto mtime = fs::last_write_time(kv.second->path);
prev.insert({fname, mtime});
}
std::list<file_info_type> added, removed;
std::set_difference(cur.begin(), cur.end(),
prev.begin(), prev.end(),
std::back_inserter(added));
std::set_difference(prev.begin(), prev.end(),
cur.begin(), cur.end(),
std::back_inserter(removed));
for (auto &nt : removed) {
auto const& v = nt.first;
std::cerr << "Removed " << v << std::endl;
on_changed_(Removed, files_providers_[v]);
}
for (auto &nt : added) {
auto const& v = nt.first;
std::cerr << "Added " << v << std::endl;
using namespace std::placeholders;
from_file(cur_config_paths[v],
std::bind(std::mem_fn(&Monitor::plugin_add), this, _1, _2));
}
return true;
}
int Monitor::watch()
{
int rc;
fds_.fill({-1, POLLIN | POLLPRI, 0});
fds_[0].fd = inotify_.fd();
fds_[1].fd = event_.value();
while ((rc = poll(&fds_[0], fds_.size(), -1)) >= 0
&& process_poll()) {}
std::cerr << "exiting config watch poll rc=" << rc << std::endl;
return rc;
}
static std::string statefs_variant_2str(struct statefs_variant const *src)
{
std::stringstream ss;
switch (src->tag)
{
case statefs_variant_int:
ss << src->i;
break;
case statefs_variant_uint:
ss << src->u;
break;
case statefs_variant_bool:
ss << (src->b ? "1" : "0");
break;
case statefs_variant_real:
ss << src->r;
break;
case statefs_variant_cstr:
ss << "\"" << src->s << "\"";
break;
default:
return "\"\"";
}
return ss.str();
}
class Dump
{
public:
Dump(std::ostream &out, provider_handle_type &&provider)
: out(out), provider_(std::move(provider)) {}
std::string dump(std::string const&);
private:
Dump(Dump const&);
Dump & operator = (Dump const&);
void dump_info(int level, statefs_node const *node);
void dump_prop(int level, statefs_property const *prop);
void dump_ns(int level, statefs_namespace const *ns);
std::ostream &out;
provider_handle_type provider_;
};
void Dump::dump_info(int level, statefs_node const *node)
{
if (!node->info)
return;
auto info = node->info;
while (info->name) {
out << " :" << info->name << " "
<< statefs_variant_2str(&info->value);
++info;
}
}
void Dump::dump_prop(int level, statefs_property const *prop)
{
out << "\n";
out << "(" << "prop" << " \"" << prop->node.name << "\" "
<< statefs_variant_2str(&prop->default_value);
dump_info(level, &prop->node);
int attr = provider_->io.getattr(prop);
if (!(attr & STATEFS_ATTR_DISCRETE))
out << " :behavior continuous";
out << ")";
}
typedef cor::Handle<
cor::GenericHandleTraits<
intptr_t, 0> > branch_handle_type;
void Dump::dump_ns(int level, statefs_namespace const *ns)
{
out << "\n";
out << "(" << "ns" << " \"" << ns->node.name << "\"";
dump_info(level, &ns->node);
branch_handle_type iter
(statefs_first(&ns->branch),
[&ns](intptr_t v) {
statefs_branch_release(&ns->branch, v);
});
auto next = [&ns, &iter]() {
return mk_property_handle(statefs_prop_get(&ns->branch, iter.value()));
};
auto prop = next();
while (prop) {
dump_prop(level + 1, prop.get());
statefs_next(&ns->branch, &iter.ref());
prop = next();
}
out << ")";
}
std::string Dump::dump(std::string const& path)
{
auto const &root = provider_->root;
auto provider_name = root.node.name;
out << "(" << "provider" << " \"" << provider_name << "\"";
dump_info(0, &root.node);
out << " \"" << path << "\"";
branch_handle_type iter
(statefs_first(&root.branch),
[&root](intptr_t v) {
statefs_branch_release(&root.branch, v);
});
auto next = [&root, &iter]() {
return mk_namespace_handle
(statefs_ns_get(&root.branch, iter.value()));
};
auto ns = next();
while (ns) {
dump_ns(1, ns.get());
statefs_next(&root.branch, &iter.ref());
ns = next();
}
out << ")\n";
return provider_name;
}
static std::string mk_provider_path(std::string const &path)
{
namespace fs = boost::filesystem;
auto provider_path = fs::path(path);
provider_path = fs::canonical(provider_path);
return provider_path.generic_string();
}
std::string dump(std::ostream &dst, std::string const &path)
{
auto full_path = mk_provider_path(path);
cor::SharedLib lib(full_path, RTLD_LAZY);
if (!lib.is_loaded()) {
throw cor::Error("Can't load library %s: %s"
, path.c_str(), ::dlerror());
}
return Dump(dst, mk_provider_handle(lib)).dump(full_path);
}
void save(std::string const &cfg_dir, std::string const &provider_fname)
{
namespace fs = boost::filesystem;
std::stringstream ss;
auto name = dump(ss, provider_fname);
auto cfg_path = fs::path(cfg_dir);
cfg_path /= (name + config::file_ext());
std::ofstream out(cfg_path.generic_string());
out << ss.str();
out.close();
// touch configuration directory, be sure dir monitor watch will
// observe changes
std::time_t n = std::time(0);
fs::last_write_time(cfg_dir, n);
}
} // config
<|endoftext|>
|
<commit_before>/* ---------------------------------------------------------------------------
** This software is in the public domain, furnished "as is", without technical
** support, and with no warranty, express or implied, as to its usefulness for
** any purpose.
**
** V4l2Device.cpp
**
** -------------------------------------------------------------------------*/
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
// libv4l2
#include <linux/videodev2.h>
#include "logger.h"
#include "V4l2Device.h"
std::string fourcc(unsigned int format)
{
char formatArray[] = { (char)(format&0xff), (char)((format>>8)&0xff), (char)((format>>16)&0xff), (char)((format>>24)&0xff), 0 };
return std::string(formatArray, strlen(formatArray));
}
// -----------------------------------------
// V4L2Device
// -----------------------------------------
V4l2Device::V4l2Device(const V4L2DeviceParameters& params, v4l2_buf_type deviceType) : m_params(params), m_fd(-1), m_deviceType(deviceType), m_bufferSize(0), m_format(0)
{
}
V4l2Device::~V4l2Device()
{
this->close();
}
void V4l2Device::close()
{
if (m_fd != -1)
::close(m_fd);
m_fd = -1;
}
// query current format
void V4l2Device::queryFormat()
{
struct v4l2_format fmt;
memset(&fmt,0,sizeof(fmt));
fmt.type = m_deviceType;
if (0 == ioctl(m_fd,VIDIOC_G_FMT,&fmt))
{
m_format = fmt.fmt.pix.pixelformat;
m_width = fmt.fmt.pix.width;
m_height = fmt.fmt.pix.height;
m_bufferSize = fmt.fmt.pix.sizeimage;
LOG(NOTICE) << m_params.m_devName << ":" << fourcc(m_format) << " size:" << m_width << "x" << m_height << " bufferSize:" << m_bufferSize;
}
}
// intialize the V4L2 connection
bool V4l2Device::init(unsigned int mandatoryCapabilities)
{
struct stat sb;
if ( (stat(m_params.m_devName.c_str(), &sb)==0) && ((sb.st_mode & S_IFMT) == S_IFCHR) )
{
if (initdevice(m_params.m_devName.c_str(), mandatoryCapabilities) == -1)
{
LOG(ERROR) << "Cannot init device:" << m_params.m_devName;
}
}
else
{
// open a normal file
m_fd = open(m_params.m_devName.c_str(), O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU);
}
return (m_fd!=-1);
}
// intialize the V4L2 device
int V4l2Device::initdevice(const char *dev_name, unsigned int mandatoryCapabilities)
{
m_fd = open(dev_name, m_params.m_openFlags);
if (m_fd < 0)
{
LOG(ERROR) << "Cannot open device:" << m_params.m_devName << " " << strerror(errno);
this->close();
return -1;
}
if (checkCapabilities(m_fd,mandatoryCapabilities) !=0)
{
this->close();
return -1;
}
if (configureFormat(m_fd) !=0)
{
this->close();
return -1;
}
if (configureParam(m_fd) !=0)
{
this->close();
return -1;
}
return m_fd;
}
// check needed V4L2 capabilities
int V4l2Device::checkCapabilities(int fd, unsigned int mandatoryCapabilities)
{
struct v4l2_capability cap;
memset(&(cap), 0, sizeof(cap));
if (-1 == ioctl(fd, VIDIOC_QUERYCAP, &cap))
{
LOG(ERROR) << "Cannot get capabilities for device:" << m_params.m_devName << " " << strerror(errno);
return -1;
}
LOG(NOTICE) << "driver:" << cap.driver << " capabilities:" << std::hex << cap.capabilities << " mandatory:" << mandatoryCapabilities << std::dec;
if ((cap.capabilities & V4L2_CAP_VIDEO_OUTPUT)) LOG(NOTICE) << m_params.m_devName << " support output";
if ((cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) LOG(NOTICE) << m_params.m_devName << " support capture";
if ((cap.capabilities & V4L2_CAP_READWRITE)) LOG(NOTICE) << m_params.m_devName << " support read/write";
if ((cap.capabilities & V4L2_CAP_STREAMING)) LOG(NOTICE) << m_params.m_devName << " support streaming";
if ((cap.capabilities & V4L2_CAP_TIMEPERFRAME)) LOG(NOTICE) << m_params.m_devName << " support timeperframe";
if ( (cap.capabilities & mandatoryCapabilities) != mandatoryCapabilities )
{
LOG(ERROR) << "Mandatory capability not available for device:" << m_params.m_devName;
return -1;
}
return 0;
}
// configure capture format
int V4l2Device::configureFormat(int fd)
{
// get current configuration
this->queryFormat();
unsigned int width = m_width;
unsigned int height = m_height;
if (m_params.m_width != 0) {
width= m_params.m_width;
}
if (m_params.m_height != 0) {
height= m_params.m_height;
}
if (m_params.m_formatList.size()==0) {
m_params.m_formatList.push_back(m_format);
}
// try to set format, widht, height
std::list<unsigned int>::iterator it;
for (it = m_params.m_formatList.begin(); it != m_params.m_formatList.end(); ++it) {
unsigned int format = *it;
if (this->configureFormat(fd, format, width, height)==0) {
// format has been set
// get the format again because calling SET-FMT return a bad buffersize using v4l2loopback
this->queryFormat();
return 0;
}
}
return -1;
}
// configure capture format
int V4l2Device::configureFormat(int fd, unsigned int format, unsigned int width, unsigned int height)
{
struct v4l2_format fmt;
memset(&(fmt), 0, sizeof(fmt));
fmt.type = m_deviceType;
fmt.fmt.pix.width = width;
fmt.fmt.pix.height = height;
fmt.fmt.pix.pixelformat = format;
fmt.fmt.pix.field = V4L2_FIELD_ANY;
if (ioctl(fd, VIDIOC_S_FMT, &fmt) == -1)
{
LOG(ERROR) << "Cannot set format:" << fourcc(format) << " for device:" << m_params.m_devName << " " << strerror(errno);
return -1;
}
if (fmt.fmt.pix.pixelformat != format)
{
LOG(ERROR) << "Cannot set pixelformat to:" << fourcc(format) << " format is:" << fourcc(fmt.fmt.pix.pixelformat);
return -1;
}
if ((fmt.fmt.pix.width != width) || (fmt.fmt.pix.height != height))
{
LOG(WARN) << "Cannot set size to:" << width << "x" << height << " size is:" << fmt.fmt.pix.width << "x" << fmt.fmt.pix.height;
}
m_format = fmt.fmt.pix.pixelformat;
m_width = fmt.fmt.pix.width;
m_height = fmt.fmt.pix.height;
m_bufferSize = fmt.fmt.pix.sizeimage;
LOG(NOTICE) << m_params.m_devName << ":" << fourcc(m_format) << " size:" << m_width << "x" << m_height << " bufferSize:" << m_bufferSize;
return 0;
}
// configure capture FPS
int V4l2Device::configureParam(int fd)
{
if (m_params.m_fps!=0)
{
struct v4l2_streamparm param;
memset(&(param), 0, sizeof(param));
param.type = m_deviceType;
param.parm.capture.timeperframe.numerator = 1;
param.parm.capture.timeperframe.denominator = m_params.m_fps;
if (ioctl(fd, VIDIOC_S_PARM, ¶m) == -1)
{
LOG(WARN) << "Cannot set param for device:" << m_params.m_devName << " " << strerror(errno);
}
LOG(NOTICE) << "fps:" << param.parm.capture.timeperframe.numerator << "/" << param.parm.capture.timeperframe.denominator;
LOG(NOTICE) << "nbBuffer:" << param.parm.capture.readbuffers;
}
return 0;
}
<commit_msg>fix config whithout setting format<commit_after>/* ---------------------------------------------------------------------------
** This software is in the public domain, furnished "as is", without technical
** support, and with no warranty, express or implied, as to its usefulness for
** any purpose.
**
** V4l2Device.cpp
**
** -------------------------------------------------------------------------*/
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
// libv4l2
#include <linux/videodev2.h>
#include "logger.h"
#include "V4l2Device.h"
std::string fourcc(unsigned int format)
{
char formatArray[] = { (char)(format&0xff), (char)((format>>8)&0xff), (char)((format>>16)&0xff), (char)((format>>24)&0xff), 0 };
return std::string(formatArray, strlen(formatArray));
}
// -----------------------------------------
// V4L2Device
// -----------------------------------------
V4l2Device::V4l2Device(const V4L2DeviceParameters& params, v4l2_buf_type deviceType) : m_params(params), m_fd(-1), m_deviceType(deviceType), m_bufferSize(0), m_format(0)
{
}
V4l2Device::~V4l2Device()
{
this->close();
}
void V4l2Device::close()
{
if (m_fd != -1)
::close(m_fd);
m_fd = -1;
}
// query current format
void V4l2Device::queryFormat()
{
struct v4l2_format fmt;
memset(&fmt,0,sizeof(fmt));
fmt.type = m_deviceType;
if (0 == ioctl(m_fd,VIDIOC_G_FMT,&fmt))
{
m_format = fmt.fmt.pix.pixelformat;
m_width = fmt.fmt.pix.width;
m_height = fmt.fmt.pix.height;
m_bufferSize = fmt.fmt.pix.sizeimage;
LOG(NOTICE) << m_params.m_devName << ":" << fourcc(m_format) << " size:" << m_width << "x" << m_height << " bufferSize:" << m_bufferSize;
}
}
// intialize the V4L2 connection
bool V4l2Device::init(unsigned int mandatoryCapabilities)
{
struct stat sb;
if ( (stat(m_params.m_devName.c_str(), &sb)==0) && ((sb.st_mode & S_IFMT) == S_IFCHR) )
{
if (initdevice(m_params.m_devName.c_str(), mandatoryCapabilities) == -1)
{
LOG(ERROR) << "Cannot init device:" << m_params.m_devName;
}
}
else
{
// open a normal file
m_fd = open(m_params.m_devName.c_str(), O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU);
}
return (m_fd!=-1);
}
// intialize the V4L2 device
int V4l2Device::initdevice(const char *dev_name, unsigned int mandatoryCapabilities)
{
m_fd = open(dev_name, m_params.m_openFlags);
if (m_fd < 0)
{
LOG(ERROR) << "Cannot open device:" << m_params.m_devName << " " << strerror(errno);
this->close();
return -1;
}
if (checkCapabilities(m_fd,mandatoryCapabilities) !=0)
{
this->close();
return -1;
}
if (configureFormat(m_fd) !=0)
{
this->close();
return -1;
}
if (configureParam(m_fd) !=0)
{
this->close();
return -1;
}
return m_fd;
}
// check needed V4L2 capabilities
int V4l2Device::checkCapabilities(int fd, unsigned int mandatoryCapabilities)
{
struct v4l2_capability cap;
memset(&(cap), 0, sizeof(cap));
if (-1 == ioctl(fd, VIDIOC_QUERYCAP, &cap))
{
LOG(ERROR) << "Cannot get capabilities for device:" << m_params.m_devName << " " << strerror(errno);
return -1;
}
LOG(NOTICE) << "driver:" << cap.driver << " capabilities:" << std::hex << cap.capabilities << " mandatory:" << mandatoryCapabilities << std::dec;
if ((cap.capabilities & V4L2_CAP_VIDEO_OUTPUT)) LOG(NOTICE) << m_params.m_devName << " support output";
if ((cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) LOG(NOTICE) << m_params.m_devName << " support capture";
if ((cap.capabilities & V4L2_CAP_READWRITE)) LOG(NOTICE) << m_params.m_devName << " support read/write";
if ((cap.capabilities & V4L2_CAP_STREAMING)) LOG(NOTICE) << m_params.m_devName << " support streaming";
if ((cap.capabilities & V4L2_CAP_TIMEPERFRAME)) LOG(NOTICE) << m_params.m_devName << " support timeperframe";
if ( (cap.capabilities & mandatoryCapabilities) != mandatoryCapabilities )
{
LOG(ERROR) << "Mandatory capability not available for device:" << m_params.m_devName;
return -1;
}
return 0;
}
// configure capture format
int V4l2Device::configureFormat(int fd)
{
// get current configuration
this->queryFormat();
unsigned int width = m_width;
unsigned int height = m_height;
if (m_params.m_width != 0) {
width= m_params.m_width;
}
if (m_params.m_height != 0) {
height= m_params.m_height;
}
if ( (m_params.m_formatList.size()==0) && (m_format != 0) ) {
m_params.m_formatList.push_back(m_format);
}
// try to set format, widht, height
std::list<unsigned int>::iterator it;
for (it = m_params.m_formatList.begin(); it != m_params.m_formatList.end(); ++it) {
unsigned int format = *it;
if (this->configureFormat(fd, format, width, height)==0) {
// format has been set
// get the format again because calling SET-FMT return a bad buffersize using v4l2loopback
this->queryFormat();
return 0;
}
}
return -1;
}
// configure capture format
int V4l2Device::configureFormat(int fd, unsigned int format, unsigned int width, unsigned int height)
{
struct v4l2_format fmt;
memset(&(fmt), 0, sizeof(fmt));
fmt.type = m_deviceType;
fmt.fmt.pix.width = width;
fmt.fmt.pix.height = height;
fmt.fmt.pix.pixelformat = format;
fmt.fmt.pix.field = V4L2_FIELD_ANY;
if (ioctl(fd, VIDIOC_S_FMT, &fmt) == -1)
{
LOG(ERROR) << "Cannot set format:" << fourcc(format) << " for device:" << m_params.m_devName << " " << strerror(errno);
return -1;
}
if (fmt.fmt.pix.pixelformat != format)
{
LOG(ERROR) << "Cannot set pixelformat to:" << fourcc(format) << " format is:" << fourcc(fmt.fmt.pix.pixelformat);
return -1;
}
if ((fmt.fmt.pix.width != width) || (fmt.fmt.pix.height != height))
{
LOG(WARN) << "Cannot set size to:" << width << "x" << height << " size is:" << fmt.fmt.pix.width << "x" << fmt.fmt.pix.height;
}
m_format = fmt.fmt.pix.pixelformat;
m_width = fmt.fmt.pix.width;
m_height = fmt.fmt.pix.height;
m_bufferSize = fmt.fmt.pix.sizeimage;
LOG(NOTICE) << m_params.m_devName << ":" << fourcc(m_format) << " size:" << m_width << "x" << m_height << " bufferSize:" << m_bufferSize;
return 0;
}
// configure capture FPS
int V4l2Device::configureParam(int fd)
{
if (m_params.m_fps!=0)
{
struct v4l2_streamparm param;
memset(&(param), 0, sizeof(param));
param.type = m_deviceType;
param.parm.capture.timeperframe.numerator = 1;
param.parm.capture.timeperframe.denominator = m_params.m_fps;
if (ioctl(fd, VIDIOC_S_PARM, ¶m) == -1)
{
LOG(WARN) << "Cannot set param for device:" << m_params.m_devName << " " << strerror(errno);
}
LOG(NOTICE) << "fps:" << param.parm.capture.timeperframe.numerator << "/" << param.parm.capture.timeperframe.denominator;
LOG(NOTICE) << "nbBuffer:" << param.parm.capture.readbuffers;
}
return 0;
}
<|endoftext|>
|
<commit_before>/// \file urbi/uobject.hh
#ifndef URBI_UOBJECT_HH
# define URBI_UOBJECT_HH
# include <string>
# include <libport/fwd.hh>
# include <libport/ufloat.h>
# include <libport/utime.hh>
# include <urbi/fwd.hh>
# include <urbi/export.hh>
# include <urbi/ucallbacks.hh>
# include <urbi/utimer-callback.hh>
# include <urbi/uvar.hh>
# include <urbi/uobject-hub.hh>
// Tell our users that it is fine to use void returning functions.
#define USE_VOID 1
/** Bind a variable to an object.
This macro can only be called from within a class inheriting from
UObject. It binds the UVar x within the object to a variable
with the same name in the corresponding URBI object. */
# define UBindVar(Obj,X) \
(X).init(__name, #X)
/** This macro inverts a UVar in/out accesses.
After this call is made, writes by this module affect the sensed
value, and reads read the target value. Writes by other modules
and URBI code affect the target value, and reads get the sensed
value. Without this call, all operations affect the same
underlying variable. */
# define UOwned(X) \
(X).setOwned()
/// Backward compatibility.
# define USensor(X) \
UOwned(X)
/** Bind the function x in current URBI object to the C++ member
function of same name. The return value and parameters must be of
a basic integral or floating types, char *, std::string, UValue,
UBinary, USound or UImage, or any type that can cast to/from
UValue. */
# define UBindFunction(Obj, X) \
::urbi::createUCallback(__name, "function", this, \
(&Obj::X), __name + "." #X, \
::urbi::functionmap(), false)
/** Registers a function x in current object that will be called each
time the event of same name is triggered. The function will be
called only if the number of arguments match between the function
prototype and the URBI event.
*/
# define UBindEvent(Obj, X) \
::urbi::createUCallback(__name, "event", this, \
(&Obj::X), __name + "." #X, \
::urbi::eventmap(), false)
/** Registers a function x in current object that will be called each
* time the event of same name is triggered, and a function fun called
* when the event ends. The function will be called only if the number
* of arguments match between the function prototype and the URBI
* event.
*/
# define UBindEventEnd(Obj, X, Fun) \
::urbi::createUCallback(__name, "eventend", this, \
(&Obj::X),(&Obj::Fun), __name + "." #X, \
::urbi::eventendmap())
/// Register current object to the UObjectHub named 'hub'.
# define URegister(Hub) \
do { \
objecthub = ::urbi::baseURBIStarterHub::find(#Hub); \
if (objecthub) \
objecthub->addMember(this); \
else \
::urbi::echo("Error: hub name '" #Hub "' is unknown\n"); \
} while (0)
//macro to send urbi commands
# ifndef URBI
/// Send unquoted URBI commands to the server.
/// Add an extra layer of parenthesis for safety.
# define URBI(A) \
::urbi::uobject_unarmorAndSend(# A)
# endif
/// Send \a Args (which is given to a stream and therefore can use <<)
/// to the server.
# define URBI_SEND(Args) \
do { \
std::ostringstream os; \
os << Args; \
URBI(()) << os.str(); \
} while (0)
/// Send "\a Args ; \n".
# define URBI_SEND_COMMAND(Args) \
URBI_SEND(Args << ';' << std::endl)
/** Send "\a Args | \n".
* \b Warning: nothing is executed until a ';' or ',' is sent.
*/
# define URBI_SEND_PIPED_COMMAND(Args) \
URBI_SEND(Args << '|' << std::endl)
namespace urbi
{
typedef int UReturn;
/// an empty dummy UObject used by UVar to set a NotifyChange
/// This avoid coupling a UVar to a particular object
extern URBI_SDK_API UObject* dummyUObject;
// Global function of the urbi:: namespace to access kernel features
/// Write a message to the server debug output. Printf syntax.
URBI_SDK_API void echo(const char* format, ... );
/// Retrieve a UObjectHub based on its name or return 0 if not found.
UObjectHub* getUObjectHub(const std::string& n);
/// Retrieve a UObject based on its name or return 0 if not found.
UObject* getUObject(const std::string& n);
/// Send URBI code (ghost connection in plugin mode, default
/// connection in remote mode).
URBI_SDK_API void uobject_unarmorAndSend(const char* str);
/// Send the string to the connection hosting the UObject.
URBI_SDK_API void send(const char* str);
/// Send buf to the connection hosting the UObject.
URBI_SDK_API void send(void* buf, size_t size);
/// Possible UObject running modes.
enum UObjectMode
{
MODE_PLUGIN=1,
MODE_REMOTE
};
/// Return the mode in which the code is running.
URBI_SDK_API UObjectMode getRunningMode();
/// Return true if the code is running in plugin mode.
inline bool isPluginMode() { return getRunningMode() == MODE_PLUGIN;}
/// Return true if the code is running in remote mode.
inline bool isRemoteMode() { return getRunningMode() == MODE_REMOTE;}
/// Yield execution until next cycle. Process pending messages in remote mode.
URBI_SDK_API void yield();
/// Yield execution until \b deadline is met (see libport::utime()).
URBI_SDK_API void yield_until(libport::utime_t deadline);
/** Yield execution until something else is scheduled, or until a message is
* received in remote mode.
*/
URBI_SDK_API void yield_until_things_changed();
/** If \b s is true, mark the current task as having no side effect.
* This call has no effect in remote mode.
*/
URBI_SDK_API void side_effect_free_set(bool s);
/// Get the current side_effect_free state.
URBI_SDK_API bool side_effect_free_get();
/** Main UObject class definition
Each UObject instance corresponds to an URBI object.
It provides mechanisms to bind variables and functions between
C++ and URBI.
*/
class URBI_SDK_API UObject
{
public:
UObject(const std::string&);
/// dummy UObject constructor
UObject(int);
virtual ~UObject();
// This call registers both an UObject (say of type
// UObjectDerived), and a callback working on it (named here
// fun). createUCallback wants both the object and the callback
// to have the same type, which is not the casem this is static
// type of the former is UObject (its runtime type is indeed
// UObjectDerived though), and the callback wants a
// UObjectDerived. So we need a cast, until a more elegant way
// is found (e.g., using free standing functions instead of a
// member functions).
// These macros provide the following callbacks :
// Notify
// Access | const std::string& | int (T::*fun) () | const
// Change | urbi::UVar& | int (T::*fun) (urbi::UVar&) | non-const
// OnRequest |
# ifdef DOXYGEN
// Doxygen does not handle macros very well so feed it simplified code.
/*!
\brief Call a function each time a variable is modified.
\param v the variable to monitor.
\param fun the function to call each time the variable \b v is modified.
The function is called rigth after the variable v is modified.
*/
void UNotifyChange(UVar& v, int (UObject::*fun)(UVar&));
/*!
\brief Call a function each time a new variable value is available.
\param v the variable to monitor.
\param fun the function to call each time the variable \b v is modified.
This function is similar to UNotifyChange(), but it does not monitor the
changes on \b v. You must explicitly call UVar::requestValue() when you
want the callback function to be called.
The function is called rigth after the variable v is updated.
*/
void UNotifyOnRequest(UVar& v, int (UObject::*fun)(UVar&));
/*!
\brief Call a function each time a variable is accessed.
\param v the variable to monitor.
\param fun the function to call each time the variable \b v is accessed.
The function is called rigth \b before the variable v is accessed, giving
\b fun the oportunity to modify it.
*/
void UNotifyAccess(UVar& v, int (UObject::*fun)(UVar&));
/*!
\brief Setup a callback function that will be called every \t milliseconds.
*/
template <class T>
void USetTimer(ufloat t, int (T::*fun) ());
# else
/// \internal
# define MakeNotify(Type, Notified, Arg, Const, \
TypeString, Name, Map, Owned, \
WithArg, StoreArg) \
template <class T> \
void UNotify##Type (Notified, int (T::*fun) (Arg) Const) \
{ \
UGenericCallback* cb = \
createUCallback (__name, TypeString, \
dynamic_cast<T*>(this), \
fun, Name, Map, Owned); \
\
if (WithArg && cb) \
cb->storage = StoreArg; \
}
/// \internal
# define MakeMetaNotifyArg(Type, Notified, TypeString, Map, Owned, \
Name, StoreArg) \
MakeNotify (Type, Notified, /**/, /**/, TypeString, Name, \
Map, Owned, false, StoreArg); \
MakeNotify (Type, Notified, /**/, const, TypeString, Name, \
Map, Owned, false, StoreArg); \
MakeNotify (Type, Notified, UVar&, /**/, TypeString, Name, \
Map, Owned, true, StoreArg); \
MakeNotify (Type, Notified, UVar&, const, TypeString, Name, \
Map, Owned, true, StoreArg);
/// \internal
# define MakeMetaNotify(Type, TypeString, Map) \
MakeMetaNotifyArg (Type, UVar& v, TypeString, \
Map, v.owned, v.get_name (), &v); \
MakeMetaNotifyArg (Type, const std::string& name, TypeString, \
Map, false, name, new UVar(name));
/// \internal
MakeMetaNotify (Access, "varaccess", accessmap());
/// \internal
MakeMetaNotify (Change, "var", monitormap());
/// \internal
MakeMetaNotify (OnRequest, "var_onrequest", monitormap());
# undef MakeNotify
# undef MakeMetaNotifyArg
# undef MakeMEtaNotify
/// \internal
# define MKUSetTimer(Const, Useless) \
template <class T> \
void USetTimer(ufloat t, int (T::*fun) () Const) \
{ \
new UTimerCallbackobj<T> (__name, t, \
dynamic_cast<T*>(this), fun, timermap()); \
}
MKUSetTimer (/**/, /**/);
MKUSetTimer (const, /**/);
# undef MKUSetTimer
# endif //DOXYGEN
/// Request permanent synchronization for v.
void USync(UVar &v);
/// Name of the object as seen in URBI.
std::string __name;
/// Name of the class the object is derived from.
std::string classname;
/// True when the object has been newed by an urbi command.
bool derived;
UObjectList members;
/// The hub, if it exists.
UObjectHub *objecthub;
/// Send a command to URBI.
int send(const std::string& s);
/// Set a timer that will call the update function every 'period'
/// milliseconds
void USetUpdate(ufloat period);
virtual int update() {return 0;};
/// Set autogrouping facility for each new subclass created.
void UAutoGroup() { autogroup = true; };
/// Called when a subclass is created if autogroup is true.
virtual void addAutoGroup() { UJoinGroup(classname+"s"); };
/// Join the uobject to the 'gpname' group.
virtual void UJoinGroup(const std::string& gpname);
/// Void function used in USync callbacks.
int voidfun() {return 0;};
/// Add a group with a 's' after the base class name.
bool autogroup;
/// Flag to know whether the UObject is in remote mode or not
bool remote;
/// Remove all bindings, this method is called by the destructor.
void clean();
/// The load attribute is standard and can be used to control the
/// activity of the object.
UVar load;
private:
/// Pointer to a globalData structure specific to the
/// remote/plugin architectures who defines it.
UObjectData* objectData;
ufloat period;
};
} // end namespace urbi
// This file needs the definition of UObject, so included last.
// To be cleaned later.
# include <urbi/ustarter.hh>
#endif // ! URBI_UOBJECT_HH
<commit_msg>#Define URBI_UOBJECT_VERSION 2.<commit_after>/// \file urbi/uobject.hh
#ifndef URBI_UOBJECT_HH
# define URBI_UOBJECT_HH
# include <string>
# include <libport/fwd.hh>
# include <libport/ufloat.h>
# include <libport/utime.hh>
# include <urbi/fwd.hh>
# include <urbi/export.hh>
# include <urbi/ucallbacks.hh>
# include <urbi/utimer-callback.hh>
# include <urbi/uvar.hh>
# include <urbi/uobject-hub.hh>
// Tell our users that it is fine to use void returning functions.
#define USE_VOID 1
#define URBI_UOBJECT_VERSION 2
/** Bind a variable to an object.
This macro can only be called from within a class inheriting from
UObject. It binds the UVar x within the object to a variable
with the same name in the corresponding URBI object. */
# define UBindVar(Obj,X) \
(X).init(__name, #X)
/** This macro inverts a UVar in/out accesses.
After this call is made, writes by this module affect the sensed
value, and reads read the target value. Writes by other modules
and URBI code affect the target value, and reads get the sensed
value. Without this call, all operations affect the same
underlying variable. */
# define UOwned(X) \
(X).setOwned()
/// Backward compatibility.
# define USensor(X) \
UOwned(X)
/** Bind the function x in current URBI object to the C++ member
function of same name. The return value and parameters must be of
a basic integral or floating types, char *, std::string, UValue,
UBinary, USound or UImage, or any type that can cast to/from
UValue. */
# define UBindFunction(Obj, X) \
::urbi::createUCallback(__name, "function", this, \
(&Obj::X), __name + "." #X, \
::urbi::functionmap(), false)
/** Registers a function x in current object that will be called each
time the event of same name is triggered. The function will be
called only if the number of arguments match between the function
prototype and the URBI event.
*/
# define UBindEvent(Obj, X) \
::urbi::createUCallback(__name, "event", this, \
(&Obj::X), __name + "." #X, \
::urbi::eventmap(), false)
/** Registers a function x in current object that will be called each
* time the event of same name is triggered, and a function fun called
* when the event ends. The function will be called only if the number
* of arguments match between the function prototype and the URBI
* event.
*/
# define UBindEventEnd(Obj, X, Fun) \
::urbi::createUCallback(__name, "eventend", this, \
(&Obj::X),(&Obj::Fun), __name + "." #X, \
::urbi::eventendmap())
/// Register current object to the UObjectHub named 'hub'.
# define URegister(Hub) \
do { \
objecthub = ::urbi::baseURBIStarterHub::find(#Hub); \
if (objecthub) \
objecthub->addMember(this); \
else \
::urbi::echo("Error: hub name '" #Hub "' is unknown\n"); \
} while (0)
//macro to send urbi commands
# ifndef URBI
/// Send unquoted URBI commands to the server.
/// Add an extra layer of parenthesis for safety.
# define URBI(A) \
::urbi::uobject_unarmorAndSend(# A)
# endif
/// Send \a Args (which is given to a stream and therefore can use <<)
/// to the server.
# define URBI_SEND(Args) \
do { \
std::ostringstream os; \
os << Args; \
URBI(()) << os.str(); \
} while (0)
/// Send "\a Args ; \n".
# define URBI_SEND_COMMAND(Args) \
URBI_SEND(Args << ';' << std::endl)
/** Send "\a Args | \n".
* \b Warning: nothing is executed until a ';' or ',' is sent.
*/
# define URBI_SEND_PIPED_COMMAND(Args) \
URBI_SEND(Args << '|' << std::endl)
namespace urbi
{
typedef int UReturn;
/// an empty dummy UObject used by UVar to set a NotifyChange
/// This avoid coupling a UVar to a particular object
extern URBI_SDK_API UObject* dummyUObject;
// Global function of the urbi:: namespace to access kernel features
/// Write a message to the server debug output. Printf syntax.
URBI_SDK_API void echo(const char* format, ... );
/// Retrieve a UObjectHub based on its name or return 0 if not found.
UObjectHub* getUObjectHub(const std::string& n);
/// Retrieve a UObject based on its name or return 0 if not found.
UObject* getUObject(const std::string& n);
/// Send URBI code (ghost connection in plugin mode, default
/// connection in remote mode).
URBI_SDK_API void uobject_unarmorAndSend(const char* str);
/// Send the string to the connection hosting the UObject.
URBI_SDK_API void send(const char* str);
/// Send buf to the connection hosting the UObject.
URBI_SDK_API void send(void* buf, size_t size);
/// Possible UObject running modes.
enum UObjectMode
{
MODE_PLUGIN=1,
MODE_REMOTE
};
/// Return the mode in which the code is running.
URBI_SDK_API UObjectMode getRunningMode();
/// Return true if the code is running in plugin mode.
inline bool isPluginMode() { return getRunningMode() == MODE_PLUGIN;}
/// Return true if the code is running in remote mode.
inline bool isRemoteMode() { return getRunningMode() == MODE_REMOTE;}
/// Yield execution until next cycle. Process pending messages in remote mode.
URBI_SDK_API void yield();
/// Yield execution until \b deadline is met (see libport::utime()).
URBI_SDK_API void yield_until(libport::utime_t deadline);
/** Yield execution until something else is scheduled, or until a message is
* received in remote mode.
*/
URBI_SDK_API void yield_until_things_changed();
/** If \b s is true, mark the current task as having no side effect.
* This call has no effect in remote mode.
*/
URBI_SDK_API void side_effect_free_set(bool s);
/// Get the current side_effect_free state.
URBI_SDK_API bool side_effect_free_get();
/** Main UObject class definition
Each UObject instance corresponds to an URBI object.
It provides mechanisms to bind variables and functions between
C++ and URBI.
*/
class URBI_SDK_API UObject
{
public:
UObject(const std::string&);
/// dummy UObject constructor
UObject(int);
virtual ~UObject();
// This call registers both an UObject (say of type
// UObjectDerived), and a callback working on it (named here
// fun). createUCallback wants both the object and the callback
// to have the same type, which is not the casem this is static
// type of the former is UObject (its runtime type is indeed
// UObjectDerived though), and the callback wants a
// UObjectDerived. So we need a cast, until a more elegant way
// is found (e.g., using free standing functions instead of a
// member functions).
// These macros provide the following callbacks :
// Notify
// Access | const std::string& | int (T::*fun) () | const
// Change | urbi::UVar& | int (T::*fun) (urbi::UVar&) | non-const
// OnRequest |
# ifdef DOXYGEN
// Doxygen does not handle macros very well so feed it simplified code.
/*!
\brief Call a function each time a variable is modified.
\param v the variable to monitor.
\param fun the function to call each time the variable \b v is modified.
The function is called rigth after the variable v is modified.
*/
void UNotifyChange(UVar& v, int (UObject::*fun)(UVar&));
/*!
\brief Call a function each time a new variable value is available.
\param v the variable to monitor.
\param fun the function to call each time the variable \b v is modified.
This function is similar to UNotifyChange(), but it does not monitor the
changes on \b v. You must explicitly call UVar::requestValue() when you
want the callback function to be called.
The function is called rigth after the variable v is updated.
*/
void UNotifyOnRequest(UVar& v, int (UObject::*fun)(UVar&));
/*!
\brief Call a function each time a variable is accessed.
\param v the variable to monitor.
\param fun the function to call each time the variable \b v is accessed.
The function is called rigth \b before the variable v is accessed, giving
\b fun the oportunity to modify it.
*/
void UNotifyAccess(UVar& v, int (UObject::*fun)(UVar&));
/*!
\brief Setup a callback function that will be called every \t milliseconds.
*/
template <class T>
void USetTimer(ufloat t, int (T::*fun) ());
# else
/// \internal
# define MakeNotify(Type, Notified, Arg, Const, \
TypeString, Name, Map, Owned, \
WithArg, StoreArg) \
template <class T> \
void UNotify##Type (Notified, int (T::*fun) (Arg) Const) \
{ \
UGenericCallback* cb = \
createUCallback (__name, TypeString, \
dynamic_cast<T*>(this), \
fun, Name, Map, Owned); \
\
if (WithArg && cb) \
cb->storage = StoreArg; \
}
/// \internal
# define MakeMetaNotifyArg(Type, Notified, TypeString, Map, Owned, \
Name, StoreArg) \
MakeNotify (Type, Notified, /**/, /**/, TypeString, Name, \
Map, Owned, false, StoreArg); \
MakeNotify (Type, Notified, /**/, const, TypeString, Name, \
Map, Owned, false, StoreArg); \
MakeNotify (Type, Notified, UVar&, /**/, TypeString, Name, \
Map, Owned, true, StoreArg); \
MakeNotify (Type, Notified, UVar&, const, TypeString, Name, \
Map, Owned, true, StoreArg);
/// \internal
# define MakeMetaNotify(Type, TypeString, Map) \
MakeMetaNotifyArg (Type, UVar& v, TypeString, \
Map, v.owned, v.get_name (), &v); \
MakeMetaNotifyArg (Type, const std::string& name, TypeString, \
Map, false, name, new UVar(name));
/// \internal
MakeMetaNotify (Access, "varaccess", accessmap());
/// \internal
MakeMetaNotify (Change, "var", monitormap());
/// \internal
MakeMetaNotify (OnRequest, "var_onrequest", monitormap());
# undef MakeNotify
# undef MakeMetaNotifyArg
# undef MakeMEtaNotify
/// \internal
# define MKUSetTimer(Const, Useless) \
template <class T> \
void USetTimer(ufloat t, int (T::*fun) () Const) \
{ \
new UTimerCallbackobj<T> (__name, t, \
dynamic_cast<T*>(this), fun, timermap()); \
}
MKUSetTimer (/**/, /**/);
MKUSetTimer (const, /**/);
# undef MKUSetTimer
# endif //DOXYGEN
/// Request permanent synchronization for v.
void USync(UVar &v);
/// Name of the object as seen in URBI.
std::string __name;
/// Name of the class the object is derived from.
std::string classname;
/// True when the object has been newed by an urbi command.
bool derived;
UObjectList members;
/// The hub, if it exists.
UObjectHub *objecthub;
/// Send a command to URBI.
int send(const std::string& s);
/// Set a timer that will call the update function every 'period'
/// milliseconds
void USetUpdate(ufloat period);
virtual int update() {return 0;};
/// Set autogrouping facility for each new subclass created.
void UAutoGroup() { autogroup = true; };
/// Called when a subclass is created if autogroup is true.
virtual void addAutoGroup() { UJoinGroup(classname+"s"); };
/// Join the uobject to the 'gpname' group.
virtual void UJoinGroup(const std::string& gpname);
/// Void function used in USync callbacks.
int voidfun() {return 0;};
/// Add a group with a 's' after the base class name.
bool autogroup;
/// Flag to know whether the UObject is in remote mode or not
bool remote;
/// Remove all bindings, this method is called by the destructor.
void clean();
/// The load attribute is standard and can be used to control the
/// activity of the object.
UVar load;
private:
/// Pointer to a globalData structure specific to the
/// remote/plugin architectures who defines it.
UObjectData* objectData;
ufloat period;
};
} // end namespace urbi
// This file needs the definition of UObject, so included last.
// To be cleaned later.
# include <urbi/ustarter.hh>
#endif // ! URBI_UOBJECT_HH
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2009, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/// \file libuco/urbi-main.cc
#include <libport/cli.hh>
#include <libport/containers.hh>
#include <urbi/umain.hh>
extern "C"
{
int urbi_main(int argc, const char* argv[],
bool block, bool errors)
{
return urbi::main(argc, argv, block, errors);
}
int urbi_main_args(const libport::cli_args_type& args,
bool block, bool errors)
{
return urbi::main(args, block, errors);
}
}
namespace urbi
{
int
main(int argc, const char* argv[], bool block, bool errors)
{
libport::cli_args_type args;
// For some reason, I failed to use std::copy here.
for (int i = 0; i < argc; ++i)
args << std::string(argv[i]);
return main(args, block, errors);
}
}
<commit_msg>Call libport::program_initialize in every entry point.<commit_after>/*
* Copyright (C) 2009, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/// \file libuco/urbi-main.cc
#include <libport/cli.hh>
#include <libport/containers.hh>
#include <urbi/umain.hh>
extern "C"
{
int urbi_main(int argc, const char* argv[],
bool block, bool errors)
{
libport::program_initialize(argc, const_cast<char**>(argv));
return urbi::main(argc, argv, block, errors);
}
int urbi_main_args(const libport::cli_args_type& args,
bool block, bool errors)
{
libport::program_initialize(args);
return urbi::main(args, block, errors);
}
}
namespace urbi
{
int
main(int argc, const char* argv[], bool block, bool errors)
{
libport::program_initialize(argc, const_cast<char**>(argv));
libport::cli_args_type args;
// For some reason, I failed to use std::copy here.
for (int i = 0; i < argc; ++i)
args << std::string(argv[i]);
return main(args, block, errors);
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "filesystem.h"
#include "utils.h"
#include "fsexcept.h"
#define BOOT_OFFSET 0*1024
#define FAT_OFFSET 1*1024
#define ROOTDIR_OFFSET 9*1024
#define DATA_OFFSET 10*1024
FileSystem::FileSystem(const std::string &partfname):part_filename(partfname), initialized(false){
memset(fat, 0x00, sizeof(fat));
}
FileSystem::~FileSystem(){
dumpfat();
}
void FileSystem::debug(){
::debug("Debugging the filesystem class...");
if (this->init() != RET_OK){
::debug("Init failed.");
}
if (this->load() != RET_OK){
::debug("Load failed.");
}
this->makedir("/home");
this->makedir("/home/box");
this->makedir("/home/box/bolo");
this->createfile("/home/box/torto.txt");
this->createfile("/home/box/cusco.txt");
this->unlink("/home/box/torto.txt");
std::vector<std::string> resp;
this->listdir("/home/box", resp);
for (unsigned int i=0; i<resp.size(); i++){
std::cout << "ls: " << resp[i] << std::endl;
}
int stop=1; // mvdebug
}
int FileSystem::init(){
remove(part_filename.c_str());
createdummy();
// step 1: writeout 1024 0xbb's
unsigned char bootblock[1024];
memset(bootblock, 0xbb, sizeof(bootblock));
writeblock(bootblock, 0);
// step 2: writeout the fat "header"
unsigned char fatheader[8192] = {0xff, 0xfd,
0xff, 0xfe,
0xff, 0xfe,
0xff, 0xfe,
0xff, 0xfe,
0xff, 0xfe,
0xff, 0xfe,
0xff, 0xfe,
0xff, 0xfe,
0xff, 0xff};
memset(fatheader+20, 0x00, sizeof(fatheader)-20);
for (unsigned int i=0; i<8; i++){
writeblock(&(fatheader[i*1024]), (i+1)*1024);
}
// step 3: we no longer have to writeout the blank rest because we now have a whole blankened dummy file from the beginning
return RET_OK;
}
int FileSystem::load(){
for (unsigned int i=0; i<8; i++){
readblock(&(fat[i*1024]), (i+1) * 1024);
}
initialized = true;
return RET_OK;
}
int FileSystem::makedir(const std::string &path){
CHECK_INIT
dir_entry_t new_dir_struct;
dir_entry_t dir_cluster[32];
unsigned short cluster_offset = 0;
const std::string new_dir_name = utils_basename(path);
int cof_i = traverse_path(path, ROOTDIR_OFFSET);
if (cof_i == -1){
std::string aux = "Could not follow path: ";
aux += path;
throw FSExcept(aux, RET_INTERNAL_ERROR);
} else{
cluster_offset = cof_i;
}
readblock(dir_cluster, cluster_offset);
if (has_in_dir(new_dir_name, dir_cluster)){
return RET_DIR_ALREADY_EXISTS;
}
const unsigned short d_idx = find_free_in_dir(dir_cluster);
unsigned short f_idx = 0;
int test_aux = find_free_fat();
if (test_aux == -1){
return RET_FAT_FULL;
} else {
f_idx = test_aux;
}
fmt_ushort_into_uchar8pair(&(fat[f_idx*2]), 0xffff);
fmt_char8_into_uchar8(new_dir_struct.filename, new_dir_name.c_str());
new_dir_struct.attributes = 1;
fmt_ushort_into_uchar8pair(new_dir_struct.first_block, f_idx);
fmt_uint_into_uchar8quad(new_dir_struct.size, 1024);
memcpy(&dir_cluster[d_idx], &new_dir_struct, sizeof(dir_entry_t));
dumpfat();
writeblock(dir_cluster, cluster_offset);
return RET_OK;
}
int FileSystem::listdir(const std::string &path, std::vector<std::string> &result){
CHECK_INIT
dir_entry_t dir_cluster[32];
unsigned short cluster_offset = 0;
std::string banzai = path;
banzai += "/xoxoxo";
int cof_i = traverse_path(banzai, ROOTDIR_OFFSET); // BANZAI!!!!!!
if (cof_i == -1){
std::string aux = "Could not follow path: ";
aux += path;
throw FSExcept(aux, RET_INTERNAL_ERROR);
} else{
cluster_offset = cof_i;
}
readblock(dir_cluster, cluster_offset);
std::vector<std::string> ret;
for (unsigned int i=0; i<32; i++){
if (dir_cluster[i].filename[0] != 0x00){
std::string aux = fmt_ascii7_to_stdstr(dir_cluster[i].filename);
ret.push_back(aux);
}
}
result = ret;
return RET_OK;
}
int FileSystem::createfile(const std::string &path){
CHECK_INIT
dir_entry_t new_dir_struct;
dir_entry_t dir_cluster[32];
unsigned short cluster_offset = 0;
const std::string new_dir_name = utils_basename(path);
int cof_i = traverse_path(path, ROOTDIR_OFFSET);
if (cof_i == -1){
std::string aux = "Could not follow path: ";
aux += path;
throw FSExcept(aux, RET_INTERNAL_ERROR);
} else{
cluster_offset = cof_i;
}
readblock(dir_cluster, cluster_offset);
if (has_in_dir(new_dir_name, dir_cluster)){
return RET_DIR_ALREADY_EXISTS;
}
const unsigned short d_idx = find_free_in_dir(dir_cluster);
unsigned short f_idx = 0;
int test_aux = find_free_fat();
if (test_aux == -1){
return RET_FAT_FULL;
} else {
f_idx = test_aux;
}
fmt_ushort_into_uchar8pair(&(fat[f_idx*2]), 0xffff);
fmt_char8_into_uchar8(new_dir_struct.filename, new_dir_name.c_str());
new_dir_struct.attributes = 0;
fmt_ushort_into_uchar8pair(new_dir_struct.first_block, f_idx);
fmt_uint_into_uchar8quad(new_dir_struct.size, 0);
memcpy(&dir_cluster[d_idx], &new_dir_struct, sizeof(dir_entry_t));
dumpfat();
writeblock(dir_cluster, cluster_offset);
return RET_OK;
}
int FileSystem::unlink(const std::string &path){
CHECK_INIT
dir_entry_t dir_cluster[32];
unsigned short cluster_offset = 0;
int cof_i = traverse_path(path, ROOTDIR_OFFSET);
if (cof_i == -1){
std::string aux = "Could not follow path: ";
aux += path;
throw FSExcept(aux, RET_INTERNAL_ERROR);
} else{
cluster_offset = cof_i;
}
readblock(dir_cluster, cluster_offset);
std::string target = utils_basename(path);
int rm_i = find_match_in_dir(target, dir_cluster);
if (rm_i == -1){
std::string aux = "Could not follow path: ";
aux += path;
throw FSExcept(aux, RET_INTERNAL_ERROR);
}
// da baixa no arquivo
dir_cluster[rm_i].filename[0] = 0x00;
follow_fat_erase(dir_cluster[rm_i].first_block);
writeblock(dir_cluster, cluster_offset);
dumpfat();
return RET_OK;
}
int FileSystem::write(const std::string &path, const std::string &content){
CHECK_INIT
(void)path;
(void)content;
return -1;
}
int FileSystem::append(const std::string &path, const std::string &content){
CHECK_INIT
(void)path;
(void)content;
return -1;
}
int FileSystem::read(const std::string &path, std::string &content){
CHECK_INIT
(void)path;
(void)content;
return -1;
}
void FileSystem::readblock(void *into, const unsigned int offset) const {
FILE* fd = fopen(part_filename.c_str(), "rb");
if (fd == NULL){
throw FSExcept("Cannot open for reading", RET_INTERNAL_ERROR);
}
fseek(fd, offset, SEEK_SET);
fread(into, 1, 1024, fd);
fclose(fd);
}
void FileSystem::writeblock(const void * buf, const unsigned int offset){
// we have to read and overwrite the whole file :S
unsigned char *wholebuffer = 0;
long fsize = 0;
// open up partition file
FILE* fd_read = fopen(part_filename.c_str(), "rb");
if (fd_read == NULL){
throw FSExcept("Cannot open for reading.", RET_INTERNAL_ERROR);
}
// get its filesize
fseek(fd_read, 0L, SEEK_END);
fsize = ftell(fd_read);
//fseek(fd_read, 0L, SEEK_SET);
rewind(fd_read);
// allocate whole buffer (to store the whole file, yes!) and read into it
wholebuffer = (unsigned char*)calloc(fsize, 1);
fread(wholebuffer, 1, fsize, fd_read);
fclose(fd_read);
// change wholebuff contents with what this function was given
memcpy(wholebuffer+offset, buf, 1024);
// and finally write the whole thing back
FILE* fd_write = fopen(part_filename.c_str(), "wb");
if (fd_write == NULL){
throw FSExcept("Cannot open for writing.", RET_INTERNAL_ERROR);
}
// write, close, dealloc.. clenaup code.
fwrite(wholebuffer, 1, fsize, fd_write);
fclose(fd_write);
free(wholebuffer);
}
void FileSystem::createdummy() const {
FILE* fd_write = fopen(part_filename.c_str(), "wb+");
// mvtodo: fopen error treating
// MV: for some reason, using more than a handful of K's on the stack was causing a segfault.
// took hours to figure it out, but theres a really DUMB solution down below
const unsigned long total = 4*1024*1024; // 4 mbs
const unsigned int piece = total / 16;
unsigned char dummybuf[piece];
memset(dummybuf, 0x00, sizeof(dummybuf));
for (unsigned int i=0; i<total/piece; i++){
fwrite(dummybuf, 1, sizeof(dummybuf), fd_write);
}
fclose(fd_write);
}
void FileSystem::dumpfat() {
for (unsigned int i=0; i<8; i++){
writeblock(&(fat[i*1024]), (i+1)*1024);
}
}
bool FileSystem::has_in_dir(const std::string &name, const dir_entry_t *dir) const {
int ret = find_match_in_dir(name, dir);
if (ret == -1){
return false;
} else {
return true;
}
}
int FileSystem::find_match_in_dir(const std::string &name, const dir_entry_t *dir) const {
for (unsigned int i=0; i<32; i++){
if (dir[i].filename[0] != 0x00){
std::string rd_str = fmt_ascii7_to_stdstr(dir[i].filename);
if (rd_str == name){
return i;
}
}
}
return -1;
}
int FileSystem::find_free_in_dir(const dir_entry_t *dir) const{
for (unsigned int i=0; i<32; i++){
if (dir[i].filename[0] == 0x00){
return i;
}
}
return -1;
}
int FileSystem::find_free_fat() const {
for (unsigned int i=0; i<sizeof(fat)/2; i+=2){
if (fat[i] == 0x00){
return (i/2);
}
}
return -1;
}
// percorre um path e devolve o offset do cluster do diretorio pai (ultimo)
int FileSystem::traverse_path(const std::string &path, const unsigned short offsetstart){
int ret = offsetstart;
std::vector<std::string> sep = tokenize_path(path);
std::string nextpath = popleft_path(path);
if (sep.size() == 1){
// we are at the parent. return offset here
return ret;
} else {
// we need to go deeper...
dir_entry_t current_cluster[32];
readblock(current_cluster, offsetstart);
int md_i = find_match_in_dir(sep[0], current_cluster);
if (md_i == -1){
std::string aux = "Could not follow path: ";
aux += path;
throw FSExcept(aux, RET_INTERNAL_ERROR);
}
if (current_cluster[md_i].attributes != 1){
std::string aux = "Could not follow path (non-dir in the middle!): ";
aux += path;
throw FSExcept(aux, RET_INTERNAL_ERROR);
}
unsigned short fid = fmt_uchar8pair_to_ushort(current_cluster[md_i].first_block);
ret = traverse_path(nextpath, fid*1024);
return ret;
}
}
void FileSystem::follow_fat_erase(const unsigned char *fb){
// persegue um first block (fb) na fat e vai liberando na fat.
// esta funcao nao dumpeia a fat pro disco. chamar manualmente depois!
unsigned short fid = fmt_uchar8pair_to_ushort(fb);
if (fat[fid*2] == 0xff && fat[(fid*2)+1] == 0xff){ // EOF
// limpa e sai...
fat[fid*2] = 0x00;
fat[(fid*2)+1] = 0x00;
return;
} else {
// limpa e persegue
unsigned char auxbuf[2];
auxbuf[0] = fat[fid*2];
auxbuf[1] = fat[(fid*2)+1];
fat[fid*2] = 0x00;
fat[(fid*2)+1] = 0x00;
follow_fat_erase(auxbuf);
}
}
<commit_msg>adding error checking when creating dummy file.part<commit_after>#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "filesystem.h"
#include "utils.h"
#include "fsexcept.h"
#define BOOT_OFFSET 0*1024
#define FAT_OFFSET 1*1024
#define ROOTDIR_OFFSET 9*1024
#define DATA_OFFSET 10*1024
FileSystem::FileSystem(const std::string &partfname):part_filename(partfname), initialized(false){
memset(fat, 0x00, sizeof(fat));
}
FileSystem::~FileSystem(){
dumpfat();
}
void FileSystem::debug(){
::debug("Debugging the filesystem class...");
if (this->init() != RET_OK){
::debug("Init failed.");
}
if (this->load() != RET_OK){
::debug("Load failed.");
}
this->makedir("/home");
this->makedir("/home/box");
this->makedir("/home/box/bolo");
this->createfile("/home/box/torto.txt");
this->createfile("/home/box/cusco.txt");
this->unlink("/home/box/torto.txt");
std::vector<std::string> resp;
this->listdir("/home/box", resp);
for (unsigned int i=0; i<resp.size(); i++){
std::cout << "ls: " << resp[i] << std::endl;
}
int stop=1; // mvdebug
}
int FileSystem::init(){
remove(part_filename.c_str());
createdummy();
// step 1: writeout 1024 0xbb's
unsigned char bootblock[1024];
memset(bootblock, 0xbb, sizeof(bootblock));
writeblock(bootblock, 0);
// step 2: writeout the fat "header"
unsigned char fatheader[8192] = {0xff, 0xfd,
0xff, 0xfe,
0xff, 0xfe,
0xff, 0xfe,
0xff, 0xfe,
0xff, 0xfe,
0xff, 0xfe,
0xff, 0xfe,
0xff, 0xfe,
0xff, 0xff};
memset(fatheader+20, 0x00, sizeof(fatheader)-20);
for (unsigned int i=0; i<8; i++){
writeblock(&(fatheader[i*1024]), (i+1)*1024);
}
// step 3: we no longer have to writeout the blank rest because we now have a whole blankened dummy file from the beginning
return RET_OK;
}
int FileSystem::load(){
for (unsigned int i=0; i<8; i++){
readblock(&(fat[i*1024]), (i+1) * 1024);
}
initialized = true;
return RET_OK;
}
int FileSystem::makedir(const std::string &path){
CHECK_INIT
dir_entry_t new_dir_struct;
dir_entry_t dir_cluster[32];
unsigned short cluster_offset = 0;
const std::string new_dir_name = utils_basename(path);
int cof_i = traverse_path(path, ROOTDIR_OFFSET);
if (cof_i == -1){
std::string aux = "Could not follow path: ";
aux += path;
throw FSExcept(aux, RET_INTERNAL_ERROR);
} else{
cluster_offset = cof_i;
}
readblock(dir_cluster, cluster_offset);
if (has_in_dir(new_dir_name, dir_cluster)){
return RET_DIR_ALREADY_EXISTS;
}
const unsigned short d_idx = find_free_in_dir(dir_cluster);
unsigned short f_idx = 0;
int test_aux = find_free_fat();
if (test_aux == -1){
return RET_FAT_FULL;
} else {
f_idx = test_aux;
}
fmt_ushort_into_uchar8pair(&(fat[f_idx*2]), 0xffff);
fmt_char8_into_uchar8(new_dir_struct.filename, new_dir_name.c_str());
new_dir_struct.attributes = 1;
fmt_ushort_into_uchar8pair(new_dir_struct.first_block, f_idx);
fmt_uint_into_uchar8quad(new_dir_struct.size, 1024);
memcpy(&dir_cluster[d_idx], &new_dir_struct, sizeof(dir_entry_t));
dumpfat();
writeblock(dir_cluster, cluster_offset);
return RET_OK;
}
int FileSystem::listdir(const std::string &path, std::vector<std::string> &result){
CHECK_INIT
dir_entry_t dir_cluster[32];
unsigned short cluster_offset = 0;
std::string banzai = path;
banzai += "/xoxoxo";
int cof_i = traverse_path(banzai, ROOTDIR_OFFSET); // BANZAI!!!!!!
if (cof_i == -1){
std::string aux = "Could not follow path: ";
aux += path;
throw FSExcept(aux, RET_INTERNAL_ERROR);
} else{
cluster_offset = cof_i;
}
readblock(dir_cluster, cluster_offset);
std::vector<std::string> ret;
for (unsigned int i=0; i<32; i++){
if (dir_cluster[i].filename[0] != 0x00){
std::string aux = fmt_ascii7_to_stdstr(dir_cluster[i].filename);
ret.push_back(aux);
}
}
result = ret;
return RET_OK;
}
int FileSystem::createfile(const std::string &path){
CHECK_INIT
dir_entry_t new_dir_struct;
dir_entry_t dir_cluster[32];
unsigned short cluster_offset = 0;
const std::string new_dir_name = utils_basename(path);
int cof_i = traverse_path(path, ROOTDIR_OFFSET);
if (cof_i == -1){
std::string aux = "Could not follow path: ";
aux += path;
throw FSExcept(aux, RET_INTERNAL_ERROR);
} else{
cluster_offset = cof_i;
}
readblock(dir_cluster, cluster_offset);
if (has_in_dir(new_dir_name, dir_cluster)){
return RET_DIR_ALREADY_EXISTS;
}
const unsigned short d_idx = find_free_in_dir(dir_cluster);
unsigned short f_idx = 0;
int test_aux = find_free_fat();
if (test_aux == -1){
return RET_FAT_FULL;
} else {
f_idx = test_aux;
}
fmt_ushort_into_uchar8pair(&(fat[f_idx*2]), 0xffff);
fmt_char8_into_uchar8(new_dir_struct.filename, new_dir_name.c_str());
new_dir_struct.attributes = 0;
fmt_ushort_into_uchar8pair(new_dir_struct.first_block, f_idx);
fmt_uint_into_uchar8quad(new_dir_struct.size, 0);
memcpy(&dir_cluster[d_idx], &new_dir_struct, sizeof(dir_entry_t));
dumpfat();
writeblock(dir_cluster, cluster_offset);
return RET_OK;
}
int FileSystem::unlink(const std::string &path){
CHECK_INIT
dir_entry_t dir_cluster[32];
unsigned short cluster_offset = 0;
int cof_i = traverse_path(path, ROOTDIR_OFFSET);
if (cof_i == -1){
std::string aux = "Could not follow path: ";
aux += path;
throw FSExcept(aux, RET_INTERNAL_ERROR);
} else{
cluster_offset = cof_i;
}
readblock(dir_cluster, cluster_offset);
std::string target = utils_basename(path);
int rm_i = find_match_in_dir(target, dir_cluster);
if (rm_i == -1){
std::string aux = "Could not follow path: ";
aux += path;
throw FSExcept(aux, RET_INTERNAL_ERROR);
}
// da baixa no arquivo
dir_cluster[rm_i].filename[0] = 0x00;
follow_fat_erase(dir_cluster[rm_i].first_block);
writeblock(dir_cluster, cluster_offset);
dumpfat();
return RET_OK;
}
int FileSystem::write(const std::string &path, const std::string &content){
CHECK_INIT
(void)path;
(void)content;
return -1;
}
int FileSystem::append(const std::string &path, const std::string &content){
CHECK_INIT
(void)path;
(void)content;
return -1;
}
int FileSystem::read(const std::string &path, std::string &content){
CHECK_INIT
(void)path;
(void)content;
return -1;
}
void FileSystem::readblock(void *into, const unsigned int offset) const {
FILE* fd = fopen(part_filename.c_str(), "rb");
if (fd == NULL){
throw FSExcept("Cannot open for reading", RET_INTERNAL_ERROR);
}
fseek(fd, offset, SEEK_SET);
fread(into, 1, 1024, fd);
fclose(fd);
}
void FileSystem::writeblock(const void * buf, const unsigned int offset){
// we have to read and overwrite the whole file :S
unsigned char *wholebuffer = 0;
long fsize = 0;
// open up partition file
FILE* fd_read = fopen(part_filename.c_str(), "rb");
if (fd_read == NULL){
throw FSExcept("Cannot open for reading.", RET_INTERNAL_ERROR);
}
// get its filesize
fseek(fd_read, 0L, SEEK_END);
fsize = ftell(fd_read);
//fseek(fd_read, 0L, SEEK_SET);
rewind(fd_read);
// allocate whole buffer (to store the whole file, yes!) and read into it
wholebuffer = (unsigned char*)calloc(fsize, 1);
fread(wholebuffer, 1, fsize, fd_read);
fclose(fd_read);
// change wholebuff contents with what this function was given
memcpy(wholebuffer+offset, buf, 1024);
// and finally write the whole thing back
FILE* fd_write = fopen(part_filename.c_str(), "wb");
if (fd_write == NULL){
throw FSExcept("Cannot open for writing.", RET_INTERNAL_ERROR);
}
// write, close, dealloc.. clenaup code.
fwrite(wholebuffer, 1, fsize, fd_write);
fclose(fd_write);
free(wholebuffer);
}
void FileSystem::createdummy() const {
FILE* fd_write = fopen(part_filename.c_str(), "wb+");
if (fd_write == NULL){
throw FSExcept("Cannot create dummy file.part", RET_INTERNAL_ERROR);
}
// MV: for some reason, using more than a handful of K's on the stack was causing a segfault.
// took hours to figure it out, but theres a really DUMB solution down below
const unsigned long total = 4*1024*1024; // 4 mbs
const unsigned int piece = total / 16;
unsigned char dummybuf[piece];
memset(dummybuf, 0x00, sizeof(dummybuf));
for (unsigned int i=0; i<total/piece; i++){
fwrite(dummybuf, 1, sizeof(dummybuf), fd_write);
}
fclose(fd_write);
}
void FileSystem::dumpfat() {
for (unsigned int i=0; i<8; i++){
writeblock(&(fat[i*1024]), (i+1)*1024);
}
}
bool FileSystem::has_in_dir(const std::string &name, const dir_entry_t *dir) const {
int ret = find_match_in_dir(name, dir);
if (ret == -1){
return false;
} else {
return true;
}
}
int FileSystem::find_match_in_dir(const std::string &name, const dir_entry_t *dir) const {
for (unsigned int i=0; i<32; i++){
if (dir[i].filename[0] != 0x00){
std::string rd_str = fmt_ascii7_to_stdstr(dir[i].filename);
if (rd_str == name){
return i;
}
}
}
return -1;
}
int FileSystem::find_free_in_dir(const dir_entry_t *dir) const{
for (unsigned int i=0; i<32; i++){
if (dir[i].filename[0] == 0x00){
return i;
}
}
return -1;
}
int FileSystem::find_free_fat() const {
for (unsigned int i=0; i<sizeof(fat)/2; i+=2){
if (fat[i] == 0x00){
return (i/2);
}
}
return -1;
}
// percorre um path e devolve o offset do cluster do diretorio pai (ultimo)
int FileSystem::traverse_path(const std::string &path, const unsigned short offsetstart){
int ret = offsetstart;
std::vector<std::string> sep = tokenize_path(path);
std::string nextpath = popleft_path(path);
if (sep.size() == 1){
// we are at the parent. return offset here
return ret;
} else {
// we need to go deeper...
dir_entry_t current_cluster[32];
readblock(current_cluster, offsetstart);
int md_i = find_match_in_dir(sep[0], current_cluster);
if (md_i == -1){
std::string aux = "Could not follow path: ";
aux += path;
throw FSExcept(aux, RET_INTERNAL_ERROR);
}
if (current_cluster[md_i].attributes != 1){
std::string aux = "Could not follow path (non-dir in the middle!): ";
aux += path;
throw FSExcept(aux, RET_INTERNAL_ERROR);
}
unsigned short fid = fmt_uchar8pair_to_ushort(current_cluster[md_i].first_block);
ret = traverse_path(nextpath, fid*1024);
return ret;
}
}
void FileSystem::follow_fat_erase(const unsigned char *fb){
// persegue um first block (fb) na fat e vai liberando na fat.
// esta funcao nao dumpeia a fat pro disco. chamar manualmente depois!
unsigned short fid = fmt_uchar8pair_to_ushort(fb);
if (fat[fid*2] == 0xff && fat[(fid*2)+1] == 0xff){ // EOF
// limpa e sai...
fat[fid*2] = 0x00;
fat[(fid*2)+1] = 0x00;
return;
} else {
// limpa e persegue
unsigned char auxbuf[2];
auxbuf[0] = fat[fid*2];
auxbuf[1] = fat[(fid*2)+1];
fat[fid*2] = 0x00;
fat[(fid*2)+1] = 0x00;
follow_fat_erase(auxbuf);
}
}
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software 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.
//
//////////////////////////////////////////////////////////////////////////
#include "IECoreMaya/FromMayaTransformConverter.h"
#include "IECoreMaya/Convert.h"
#include "IECore/CompoundParameter.h"
#include "IECore/TransformationMatrixData.h"
#include "maya/MTransformationMatrix.h"
#include "maya/MFnMatrixData.h"
#include "maya/MFnTransform.h"
#include "maya/MPlug.h"
using namespace IECoreMaya;
static const MFn::Type fromTypes[] = { MFn::kTransform };
static const IECore::TypeId toTypes[] = { IECore::TransformationMatrixdData::staticTypeId() };
FromMayaDagNodeConverter::Description<FromMayaTransformConverter> FromMayaTransformConverter::g_description( fromTypes, toTypes );
FromMayaTransformConverter::FromMayaTransformConverter( const MDagPath &dagPath )
: FromMayaDagNodeConverter( staticTypeName(), "Converts transform nodes.", dagPath )
{
IECore::IntParameter::PresetsMap spacePresets;
spacePresets["Local"] = Local;
spacePresets["World"] = World;
m_spaceParameter = new IECore::IntParameter(
"space",
"The space in which the transfprm is converted.",
World,
Local,
World,
spacePresets,
true
);
parameters()->addParameter( m_spaceParameter );
}
IECore::IntParameterPtr FromMayaTransformConverter::spaceParameter()
{
return m_spaceParameter;
}
IECore::ConstIntParameterPtr FromMayaTransformConverter::spaceParameter() const
{
return m_spaceParameter;
}
IECore::ObjectPtr FromMayaTransformConverter::doConversion( const MDagPath &dagPath, IECore::ConstCompoundObjectPtr operands ) const
{
MTransformationMatrix transform;
if( m_spaceParameter->getNumericValue()==Local )
{
MFnTransform fnT( dagPath );
transform = fnT.transformation();
}
else
{
unsigned instIndex = dagPath.instanceNumber();
MObject dagNode = dagPath.node();
MFnDependencyNode fnN( dagNode );
MPlug plug = fnN.findPlug( "worldMatrix" );
MPlug instPlug = plug.elementByLogicalIndex( instIndex );
MObject matrix;
instPlug.getValue( matrix );
MFnMatrixData fnM( matrix );
transform = fnM.transformation();
}
return new IECore::TransformationMatrixdData( IECore::convert<IECore::TransformationMatrixd, MTransformationMatrix>( transform ) );
}
<commit_msg>Fixed typo<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software 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.
//
//////////////////////////////////////////////////////////////////////////
#include "IECoreMaya/FromMayaTransformConverter.h"
#include "IECoreMaya/Convert.h"
#include "IECore/CompoundParameter.h"
#include "IECore/TransformationMatrixData.h"
#include "maya/MTransformationMatrix.h"
#include "maya/MFnMatrixData.h"
#include "maya/MFnTransform.h"
#include "maya/MPlug.h"
using namespace IECoreMaya;
static const MFn::Type fromTypes[] = { MFn::kTransform };
static const IECore::TypeId toTypes[] = { IECore::TransformationMatrixdData::staticTypeId() };
FromMayaDagNodeConverter::Description<FromMayaTransformConverter> FromMayaTransformConverter::g_description( fromTypes, toTypes );
FromMayaTransformConverter::FromMayaTransformConverter( const MDagPath &dagPath )
: FromMayaDagNodeConverter( staticTypeName(), "Converts transform nodes.", dagPath )
{
IECore::IntParameter::PresetsMap spacePresets;
spacePresets["Local"] = Local;
spacePresets["World"] = World;
m_spaceParameter = new IECore::IntParameter(
"space",
"The space in which the transform is converted.",
World,
Local,
World,
spacePresets,
true
);
parameters()->addParameter( m_spaceParameter );
}
IECore::IntParameterPtr FromMayaTransformConverter::spaceParameter()
{
return m_spaceParameter;
}
IECore::ConstIntParameterPtr FromMayaTransformConverter::spaceParameter() const
{
return m_spaceParameter;
}
IECore::ObjectPtr FromMayaTransformConverter::doConversion( const MDagPath &dagPath, IECore::ConstCompoundObjectPtr operands ) const
{
MTransformationMatrix transform;
if( m_spaceParameter->getNumericValue()==Local )
{
MFnTransform fnT( dagPath );
transform = fnT.transformation();
}
else
{
unsigned instIndex = dagPath.instanceNumber();
MObject dagNode = dagPath.node();
MFnDependencyNode fnN( dagNode );
MPlug plug = fnN.findPlug( "worldMatrix" );
MPlug instPlug = plug.elementByLogicalIndex( instIndex );
MObject matrix;
instPlug.getValue( matrix );
MFnMatrixData fnM( matrix );
transform = fnM.transformation();
}
return new IECore::TransformationMatrixdData( IECore::convert<IECore::TransformationMatrixd, MTransformationMatrix>( transform ) );
}
<|endoftext|>
|
<commit_before>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*******************************************************************************/
//==============================================================================
// CLI utilities
//==============================================================================
#include "cliapplication.h"
#include "cliutils.h"
#include "coresettings.h"
#include "settings.h"
//==============================================================================
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QProcess>
#include <QResource>
#include <QSettings>
#include <QTemporaryFile>
//==============================================================================
namespace OpenCOR {
//==============================================================================
#include "corecliutils.cpp.inl"
//==============================================================================
void initQtMessagePattern()
{
// We don't want to see debug/warning messages when not in debug mode
#ifndef QT_DEBUG
qSetMessagePattern("%{if-debug}%{endif}" \
"%{if-warning}%{endif}" \
"%{if-critical}%{message}%{endif}" \
"%{if-fatal}%{message}%{endif}");
#endif
}
//==============================================================================
void initPluginsPath(const QString &pAppFileName)
{
// Initialise the plugins path
QFileInfo appFileInfo = pAppFileName;
QString appDir;
#ifdef Q_OS_WIN
if (appFileInfo.suffix().isEmpty())
// If pAppFileName has no suffix, then it means we tried to run OpenCOR
// using something like "[OpenCOR]/OpenCOR", in which case QFileInfo()
// will get lost when trying to retrieve the canonical path for OpenCOR.
// Now, when use something like "[OpenCOR]/OpenCOR", it's as if we were
// to use something like "[OpenCOR]/OpenCOR.com", so update appFileInfo
// accordingly
appFileInfo = pAppFileName+".com";
#endif
appDir = QDir::toNativeSeparators(appFileInfo.canonicalPath());
QString pluginsDir = QString();
#if defined(Q_OS_WIN) || defined(Q_OS_LINUX)
pluginsDir = appDir+QDir::separator()+QString("..")+QDir::separator()+"plugins";
if (!QDir(pluginsDir).exists())
// The plugins directory doesn't exist, which should only happen if we
// are trying to run OpenCOR from within Qt Creator, in which case
// OpenCOR's file name will be [OpenCOR]/build/OpenCOR.exe rather than
// [OpenCOR]/build/bin/OpenCOR.exe as it should normally be if we were
// to mimic the case where OpenCOR has been deployed. Then, because the
// plugins are in [OpenCOR]/build/plugins/OpenCOR, we must skip the
// "../" bit. So, yes, it's not neat, but is there another solution?...
pluginsDir = appDir+QDir::separator()+"plugins";
#elif defined(Q_OS_MAC)
pluginsDir = appDir+QDir::separator()+QString("..")+QDir::separator()+"PlugIns";
#else
#error Unsupported platform
#endif
pluginsDir = QDir::toNativeSeparators(QDir(pluginsDir).canonicalPath());
QCoreApplication::setLibraryPaths(QStringList() << pluginsDir);
}
//==============================================================================
void initApplication(QCoreApplication *pApp, QString *pAppDate)
{
// Remove all 'global' instances, in case OpenCOR previously crashed or
// something (and therefore didn't remove all of them before quitting)
OpenCOR::removeGlobalInstances();
// Ignore SSL-related warnings
// Note #1: this is to address an issue with QSslSocket not being able to
// resolve some methods...
// Note #2: see https://github.com/opencor/opencor/issues/516 for more
// information...
qputenv("QT_LOGGING_RULES", "qt.network.ssl.warning=false");
// Set the name of the application
pApp->setApplicationName(QFileInfo(pApp->applicationFilePath()).baseName());
// Retrieve and set the version of the application
QString versionData;
readTextFromFile(":app_versiondate", versionData);
QStringList versionDataList = versionData.split(eolString());
pApp->setApplicationVersion(versionDataList.first());
if (pAppDate)
*pAppDate = versionDataList.last();
}
//==============================================================================
bool cliApplication(QCoreApplication *pApp, int *pRes)
{
// Create and run our CLI application object
CliApplication *cliApp = new CliApplication(pApp);
bool res = cliApp->run(pRes);
delete cliApp;
return res;
}
//==============================================================================
void removeGlobalInstances()
{
// Remove all the 'global' information shared between OpenCOR and its
// different plugins
QSettings(SettingsOrganization, SettingsApplication).remove(SettingsGlobal);
}
//==============================================================================
QString shortVersion(QCoreApplication *pApp)
{
QString res = QString();
QString appVersion = pApp->applicationVersion();
QString bitVersion;
enum {
SizeOfPointer = sizeof(void *)
};
if (SizeOfPointer == 4)
bitVersion = "32-bit";
else if (SizeOfPointer == 8)
bitVersion = "64-bit";
else
bitVersion = QString();
if (!appVersion.contains("-"))
res += "Version ";
else
res += "Snapshot ";
res += appVersion;
if (!bitVersion.isEmpty())
res += " ("+bitVersion+")";
return res;
}
//==============================================================================
QString version(QCoreApplication *pApp)
{
return pApp->applicationName()+" "+shortVersion(pApp);
}
//==============================================================================
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>Some minor cleaning up [ci skip].<commit_after>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*******************************************************************************/
//==============================================================================
// CLI utilities
//==============================================================================
#include "cliapplication.h"
#include "cliutils.h"
#include "coresettings.h"
#include "settings.h"
//==============================================================================
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QProcess>
#include <QResource>
#include <QSettings>
#include <QTemporaryFile>
//==============================================================================
namespace OpenCOR {
//==============================================================================
#include "corecliutils.cpp.inl"
//==============================================================================
void initQtMessagePattern()
{
// We don't want to see debug/warning messages when not in debug mode
#ifndef QT_DEBUG
qSetMessagePattern("%{if-debug}%{endif}" \
"%{if-warning}%{endif}" \
"%{if-critical}%{message}%{endif}" \
"%{if-fatal}%{message}%{endif}");
#endif
}
//==============================================================================
void initPluginsPath(const QString &pAppFileName)
{
// Initialise the plugins path
QFileInfo appFileInfo = pAppFileName;
QString appDir;
#ifdef Q_OS_WIN
if (appFileInfo.suffix().isEmpty())
// If pAppFileName has no suffix, then it means we tried to run OpenCOR
// using something like "[OpenCOR]/OpenCOR", in which case QFileInfo()
// will get lost when trying to retrieve the canonical path for OpenCOR.
// Now, when use something like "[OpenCOR]/OpenCOR", it's as if we were
// to use something like "[OpenCOR]/OpenCOR.com", so update appFileInfo
// accordingly
appFileInfo = pAppFileName+".com";
#endif
appDir = QDir::toNativeSeparators(appFileInfo.canonicalPath());
QString pluginsDir = QString();
#if defined(Q_OS_WIN) || defined(Q_OS_LINUX)
pluginsDir = appDir+QDir::separator()+QString("..")+QDir::separator()+"plugins";
if (!QDir(pluginsDir).exists()) {
// The plugins directory doesn't exist, which should only happen if we
// are trying to run OpenCOR from within Qt Creator, in which case
// OpenCOR's file name will be [OpenCOR]/build/OpenCOR.exe rather than
// [OpenCOR]/build/bin/OpenCOR.exe as it should normally be if we were
// to mimic the case where OpenCOR has been deployed. Then, because the
// plugins are in [OpenCOR]/build/plugins/OpenCOR, we must skip the
// "../" bit. So, yes, it's not neat, but is there another solution?...
pluginsDir = appDir+QDir::separator()+"plugins";
}
#elif defined(Q_OS_MAC)
pluginsDir = appDir+QDir::separator()+QString("..")+QDir::separator()+"PlugIns";
#else
#error Unsupported platform
#endif
pluginsDir = QDir::toNativeSeparators(QDir(pluginsDir).canonicalPath());
QCoreApplication::setLibraryPaths(QStringList() << pluginsDir);
}
//==============================================================================
void initApplication(QCoreApplication *pApp, QString *pAppDate)
{
// Remove all 'global' instances, in case OpenCOR previously crashed or
// something (and therefore didn't remove all of them before quitting)
OpenCOR::removeGlobalInstances();
// Ignore SSL-related warnings
// Note #1: this is to address an issue with QSslSocket not being able to
// resolve some methods...
// Note #2: see https://github.com/opencor/opencor/issues/516 for more
// information...
qputenv("QT_LOGGING_RULES", "qt.network.ssl.warning=false");
// Set the name of the application
pApp->setApplicationName(QFileInfo(pApp->applicationFilePath()).baseName());
// Retrieve and set the version of the application
QString versionData;
readTextFromFile(":app_versiondate", versionData);
QStringList versionDataList = versionData.split(eolString());
pApp->setApplicationVersion(versionDataList.first());
if (pAppDate)
*pAppDate = versionDataList.last();
}
//==============================================================================
bool cliApplication(QCoreApplication *pApp, int *pRes)
{
// Create and run our CLI application object
CliApplication *cliApp = new CliApplication(pApp);
bool res = cliApp->run(pRes);
delete cliApp;
return res;
}
//==============================================================================
void removeGlobalInstances()
{
// Remove all the 'global' information shared between OpenCOR and its
// different plugins
QSettings(SettingsOrganization, SettingsApplication).remove(SettingsGlobal);
}
//==============================================================================
QString shortVersion(QCoreApplication *pApp)
{
QString res = QString();
QString appVersion = pApp->applicationVersion();
QString bitVersion;
enum {
SizeOfPointer = sizeof(void *)
};
if (SizeOfPointer == 4)
bitVersion = "32-bit";
else if (SizeOfPointer == 8)
bitVersion = "64-bit";
else
bitVersion = QString();
if (!appVersion.contains("-"))
res += "Version ";
else
res += "Snapshot ";
res += appVersion;
if (!bitVersion.isEmpty())
res += " ("+bitVersion+")";
return res;
}
//==============================================================================
QString version(QCoreApplication *pApp)
{
return pApp->applicationName()+" "+shortVersion(pApp);
}
//==============================================================================
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|>
|
<commit_before>#include "WaveformUI.h"
#include "main.h"
#include <QQuickFramebufferObject>
#include <QOpenGLFunctions>
class WaveformRenderer : public QQuickFramebufferObject::Renderer, protected QOpenGLFunctions {
QOpenGLShaderProgram *m_program;
public:
WaveformRenderer()
: m_program(0)
, m_fragmentShader() {
initializeOpenGLFunctions();
}
~WaveformRenderer() {
delete m_program;
}
protected:
void changeProgram(QString fragmentShader) {
m_fragmentShader = fragmentShader;
auto program = new QOpenGLShaderProgram();
if(!program->addShaderFromSourceCode(QOpenGLShader::Vertex,
"attribute highp vec4 vertices;"
"varying highp vec2 coords;"
"void main() {"
" gl_Position = vertices;"
" coords = vertices.xy;"
"}")) goto err;
if(!program->addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShader)) goto err;
program->bindAttributeLocation("vertices", 0);
if(!program->link()) goto err;
delete m_program;
m_program = program;
return;
err:
qDebug() << "Error setting shader program";
delete program;
}
QOpenGLFramebufferObject *createFramebufferObject(const QSize &size) override {
return new QOpenGLFramebufferObject(size);
}
void synchronize(QQuickFramebufferObject *item) override {
auto waveformUI = static_cast<WaveformUI *>(item);
auto fs = waveformUI->fragmentShader();
if(fs != m_fragmentShader) changeProgram(fs);
}
void render() override {
if(m_program != 0) {
audio->renderWaveform();
glClearColor(0, 0, 0, 0);
glDisable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
float values[] = {
-1, -1,
1, -1,
-1, 1,
1, 1
};
m_program->bind();
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_1D, audio->m_waveformTexture->textureId());
m_program->setAttributeArray(0, GL_FLOAT, values, 2);
m_program->setUniformValue("iResolution", framebufferObject()->size());
m_program->setUniformValue("iWaveform", 0);
m_program->enableAttributeArray(0);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
m_program->disableAttributeArray(0);
m_program->release();
}
update();
}
QString m_fragmentShader;
};
QString WaveformUI::fragmentShader() {
QMutexLocker locker(&m_fragmentShaderLock);
return m_fragmentShader;
}
void WaveformUI::setFragmentShader(QString fragmentShader) {
{
QMutexLocker locker(&m_fragmentShaderLock);
m_fragmentShader = fragmentShader;
}
emit fragmentShaderChanged(fragmentShader);
}
QQuickFramebufferObject::Renderer *WaveformUI::createRenderer() const {
return new WaveformRenderer();
}
<commit_msg>cleaner c++ / memory management<commit_after>#include "WaveformUI.h"
#include "main.h"
#include <QQuickFramebufferObject>
#include <QOpenGLFunctions>
class WaveformRenderer : public QQuickFramebufferObject::Renderer, protected QOpenGLFunctions {
std::unique_ptr<QOpenGLShaderProgram> m_program{};
protected:
QString m_fragmentShader{};
public:
WaveformRenderer()
{
initializeOpenGLFunctions();
}
~WaveformRenderer() = default;
protected:
void changeProgram(QString fragmentShader)
{
try {
fragmentShader;
auto program = std::make_unique<QOpenGLShaderProgram>();
if(!program->addShaderFromSourceCode(QOpenGLShader::Vertex,
"attribute highp vec4 vertices;"
"varying highp vec2 coords;"
"void main() {"
" gl_Position = vertices;"
" coords = vertices.xy;"
"}"))
throw std::runtime_error("bad vertex shader.");
if(!program->addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShader))
throw std::runtime_eror("bad fragment shader.");
program->bindAttributeLocation("vertices", 0);
if(!program->link())
throw std::runtime_error("linkage failure.");
m_fragmentShader.swap(fragmentShader);
m_program.swap(program);
m_program->setUniformValue("iWaveform", 0);
}catch(const std::exception &e) {
qDebug() << "Error setting shader program" << e.message();
}
}
QOpenGLFramebufferObject *createFramebufferObject(const QSize &size) override
{
return new QOpenGLFramebufferObject(size);
}
void synchronize(QQuickFramebufferObject *item) override
{
auto waveformUI = static_cast<WaveformUI *>(item);
auto fs = waveformUI->fragmentShader();
if(fs != m_fragmentShader) changeProgram(fs);
}
void render() override
{
if(m_program) {
audio->renderWaveform();
glClearColor(0, 0, 0, 0);
glDisable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
float values[] = {
-1, -1,
1, -1,
-1, 1,
1, 1
};
m_program->bind();
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_1D, audio->m_waveformTexture->textureId());
m_program->setAttributeArray(0, GL_FLOAT, values, 2);
m_program->enableAttributeArray(0);
m_program->setUniformValue("iResolution", framebufferObject()->size());
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
m_program->disableAttributeArray(0);
m_program->release();
}
update();
}
};
QString WaveformUI::fragmentShader()
{
QMutexLocker locker(&m_fragmentShaderLock);
return m_fragmentShader;
}
void WaveformUI::setFragmentShader(QString fragmentShader)
{
{
QMutexLocker locker(&m_fragmentShaderLock);
if(m_fragmentShader == fragmentShader)
return;
m_fragmentShader = fragmentShader;
}
emit fragmentShaderChanged(fragmentShader);
}
QQuickFramebufferObject::Renderer *WaveformUI::createRenderer() const
{
return new WaveformRenderer();
}
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <cmath>
#include <iterator>
#include <fstream>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
#include "gzstream.h"
#include "readerwriterqueue.h"
#include "atomicops.h"
namespace mc = moodycamel;
template<typename Out> void split(const std::string &s, char delim, Out result);
std::vector<std::string> split(const std::string &s, char delim);
bool startsWith(const std::string& haystack, const std::string& needle);
double PLtoPP(std::string x);
int main (int argc, char *argv[]) {
const int REF = 3;
const int ALT = 4;
const int FORMAT = 8;
const int ENTRY_START = FORMAT + 1;
const size_t Q_SIZE = 1000;
const std::string QUIT_STR = "~";
igzstream infile(argv[1]);
ogzstream outfile(argv[2]);
mc::BlockingReaderWriterQueue<std::string> lines(Q_SIZE);
// set up consumer thread
std::thread reader([&]() {
double pls [3];
std::string line;
std::string entry;
std::stringstream ss_line;
ss_line.setf(std::ios::fixed,std::ios::floatfield);
ss_line.precision(2);
while (true) {
lines.wait_dequeue(line);
if (line.compare(QUIT_STR) == 0) {
// output any remaining strings
outfile << ss_line.rdbuf();
break;
}
if (startsWith(line, "#")) {
ss_line << line << std::endl;
continue;
}
std::vector<std::string> row = split(line, '\t');
if (row[REF].length() > 1 || row[ALT].length() > 1) {
continue;
}
for (int i = 0; i < FORMAT; i++) {
ss_line << row[i] << '\t';
}
ss_line << row[FORMAT] + ":DS" << '\t';
for (int i = ENTRY_START; i < row.size() - 1; i++) {
std::string token = row[i].substr(row[i].find_last_of(':') + 1);
std::stringstream ss;
ss.str(token);
for (int j = 0; j < 3; j++) {
std::getline(ss, entry, ',');
pls[j] = PLtoPP(entry);
}
double dose = (pls[1] + 2 * pls[2]) / (pls[0] + pls[1] + pls[2]);
ss_line << row[i] + ":" << dose << '\t';
}
int i = row.size() - 1;
std::string token = row[i].substr(row[i].find_last_of(':') + 1);
std::stringstream ss;
ss.str(token);
for (int j = 0; j < 3; j++) {
std::getline(ss, entry, ',');
pls[j] = PLtoPP(entry);
}
double dose = (pls[1] + 2 * pls[2]) / (pls[0] + pls[1] + pls[2]);
ss_line << row[i] + ":" << dose << std::endl;
outfile << ss_line.rdbuf();
ss_line.str(std::string());
}
});
std::string line;
while (std::getline(infile, line)) {
while(!lines.try_enqueue(line)) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
while(!lines.try_enqueue(QUIT_STR)) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
reader.join();
outfile.close();
infile.close();
return 0;
}
template<typename Out>
void split(const std::string &s, char delim, Out result) {
std::stringstream ss;
ss.str(s);
std::string item;
while (std::getline(ss, item, delim)) {
*(result++) = item;
}
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, std::back_inserter(elems));
return elems;
}
bool startsWith(const std::string& haystack, const std::string& needle) {
return needle.length() <= haystack.length()
&& std::equal(needle.begin(), needle.end(), haystack.begin());
}
double PLtoPP(std::string x) {
std::string::size_type sz;
return std::pow(10.0, std::stod(x, &sz) / -10.0);
}
<commit_msg>updated code to be a bit cleaner. need to add proper options and help'<commit_after>#include <algorithm>
#include <cmath>
#include <iterator>
#include <fstream>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
#include "gzstream.h"
#include "readerwriterqueue.h"
#include "atomicops.h"
namespace mc = moodycamel;
template<typename Out> void split(const std::string &s, char delim, Out result);
std::vector<std::string> split(const std::string &s, char delim);
bool startsWith(const std::string& haystack, const std::string& needle);
double PLtoPP(std::string x);
void print_help();
int main (int argc, char *argv[]) {
// VCF constants
const int REF = 3;
const int ALT = 4;
const int FORMAT = 8;
const int ENTRY_START = FORMAT + 1;
const char ENTRY_SEP = ':';
const char PL_SEP = ',';
// taskqueue constants
const size_t Q_SIZE = 1000;
const std::string QUIT_STR = "~";
if (argc < 3) {
print_help();
return 1;
}
// initialize input/ouput streams
igzstream infile(argv[1]);
ogzstream outfile(argv[2]);
// create task queue
mc::BlockingReaderWriterQueue<std::string> lines(Q_SIZE);
// set up consumer thread
std::thread reader([&]() {
double pls [3];
std::string line;
std::string entry;
std::stringstream ss_line;
ss_line.setf(std::ios::fixed,std::ios::floatfield);
ss_line.precision(2);
while (true) {
lines.wait_dequeue(line);
// output any remaining strings and then quit
if (line.compare(QUIT_STR) == 0) {
outfile << ss_line.rdbuf();
break;
}
// buffer the header data
if (startsWith(line, "#")) {
ss_line << line << std::endl;
continue;
}
// grab information for variant
std::vector<std::string> row = split(line, '\t');
// keep only SNPs
if (row[REF].length() > 1 || row[ALT].length() > 1) {
continue;
}
// buffer the variant meta data
for (int i = 0; i < FORMAT; i++) {
ss_line << row[i] << '\t';
}
ss_line << row[FORMAT] << ":DS" << '\t';
// process likelihoods for each sample and convert to dosage
for (int i = ENTRY_START; i < row.size() - 1; i++) {
std::string token = row[i].substr(row[i].find_last_of(ENTRY_SEP) + 1);
std::stringstream ss;
ss.str(token);
for (int j = 0; j < 3; j++) {
std::getline(ss, entry, PL_SEP);
pls[j] = PLtoPP(entry);
}
double dose = (pls[1] + 2 * pls[2]) / (pls[0] + pls[1] + pls[2]);
ss_line << row[i] << ENTRY_SEP << dose << '\t';
}
int i = row.size() - 1;
std::string token = row[i].substr(row[i].find_last_of(ENTRY_SEP) + 1);
std::stringstream ss;
ss.str(token);
for (int j = 0; j < 3; j++) {
std::getline(ss, entry, PL_SEP);
pls[j] = PLtoPP(entry);
}
double dose = (pls[1] + 2 * pls[2]) / (pls[0] + pls[1] + pls[2]);
ss_line << row[i] << ENTRY_SEP << dose << std::endl;
outfile << ss_line.rdbuf();
ss_line.str(std::string());
}
});
// read in a bunch of data to process
// 'sleep' once queue is full
// TODO: replace with proper condition variable instead of sleep/spool
std::string line;
while (std::getline(infile, line)) {
while(!lines.try_enqueue(line)) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
// no lines left push quit signal
while(!lines.try_enqueue(QUIT_STR)) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
// join thread and close files
reader.join();
outfile.close();
infile.close();
return 0;
}
template<typename Out>
void split(const std::string &s, char delim, Out result) {
std::stringstream ss;
ss.str(s);
std::string item;
while (std::getline(ss, item, delim)) {
*(result++) = item;
}
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, std::back_inserter(elems));
return elems;
}
bool startsWith(const std::string& haystack, const std::string& needle) {
return needle.length() <= haystack.length()
&& std::equal(needle.begin(), needle.end(), haystack.begin());
}
double PLtoPP(std::string x) {
std::string::size_type sz;
return std::pow(10.0, std::stod(x, &sz) / -10.0);
}
void print_help() {
std::cerr << "Usage: add_dosage [OPTIONS] INPUT.VCF.GZ OUTPUT.VCF.GZ" << std::endl;
std::cerr << "Try 'add_dosage --help' for more options" << std::endl;
return;
}
<|endoftext|>
|
<commit_before>
#include "model_builder.hpp"
#include "model_basic_primitives.hpp"
#include "model_gltf_save.hpp"
#include "model_msh_save.hpp"
#include "model_scene.hpp"
#include "synced_cout.hpp"
#include <algorithm>
#include <iterator>
#include <string_view>
#include <tuple>
#include <fmt/format.h>
#include <gsl/gsl>
#include <tbb/tbb.h>
using namespace std::literals;
namespace model {
namespace {
template<typename Type>
void merge_containers(std::vector<Type>& into, std::vector<Type>& from) noexcept
{
into.insert(into.end(), std::make_move_iterator(from.begin()),
std::make_move_iterator(from.end()));
from.clear();
}
auto lod_suffix(const Lod lod) -> std::string_view
{
switch (lod) {
case Lod::zero:
return ""sv;
case Lod::one:
return "_lod1"sv;
case Lod::two:
return "_lod2"sv;
case Lod::three:
return "_lod3"sv;
case Lod::lowres:
return "_lowres"sv;
default:
std::terminate();
}
}
auto collision_flags_string(const Collision_flags flags) -> std::string
{
if (flags == Collision_flags::all) return ""s;
std::string str;
if (are_flags_set(flags, Collision_flags::soldier)) str += "s"sv;
if (are_flags_set(flags, Collision_flags::vehicle)) str += "v"sv;
if (are_flags_set(flags, Collision_flags::building)) str += "b"sv;
if (are_flags_set(flags, Collision_flags::terrain)) str += "t"sv;
if (are_flags_set(flags, Collision_flags::ordnance)) str += "o"sv;
if (are_flags_set(flags, Collision_flags::flyer)) str += "f"sv;
return str;
}
auto insert_scene_material(scene::Scene& scene, scene::Material material) -> std::size_t
{
if (auto it = std::find(scene.materials.begin(), scene.materials.end(), material);
it != scene.materials.end()) {
return static_cast<std::size_t>(std::distance(scene.materials.begin(), it));
}
const auto index = scene.materials.size();
scene.materials.emplace_back(std::move(material));
return index;
}
auto make_primitive_visualization_geometry(const Collision_primitive_type type,
const glm::vec3 size) -> scene::Geometry
{
const auto [indices, positions, normals, texcoords, scale] = [=] {
using namespace primitives;
const auto as_spans = [](const auto&... args) {
return std::make_tuple(gsl::make_span(args)...);
};
switch (type) {
case Collision_primitive_type::sphere:
return std::tuple_cat(as_spans(sphere_indices, sphere_vertex_positions,
sphere_vertex_normals, sphere_vertex_texcoords),
std::make_tuple(glm::vec3{size.x}));
case Collision_primitive_type::cylinder:
return std::tuple_cat(as_spans(cylinder_indices, cylinder_vertex_positions,
cylinder_vertex_normals,
cylinder_vertex_texcoords),
std::make_tuple(glm::vec3{size.xyx}));
case Collision_primitive_type::cube:
return std::tuple_cat(as_spans(cube_indices, cube_vertex_positions,
cube_vertex_normals, cube_vertex_texcoords),
std::make_tuple(glm::vec3{size}));
default:
std::terminate();
}
}();
scene::Geometry geometry{
.topology = primitives::primitive_topology,
.indices = Indices{std::cbegin(indices), std::cend(indices)},
.vertices = Vertices{static_cast<std::size_t>(positions.size()),
{.positions = true, .normals = true, .texcoords = true}}};
std::transform(std::cbegin(positions), std::cend(positions),
geometry.vertices.positions.get(),
[scale](const auto pos) { return pos * scale; });
std::copy(std::cbegin(normals), std::cend(normals), geometry.vertices.normals.get());
std::copy(std::cbegin(texcoords), std::cend(texcoords),
geometry.vertices.texcoords.get());
return geometry;
}
auto positions_to_vertices(const std::vector<glm::vec3>& positions) -> Vertices
{
Vertices vertices{positions.size(), {.positions = true}};
std::copy(std::cbegin(positions), std::cend(positions), vertices.positions.get());
return vertices;
}
auto create_scene(Model model) -> scene::Scene
{
scene::Scene scene{.name = std::move(model.name)};
scene.materials.push_back({.name = "default_material",
.diffuse_colour = {0.5f, 0.5f, 0.5f, 0.33f},
.flags = Render_flags::transparent});
if (model.bones.empty()) {
scene.nodes.push_back({.name = "root"s,
.parent = ""s,
.material_index = 0,
.type = scene::Node_type::null});
}
for (auto& bone : model.bones) {
scene.nodes.push_back({.name = std::move(bone.name),
.parent = std::move(bone.parent),
.material_index = 0,
.type = scene::Node_type::null,
.transform = bone.transform});
}
int name_counter = 0;
for (auto& part : model.parts) {
if (part.material.attached_light) {
scene.attached_lights.push_back(
{.node = part.name.value(),
.light = std::move(part.material.attached_light.value())});
}
scene.nodes.push_back(
{.name = part.name ? std::move(*part.name)
: fmt::format("mesh_part{}{}"sv, ++name_counter,
lod_suffix(part.lod)),
.parent = std::move(part.parent),
.material_index = insert_scene_material(
scene,
scene::Material{.name = part.material.name.value_or(""s),
.diffuse_colour = part.material.diffuse_colour,
.specular_colour = part.material.specular_colour,
.specular_exponent = part.material.specular_exponent,
.flags = part.material.flags,
.rendertype = part.material.type,
.params = part.material.params,
.textures = std::move(part.material.textures),
.reference_in_option_file = part.material.name.has_value()}),
.type = scene::Node_type::geometry,
.lod = part.lod,
.geometry = scene::Geometry{.topology = part.primitive_topology,
.indices = std::move(part.indices),
.vertices = std::move(part.vertices),
.bone_map = std::move(part.bone_map)}});
}
name_counter = 0;
for (auto& mesh : model.collision_meshes) {
scene.nodes.push_back(
{.name = fmt::format("collision_-{}-mesh{}"sv,
collision_flags_string(mesh.flags), ++name_counter),
.parent = scene.nodes.front().name, // take the dangerous assumption that the
// first node we added is root
.material_index = 0,
.type = scene::Node_type::collision,
.geometry =
scene::Geometry{.topology = mesh.primitive_topology,
.indices = std::move(mesh.indices),
.vertices = positions_to_vertices(mesh.positions)}});
}
for (auto& prim : model.collision_primitives) {
scene.nodes.push_back(
{.name = prim.name,
.parent = std::move(prim.parent),
.material_index = 0,
.type = scene::Node_type::collision_primitive,
.transform = prim.transform,
.geometry = make_primitive_visualization_geometry(prim.type, prim.size),
.collision = scene::Collision{.type = prim.type, .size = prim.size}});
}
for (auto& cloth : model.cloths) {
scene.nodes.push_back(
{.name = std::move(cloth.name),
.parent = std::move(cloth.parent),
.material_index = 0,
.type = scene::Node_type::cloth_geometry,
.transform = cloth.transform,
.cloth_geometry = scene::Cloth_geometry{
.texture_name = std::move(cloth.texture_name),
.vertices = std::move(cloth.vertices),
.indices = std::move(cloth.indices),
.fixed_points = std::move(cloth.fixed_points),
.fixed_weights = std::move(cloth.fixed_weights),
.stretch_constraints = std::move(cloth.stretch_constraints),
.cross_constraints = std::move(cloth.cross_constraints),
.bend_constraints = std::move(cloth.bend_constraints),
.collision = std::move(cloth.collision),
}});
}
name_counter = 0;
for (auto& material : scene.materials) {
if (!material.name.empty()) continue;
material.name = fmt::format("material{}"sv, ++name_counter);
}
for (const auto& node : scene.nodes) {
scene.softskin |= node.geometry ? node.geometry->vertices.softskinned : false;
scene.vertex_lighting |=
node.geometry ? node.geometry->vertices.static_lighting : false;
}
scene::reverse_pretransforms(scene);
scene::recreate_aabbs(scene);
return scene;
}
void save_model(Model model, File_saver& file_saver, const Game_version game_version,
const Model_format format)
{
if (format == Model_format::msh) {
msh::save_scene(create_scene(std::move(model)), file_saver, game_version);
}
else if (format == Model_format::gltf2) {
gltf::save_scene(create_scene(std::move(model)), file_saver);
}
}
void clean_model(Model& model, const Model_discard_flags discard_flags) noexcept
{
if (discard_flags == Model_discard_flags::none) return;
if (are_flags_set(discard_flags, Model_discard_flags::collision)) {
model.collision_meshes.clear();
model.collision_primitives.clear();
}
if (are_flags_set(discard_flags, Model_discard_flags::lod)) {
model.parts.erase(
std::remove_if(model.parts.begin(), model.parts.end(),
[](const Part& part) { return part.lod != Lod::zero; }),
model.parts.end());
}
}
}
Vertices::Vertices(const std::size_t size, const Create_flags flags) : size{size}
{
if (flags.positions) positions = std::make_unique<glm::vec3[]>(size);
if (flags.normals) normals = std::make_unique<glm::vec3[]>(size);
if (flags.tangents) tangents = std::make_unique<glm::vec3[]>(size);
if (flags.bitangents) bitangents = std::make_unique<glm::vec3[]>(size);
if (flags.colors) colors = std::make_unique<glm::vec4[]>(size);
if (flags.texcoords) texcoords = std::make_unique<glm::vec2[]>(size);
if (flags.bones) bones = std::make_unique<glm::u8vec3[]>(size);
if (flags.weights) weights = std::make_unique<glm::vec3[]>(size);
}
void Model::merge_with(Model other) noexcept
{
merge_containers(this->bones, other.bones);
merge_containers(this->parts, other.parts);
merge_containers(this->collision_meshes, other.collision_meshes);
merge_containers(this->collision_primitives, other.collision_primitives);
merge_containers(this->cloths, other.cloths);
}
void Models_builder::integrate(Model model) noexcept
{
std::lock_guard lock{_mutex};
if (const auto it = std::find_if(
_models.begin(), _models.end(),
[&](const auto& other) noexcept { return (model.name == other.name); });
it != _models.end()) {
it->merge_with(std::move(model));
}
else {
_models.emplace_back(std::move(model));
}
}
void Models_builder::save_models(File_saver& file_saver, const Game_version game_version,
const Model_format format,
const Model_discard_flags discard_flags) noexcept
{
std::lock_guard lock{_mutex};
tbb::parallel_for_each(_models, [&](Model& model) {
clean_model(model, discard_flags);
save_model(std::move(model), file_saver, game_version, format);
});
_models.clear();
}
}<commit_msg>fix invalid collision primitive shape handling<commit_after>
#include "model_builder.hpp"
#include "model_basic_primitives.hpp"
#include "model_gltf_save.hpp"
#include "model_msh_save.hpp"
#include "model_scene.hpp"
#include "synced_cout.hpp"
#include <algorithm>
#include <iterator>
#include <string_view>
#include <tuple>
#include <fmt/format.h>
#include <gsl/gsl>
#include <tbb/tbb.h>
using namespace std::literals;
namespace model {
namespace {
template<typename Type>
void merge_containers(std::vector<Type>& into, std::vector<Type>& from) noexcept
{
into.insert(into.end(), std::make_move_iterator(from.begin()),
std::make_move_iterator(from.end()));
from.clear();
}
auto lod_suffix(const Lod lod) -> std::string_view
{
switch (lod) {
case Lod::zero:
return ""sv;
case Lod::one:
return "_lod1"sv;
case Lod::two:
return "_lod2"sv;
case Lod::three:
return "_lod3"sv;
case Lod::lowres:
return "_lowres"sv;
default:
std::terminate();
}
}
auto collision_flags_string(const Collision_flags flags) -> std::string
{
if (flags == Collision_flags::all) return ""s;
std::string str;
if (are_flags_set(flags, Collision_flags::soldier)) str += "s"sv;
if (are_flags_set(flags, Collision_flags::vehicle)) str += "v"sv;
if (are_flags_set(flags, Collision_flags::building)) str += "b"sv;
if (are_flags_set(flags, Collision_flags::terrain)) str += "t"sv;
if (are_flags_set(flags, Collision_flags::ordnance)) str += "o"sv;
if (are_flags_set(flags, Collision_flags::flyer)) str += "f"sv;
return str;
}
auto insert_scene_material(scene::Scene& scene, scene::Material material) -> std::size_t
{
if (auto it = std::find(scene.materials.begin(), scene.materials.end(), material);
it != scene.materials.end()) {
return static_cast<std::size_t>(std::distance(scene.materials.begin(), it));
}
const auto index = scene.materials.size();
scene.materials.emplace_back(std::move(material));
return index;
}
auto make_primitive_visualization_geometry(const Collision_primitive_type type,
const glm::vec3 size) -> scene::Geometry
{
const auto [indices, positions, normals, texcoords, scale] = [=] {
using namespace primitives;
const auto as_spans = [](const auto&... args) {
return std::make_tuple(gsl::make_span(args)...);
};
switch (type) {
case Collision_primitive_type::cylinder:
return std::tuple_cat(as_spans(cylinder_indices, cylinder_vertex_positions,
cylinder_vertex_normals,
cylinder_vertex_texcoords),
std::make_tuple(glm::vec3{size.xyx}));
case Collision_primitive_type::cube:
return std::tuple_cat(as_spans(cube_indices, cube_vertex_positions,
cube_vertex_normals, cube_vertex_texcoords),
std::make_tuple(glm::vec3{size}));
default:
return std::tuple_cat(as_spans(sphere_indices, sphere_vertex_positions,
sphere_vertex_normals, sphere_vertex_texcoords),
std::make_tuple(glm::vec3{size.x}));
}
}();
scene::Geometry geometry{
.topology = primitives::primitive_topology,
.indices = Indices{std::cbegin(indices), std::cend(indices)},
.vertices = Vertices{static_cast<std::size_t>(positions.size()),
{.positions = true, .normals = true, .texcoords = true}}};
std::transform(std::cbegin(positions), std::cend(positions),
geometry.vertices.positions.get(),
[scale](const auto pos) { return pos * scale; });
std::copy(std::cbegin(normals), std::cend(normals), geometry.vertices.normals.get());
std::copy(std::cbegin(texcoords), std::cend(texcoords),
geometry.vertices.texcoords.get());
return geometry;
}
auto positions_to_vertices(const std::vector<glm::vec3>& positions) -> Vertices
{
Vertices vertices{positions.size(), {.positions = true}};
std::copy(std::cbegin(positions), std::cend(positions), vertices.positions.get());
return vertices;
}
auto create_scene(Model model) -> scene::Scene
{
scene::Scene scene{.name = std::move(model.name)};
scene.materials.push_back({.name = "default_material",
.diffuse_colour = {0.5f, 0.5f, 0.5f, 0.33f},
.flags = Render_flags::transparent});
if (model.bones.empty()) {
scene.nodes.push_back({.name = "root"s,
.parent = ""s,
.material_index = 0,
.type = scene::Node_type::null});
}
for (auto& bone : model.bones) {
scene.nodes.push_back({.name = std::move(bone.name),
.parent = std::move(bone.parent),
.material_index = 0,
.type = scene::Node_type::null,
.transform = bone.transform});
}
int name_counter = 0;
for (auto& part : model.parts) {
if (part.material.attached_light) {
scene.attached_lights.push_back(
{.node = part.name.value(),
.light = std::move(part.material.attached_light.value())});
}
scene.nodes.push_back(
{.name = part.name ? std::move(*part.name)
: fmt::format("mesh_part{}{}"sv, ++name_counter,
lod_suffix(part.lod)),
.parent = std::move(part.parent),
.material_index = insert_scene_material(
scene,
scene::Material{.name = part.material.name.value_or(""s),
.diffuse_colour = part.material.diffuse_colour,
.specular_colour = part.material.specular_colour,
.specular_exponent = part.material.specular_exponent,
.flags = part.material.flags,
.rendertype = part.material.type,
.params = part.material.params,
.textures = std::move(part.material.textures),
.reference_in_option_file = part.material.name.has_value()}),
.type = scene::Node_type::geometry,
.lod = part.lod,
.geometry = scene::Geometry{.topology = part.primitive_topology,
.indices = std::move(part.indices),
.vertices = std::move(part.vertices),
.bone_map = std::move(part.bone_map)}});
}
name_counter = 0;
for (auto& mesh : model.collision_meshes) {
scene.nodes.push_back(
{.name = fmt::format("collision_-{}-mesh{}"sv,
collision_flags_string(mesh.flags), ++name_counter),
.parent = scene.nodes.front().name, // take the dangerous assumption that the
// first node we added is root
.material_index = 0,
.type = scene::Node_type::collision,
.geometry =
scene::Geometry{.topology = mesh.primitive_topology,
.indices = std::move(mesh.indices),
.vertices = positions_to_vertices(mesh.positions)}});
}
for (auto& prim : model.collision_primitives) {
scene.nodes.push_back(
{.name = prim.name,
.parent = std::move(prim.parent),
.material_index = 0,
.type = scene::Node_type::collision_primitive,
.transform = prim.transform,
.geometry = make_primitive_visualization_geometry(prim.type, prim.size),
.collision = scene::Collision{.type = prim.type, .size = prim.size}});
}
for (auto& cloth : model.cloths) {
scene.nodes.push_back(
{.name = std::move(cloth.name),
.parent = std::move(cloth.parent),
.material_index = 0,
.type = scene::Node_type::cloth_geometry,
.transform = cloth.transform,
.cloth_geometry = scene::Cloth_geometry{
.texture_name = std::move(cloth.texture_name),
.vertices = std::move(cloth.vertices),
.indices = std::move(cloth.indices),
.fixed_points = std::move(cloth.fixed_points),
.fixed_weights = std::move(cloth.fixed_weights),
.stretch_constraints = std::move(cloth.stretch_constraints),
.cross_constraints = std::move(cloth.cross_constraints),
.bend_constraints = std::move(cloth.bend_constraints),
.collision = std::move(cloth.collision),
}});
}
name_counter = 0;
for (auto& material : scene.materials) {
if (!material.name.empty()) continue;
material.name = fmt::format("material{}"sv, ++name_counter);
}
for (const auto& node : scene.nodes) {
scene.softskin |= node.geometry ? node.geometry->vertices.softskinned : false;
scene.vertex_lighting |=
node.geometry ? node.geometry->vertices.static_lighting : false;
}
scene::reverse_pretransforms(scene);
scene::recreate_aabbs(scene);
return scene;
}
void save_model(Model model, File_saver& file_saver, const Game_version game_version,
const Model_format format)
{
if (format == Model_format::msh) {
msh::save_scene(create_scene(std::move(model)), file_saver, game_version);
}
else if (format == Model_format::gltf2) {
gltf::save_scene(create_scene(std::move(model)), file_saver);
}
}
void clean_model(Model& model, const Model_discard_flags discard_flags) noexcept
{
if (discard_flags == Model_discard_flags::none) return;
if (are_flags_set(discard_flags, Model_discard_flags::collision)) {
model.collision_meshes.clear();
model.collision_primitives.clear();
}
if (are_flags_set(discard_flags, Model_discard_flags::lod)) {
model.parts.erase(
std::remove_if(model.parts.begin(), model.parts.end(),
[](const Part& part) { return part.lod != Lod::zero; }),
model.parts.end());
}
}
}
Vertices::Vertices(const std::size_t size, const Create_flags flags) : size{size}
{
if (flags.positions) positions = std::make_unique<glm::vec3[]>(size);
if (flags.normals) normals = std::make_unique<glm::vec3[]>(size);
if (flags.tangents) tangents = std::make_unique<glm::vec3[]>(size);
if (flags.bitangents) bitangents = std::make_unique<glm::vec3[]>(size);
if (flags.colors) colors = std::make_unique<glm::vec4[]>(size);
if (flags.texcoords) texcoords = std::make_unique<glm::vec2[]>(size);
if (flags.bones) bones = std::make_unique<glm::u8vec3[]>(size);
if (flags.weights) weights = std::make_unique<glm::vec3[]>(size);
}
void Model::merge_with(Model other) noexcept
{
merge_containers(this->bones, other.bones);
merge_containers(this->parts, other.parts);
merge_containers(this->collision_meshes, other.collision_meshes);
merge_containers(this->collision_primitives, other.collision_primitives);
merge_containers(this->cloths, other.cloths);
}
void Models_builder::integrate(Model model) noexcept
{
std::lock_guard lock{_mutex};
if (const auto it = std::find_if(
_models.begin(), _models.end(),
[&](const auto& other) noexcept { return (model.name == other.name); });
it != _models.end()) {
it->merge_with(std::move(model));
}
else {
_models.emplace_back(std::move(model));
}
}
void Models_builder::save_models(File_saver& file_saver, const Game_version game_version,
const Model_format format,
const Model_discard_flags discard_flags) noexcept
{
std::lock_guard lock{_mutex};
tbb::parallel_for_each(_models, [&](Model& model) {
clean_model(model, discard_flags);
save_model(std::move(model), file_saver, game_version, format);
});
_models.clear();
}
}<|endoftext|>
|
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009 Andrew Manson <g.real.ate@gmail.com>
//
#include "GeoLineStringGraphicsItem.h"
#include "GeoDataLineString.h"
#include "GeoDataLineStyle.h"
#include "GeoPainter.h"
#include "ViewportParams.h"
#include "GeoDataStyle.h"
namespace Marble
{
GeoLineStringGraphicsItem::GeoLineStringGraphicsItem( const GeoDataFeature *feature, const GeoDataLineString* lineString )
: GeoGraphicsItem( feature ),
m_lineString( lineString )
{
}
void GeoLineStringGraphicsItem::setLineString( const GeoDataLineString* lineString )
{
m_lineString = lineString;
}
const GeoDataLatLonAltBox& GeoLineStringGraphicsItem::latLonAltBox() const
{
return m_lineString->latLonAltBox();
}
void GeoLineStringGraphicsItem::paint( GeoPainter* painter, const ViewportParams* viewport )
{
if ( !style() )
{
painter->save();
painter->setPen( QPen() );
painter->drawPolyline( *m_lineString );
painter->restore();
return;
}
painter->save();
QPen currentPen = painter->pen();
if ( currentPen.color() != style()->lineStyle().paintedColor() )
currentPen.setColor( style()->lineStyle().paintedColor() );
if ( currentPen.widthF() != style()->lineStyle().width() ||
style()->lineStyle().physicalWidth() != 0.0 )
{
if ( float( viewport->radius() ) / EARTH_RADIUS * style()->lineStyle().physicalWidth() < style()->lineStyle().width() )
currentPen.setWidthF( style()->lineStyle().width() );
else
currentPen.setWidthF( float( viewport->radius() ) / EARTH_RADIUS * style()->lineStyle().physicalWidth() );
}
if ( currentPen.capStyle() != style()->lineStyle().capStyle() )
currentPen.setCapStyle( style()->lineStyle().capStyle() );
if ( currentPen.style() != style()->lineStyle().penStyle() )
currentPen.setStyle( style()->lineStyle().penStyle() );
if ( style()->lineStyle().penStyle() == Qt::CustomDashLine )
currentPen.setDashPattern( style()->lineStyle().dashPattern() );
if ( painter->mapQuality() != Marble::HighQuality
&& painter->mapQuality() != Marble::PrintQuality )
{
QColor penColor = currentPen.color();
penColor.setAlpha( 255 );
currentPen.setColor( penColor );
}
if ( painter->pen() != currentPen ) painter->setPen( currentPen );
if ( style()->lineStyle().background() )
{
QBrush brush = painter->background();
brush.setColor( style()->polyStyle().paintedColor() );
painter->setBackground( brush );
painter->setBackgroundMode( Qt::OpaqueMode );
}
painter->drawPolyline( *m_lineString );
painter->restore();
}
}
<commit_msg>have only one draw statement<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009 Andrew Manson <g.real.ate@gmail.com>
//
#include "GeoLineStringGraphicsItem.h"
#include "GeoDataLineString.h"
#include "GeoDataLineStyle.h"
#include "GeoPainter.h"
#include "ViewportParams.h"
#include "GeoDataStyle.h"
namespace Marble
{
GeoLineStringGraphicsItem::GeoLineStringGraphicsItem( const GeoDataFeature *feature, const GeoDataLineString* lineString )
: GeoGraphicsItem( feature ),
m_lineString( lineString )
{
}
void GeoLineStringGraphicsItem::setLineString( const GeoDataLineString* lineString )
{
m_lineString = lineString;
}
const GeoDataLatLonAltBox& GeoLineStringGraphicsItem::latLonAltBox() const
{
return m_lineString->latLonAltBox();
}
void GeoLineStringGraphicsItem::paint( GeoPainter* painter, const ViewportParams* viewport )
{
painter->save();
if ( !style() ) {
painter->setPen( QPen() );
}
else {
QPen currentPen = painter->pen();
if ( currentPen.color() != style()->lineStyle().paintedColor() )
currentPen.setColor( style()->lineStyle().paintedColor() );
if ( currentPen.widthF() != style()->lineStyle().width() ||
style()->lineStyle().physicalWidth() != 0.0 ) {
if ( float( viewport->radius() ) / EARTH_RADIUS * style()->lineStyle().physicalWidth() < style()->lineStyle().width() )
currentPen.setWidthF( style()->lineStyle().width() );
else
currentPen.setWidthF( float( viewport->radius() ) / EARTH_RADIUS * style()->lineStyle().physicalWidth() );
}
if ( currentPen.capStyle() != style()->lineStyle().capStyle() )
currentPen.setCapStyle( style()->lineStyle().capStyle() );
if ( currentPen.style() != style()->lineStyle().penStyle() )
currentPen.setStyle( style()->lineStyle().penStyle() );
if ( style()->lineStyle().penStyle() == Qt::CustomDashLine )
currentPen.setDashPattern( style()->lineStyle().dashPattern() );
if ( painter->mapQuality() != Marble::HighQuality
&& painter->mapQuality() != Marble::PrintQuality ) {
QColor penColor = currentPen.color();
penColor.setAlpha( 255 );
currentPen.setColor( penColor );
}
if ( painter->pen() != currentPen )
painter->setPen( currentPen );
if ( style()->lineStyle().background() ) {
QBrush brush = painter->background();
brush.setColor( style()->polyStyle().paintedColor() );
painter->setBackground( brush );
painter->setBackgroundMode( Qt::OpaqueMode );
}
}
painter->drawPolyline( *m_lineString );
painter->restore();
}
}
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <algorithm>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/Language.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-base/util/SimpleRateLimit.h"
#include "fnord-base/InternMap.h"
#include "fnord-json/json.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "fnord-sstable/sstablereader.h"
#include "fnord-sstable/sstablewriter.h"
#include "fnord-sstable/SSTableColumnSchema.h"
#include "fnord-sstable/SSTableColumnReader.h"
#include "fnord-sstable/SSTableColumnWriter.h"
#include "common.h"
#include "CustomerNamespace.h"
#include "FeatureSchema.h"
#include "JoinedQuery.h"
#include "CTRCounter.h"
#include "Analyzer.h"
using namespace fnord;
using namespace cm;
struct ItemStats {
ItemStats() : views(0), clicks(0) {}
uint32_t views;
uint32_t clicks;
HashMap<void*, uint32_t> term_counts;
};
struct GlobalCounter {
GlobalCounter() : views(0), clicks(0) {}
uint32_t views;
uint32_t clicks;
};
typedef HashMap<uint64_t, ItemStats> CounterMap;
InternMap intern_map;
void indexJoinedQuery(
const cm::JoinedQuery& query,
ItemEligibility eligibility,
FeatureIndex* feature_index,
Analyzer* analyzer,
Language lang,
CounterMap* counters,
GlobalCounter* global_counter) {
if (!isQueryEligible(eligibility, query)) {
return;
}
/* query string terms */
auto qstr_opt = cm::extractAttr(query.attrs, "qstr~de"); // FIXPAUL
if (qstr_opt.isEmpty()) {
return;
}
Set<String> qstr_terms;
analyzer->extractTerms(lang, qstr_opt.get(), &qstr_terms);
for (const auto& item : query.items) {
if (!isItemEligible(eligibility, query, item)) {
continue;
}
auto& stats = (*counters)[std::stoul(item.item.item_id)];
++stats.views;
stats.clicks += (int) item.clicked;
for (const auto& term : qstr_terms) {
++stats.term_counts[intern_map.internString(term)];
}
++global_counter->views;
global_counter->clicks += (int) item.clicked;
}
}
/* write output table */
void writeOutputTable(
const String& filename,
const CounterMap& counters,
const GlobalCounter& global_counter,
uint64_t start_time,
uint64_t end_time) {
/* prepare output sstable schema */
sstable::SSTableColumnSchema sstable_schema;
sstable_schema.addColumn("views", 1, sstable::SSTableColumnType::UINT64);
sstable_schema.addColumn("clicks", 2, sstable::SSTableColumnType::UINT64);
sstable_schema.addColumn("terms", 3, sstable::SSTableColumnType::STRING);
HashMap<String, String> out_hdr;
out_hdr["start_time"] = StringUtil::toString(start_time);
out_hdr["end_time"] = StringUtil::toString(end_time);
auto outhdr_json = json::toJSONString(out_hdr);
///* open output sstable */
fnord::logInfo("cm.ctrstats", "Writing results to: $0", filename);
auto sstable_writer = sstable::SSTableWriter::create(
filename,
sstable::IndexProvider{},
outhdr_json.data(),
outhdr_json.length());
auto baseline_ctr = global_counter.clicks / (double) global_counter.views;
fnord::iputs("baseline ctr: $0", baseline_ctr);
for (const auto& c : counters) {
//auto ctr = c.second.clicks / (double) c.second.views;
//auto perf = ctr / baseline_ctr;
//fnord::iputs("id=$0 views=$1 clicks=$2 ctr=$3 perf=$4",
// c.first,
// c.second.views,
// c.second.clicks,
// ctr,
// perf);
String terms_str;
for (const auto t : c.second.term_counts) {
terms_str += StringUtil::format(
"$0:$1,",
intern_map.getString(t.first),
t.second);
}
sstable::SSTableColumnWriter cols(&sstable_schema);
cols.addUInt64Column(1, c.second.views);
cols.addUInt64Column(2, c.second.clicks);
//cols.addFloatColumn(3, ctr);
//cols.addFloatColumn(4, perf);
sstable_writer->appendRow(StringUtil::toString(c.first), cols);
}
sstable_schema.writeIndex(sstable_writer.get());
sstable_writer->finalize();
}
int main(int argc, const char** argv) {
fnord::Application::init();
fnord::Application::logToStderr();
fnord::cli::FlagParser flags;
flags.defineFlag(
"lang",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"language",
"<lang>");
flags.defineFlag(
"conf",
cli::FlagParser::T_STRING,
false,
NULL,
"./conf",
"conf directory",
"<path>");
flags.defineFlag(
"output_file",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"output file path",
"<path>");
flags.defineFlag(
"featuredb_path",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"feature db path",
"<path>");
flags.defineFlag(
"loglevel",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
CounterMap counters;
GlobalCounter global_counter;
auto start_time = std::numeric_limits<uint64_t>::max();
auto end_time = std::numeric_limits<uint64_t>::min();
auto lang = languageFromString(flags.getString("lang"));
cm::Analyzer analyzer(flags.getString("conf"));
/* set up feature schema */
cm::FeatureSchema feature_schema;
feature_schema.registerFeature("shop_id", 1, 1);
feature_schema.registerFeature("category1", 2, 1);
feature_schema.registerFeature("category2", 3, 1);
feature_schema.registerFeature("category3", 4, 1);
feature_schema.registerFeature("title~de", 5, 2);
/* open featuredb db */
auto featuredb_path = flags.getString("featuredb_path");
auto featuredb = mdb::MDB::open(featuredb_path, true);
cm::FeatureIndex feature_index(featuredb, &feature_schema);
/* read input tables */
auto sstables = flags.getArgv();
auto tbl_cnt = sstables.size();
for (int tbl_idx = 0; tbl_idx < sstables.size(); ++tbl_idx) {
const auto& sstable = sstables[tbl_idx];
fnord::logInfo("cm.ctrstats", "Importing sstable: $0", sstable);
/* read sstable header */
sstable::SSTableReader reader(File::openFile(sstable, File::O_READ));
if (reader.bodySize() == 0) {
fnord::logCritical("cm.ctrstats", "unfinished sstable: $0", sstable);
exit(1);
}
/* read report header */
auto hdr = json::parseJSON(reader.readHeader());
auto tbl_start_time = json::JSONUtil::objectGetUInt64(
hdr.begin(),
hdr.end(),
"start_time").get();
auto tbl_end_time = json::JSONUtil::objectGetUInt64(
hdr.begin(),
hdr.end(),
"end_time").get();
if (tbl_start_time < start_time) {
start_time = tbl_start_time;
}
if (tbl_end_time > end_time) {
end_time = tbl_end_time;
}
/* get sstable cursor */
auto cursor = reader.getCursor();
auto body_size = reader.bodySize();
int row_idx = 0;
/* status line */
util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () {
auto p = (tbl_idx / (double) tbl_cnt) +
((cursor->position() / (double) body_size)) / (double) tbl_cnt;
fnord::logInfo(
"cm.ctrstats",
"[$0%] Reading sstables... rows=$1",
(size_t) (p * 100),
row_idx);
});
/* read sstable rows */
for (; cursor->valid(); ++row_idx) {
status_line.runMaybe();
auto val = cursor->getDataBuffer();
Option<cm::JoinedQuery> q;
try {
q = Some(json::fromJSON<cm::JoinedQuery>(val));
} catch (const Exception& e) {
//fnord::logWarning("cm.ctrstats", e, "invalid json: $0", val.toString());
}
if (!q.isEmpty()) {
indexJoinedQuery(
q.get(),
cm::ItemEligibility::DAWANDA_ALL_NOBOTS,
&feature_index,
&analyzer,
lang,
&counters,
&global_counter);
}
if (!cursor->next()) {
break;
}
}
status_line.runForce();
}
/* write output table */
writeOutputTable(
flags.getString("output_file"),
counters,
global_counter,
start_time,
end_time);
return 0;
}
<commit_msg>posi norm<commit_after>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <algorithm>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/Language.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-base/util/SimpleRateLimit.h"
#include "fnord-base/InternMap.h"
#include "fnord-json/json.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "fnord-sstable/sstablereader.h"
#include "fnord-sstable/sstablewriter.h"
#include "fnord-sstable/SSTableColumnSchema.h"
#include "fnord-sstable/SSTableColumnReader.h"
#include "fnord-sstable/SSTableColumnWriter.h"
#include "common.h"
#include "CustomerNamespace.h"
#include "FeatureSchema.h"
#include "JoinedQuery.h"
#include "CTRCounter.h"
#include "Analyzer.h"
using namespace fnord;
using namespace cm;
struct ItemStats {
ItemStats() : views(0), clicks(0), clicks_norm(0) {}
uint32_t views;
uint32_t clicks;
uint32_t clicks_norm;
HashMap<void*, uint32_t> term_counts;
};
struct GlobalCounter {
GlobalCounter() : views(0), clicks(0) {}
uint32_t views;
uint32_t clicks;
};
typedef HashMap<uint64_t, ItemStats> CounterMap;
InternMap intern_map;
HashMap<uint32_t, double> posi_norm;
void indexJoinedQuery(
const cm::JoinedQuery& query,
ItemEligibility eligibility,
FeatureIndex* feature_index,
Analyzer* analyzer,
Language lang,
CounterMap* counters,
GlobalCounter* global_counter) {
if (!isQueryEligible(eligibility, query)) {
return;
}
/* query string terms */
auto qstr_opt = cm::extractAttr(query.attrs, "qstr~de"); // FIXPAUL
if (qstr_opt.isEmpty()) {
return;
}
Set<String> qstr_terms;
analyzer->extractTerms(lang, qstr_opt.get(), &qstr_terms);
for (const auto& item : query.items) {
if (!isItemEligible(eligibility, query, item)) {
continue;
}
auto& stats = (*counters)[std::stoul(item.item.item_id)];
++stats.views;
++global_counter->views;
if (item.clicked) {
stats.clicks += 1;
stats.clicks_norm += posi_norm[item.position];
global_counter->clicks += 1;
}
for (const auto& term : qstr_terms) {
++stats.term_counts[intern_map.internString(term)];
}
}
}
/* write output table */
void writeOutputTable(
const String& filename,
const CounterMap& counters,
const GlobalCounter& global_counter,
uint64_t start_time,
uint64_t end_time) {
/* prepare output sstable schema */
sstable::SSTableColumnSchema sstable_schema;
sstable_schema.addColumn("views", 1, sstable::SSTableColumnType::UINT64);
sstable_schema.addColumn("clicks", 2, sstable::SSTableColumnType::FLOAT);
sstable_schema.addColumn("clicks_norm", 3, sstable::SSTableColumnType::FLOAT);
sstable_schema.addColumn("terms", 4, sstable::SSTableColumnType::STRING);
HashMap<String, String> out_hdr;
out_hdr["start_time"] = StringUtil::toString(start_time);
out_hdr["end_time"] = StringUtil::toString(end_time);
auto outhdr_json = json::toJSONString(out_hdr);
///* open output sstable */
fnord::logInfo("cm.ctrstats", "Writing results to: $0", filename);
auto sstable_writer = sstable::SSTableWriter::create(
filename,
sstable::IndexProvider{},
outhdr_json.data(),
outhdr_json.length());
for (const auto& c : counters) {
String terms_str;
for (const auto t : c.second.term_counts) {
terms_str += StringUtil::format(
"$0:$1,",
intern_map.getString(t.first),
t.second);
}
sstable::SSTableColumnWriter cols(&sstable_schema);
cols.addUInt64Column(1, c.second.views);
cols.addUInt64Column(2, c.second.clicks);
cols.addFloatColumn(3, c.second.clicks_norm);
cols.addStringColumn(4, terms_str);
sstable_writer->appendRow(StringUtil::toString(c.first), cols);
}
sstable_schema.writeIndex(sstable_writer.get());
sstable_writer->finalize();
}
int main(int argc, const char** argv) {
fnord::Application::init();
fnord::Application::logToStderr();
fnord::cli::FlagParser flags;
flags.defineFlag(
"lang",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"language",
"<lang>");
flags.defineFlag(
"conf",
cli::FlagParser::T_STRING,
false,
NULL,
"./conf",
"conf directory",
"<path>");
flags.defineFlag(
"output_file",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"output file path",
"<path>");
flags.defineFlag(
"featuredb_path",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"feature db path",
"<path>");
flags.defineFlag(
"loglevel",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
CounterMap counters;
GlobalCounter global_counter;
auto start_time = std::numeric_limits<uint64_t>::max();
auto end_time = std::numeric_limits<uint64_t>::min();
auto lang = languageFromString(flags.getString("lang"));
cm::Analyzer analyzer(flags.getString("conf"));
/* set up posi norm */
posi_norm.emplace(1, 1.0 / 0.006728);
posi_norm.emplace(2, 1.0 / 0.006491);
posi_norm.emplace(3, 1.0 / 0.006345);
posi_norm.emplace(4, 1.0 / 0.004955);
posi_norm.emplace(5, 1.0 / 0.015407);
posi_norm.emplace(6, 1.0 / 0.010970);
posi_norm.emplace(7, 1.0 / 0.009629);
posi_norm.emplace(8, 1.0 / 0.009070);
posi_norm.emplace(9, 1.0 / 0.007370);
posi_norm.emplace(10, 1.0 / 0.007518);
posi_norm.emplace(11, 1.0 / 0.006699);
posi_norm.emplace(12, 1.0 / 0.006751);
posi_norm.emplace(13, 1.0 / 0.006243);
posi_norm.emplace(14, 1.0 / 0.006058);
posi_norm.emplace(15, 1.0 / 0.005885);
posi_norm.emplace(16, 1.0 / 0.005909);
posi_norm.emplace(17, 1.0 / 0.005453);
posi_norm.emplace(18, 1.0 / 0.005475);
posi_norm.emplace(19, 1.0 / 0.005424);
posi_norm.emplace(20, 1.0 / 0.005240);
posi_norm.emplace(21, 1.0 / 0.005058);
posi_norm.emplace(22, 1.0 / 0.005181);
posi_norm.emplace(23, 1.0 / 0.004913);
posi_norm.emplace(24, 1.0 / 0.004935);
posi_norm.emplace(25, 1.0 / 0.004856);
posi_norm.emplace(26, 1.0 / 0.004857);
posi_norm.emplace(27, 1.0 / 0.004649);
posi_norm.emplace(28, 1.0 / 0.004716);
posi_norm.emplace(29, 1.0 / 0.004446);
posi_norm.emplace(30, 1.0 / 0.004694);
posi_norm.emplace(31, 1.0 / 0.004542);
posi_norm.emplace(32, 1.0 / 0.004394);
posi_norm.emplace(33, 1.0 / 0.004469);
posi_norm.emplace(34, 1.0 / 0.004522);
posi_norm.emplace(35, 1.0 / 0.004416);
posi_norm.emplace(36, 1.0 / 0.004576);
posi_norm.emplace(37, 1.0 / 0.004984);
posi_norm.emplace(38, 1.0 / 0.005158);
posi_norm.emplace(39, 1.0 / 0.005268);
posi_norm.emplace(40, 1.0 / 0.005833);
/* set up feature schema */
cm::FeatureSchema feature_schema;
feature_schema.registerFeature("shop_id", 1, 1);
feature_schema.registerFeature("category1", 2, 1);
feature_schema.registerFeature("category2", 3, 1);
feature_schema.registerFeature("category3", 4, 1);
feature_schema.registerFeature("title~de", 5, 2);
/* open featuredb db */
auto featuredb_path = flags.getString("featuredb_path");
auto featuredb = mdb::MDB::open(featuredb_path, true);
cm::FeatureIndex feature_index(featuredb, &feature_schema);
/* read input tables */
auto sstables = flags.getArgv();
auto tbl_cnt = sstables.size();
for (int tbl_idx = 0; tbl_idx < sstables.size(); ++tbl_idx) {
const auto& sstable = sstables[tbl_idx];
fnord::logInfo("cm.ctrstats", "Importing sstable: $0", sstable);
/* read sstable header */
sstable::SSTableReader reader(File::openFile(sstable, File::O_READ));
if (reader.bodySize() == 0) {
fnord::logCritical("cm.ctrstats", "unfinished sstable: $0", sstable);
exit(1);
}
/* read report header */
auto hdr = json::parseJSON(reader.readHeader());
auto tbl_start_time = json::JSONUtil::objectGetUInt64(
hdr.begin(),
hdr.end(),
"start_time").get();
auto tbl_end_time = json::JSONUtil::objectGetUInt64(
hdr.begin(),
hdr.end(),
"end_time").get();
if (tbl_start_time < start_time) {
start_time = tbl_start_time;
}
if (tbl_end_time > end_time) {
end_time = tbl_end_time;
}
/* get sstable cursor */
auto cursor = reader.getCursor();
auto body_size = reader.bodySize();
int row_idx = 0;
/* status line */
util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () {
auto p = (tbl_idx / (double) tbl_cnt) +
((cursor->position() / (double) body_size)) / (double) tbl_cnt;
fnord::logInfo(
"cm.ctrstats",
"[$0%] Reading sstables... rows=$1",
(size_t) (p * 100),
row_idx);
});
/* read sstable rows */
for (; cursor->valid(); ++row_idx) {
status_line.runMaybe();
auto val = cursor->getDataBuffer();
Option<cm::JoinedQuery> q;
try {
q = Some(json::fromJSON<cm::JoinedQuery>(val));
} catch (const Exception& e) {
fnord::logWarning("cm.ctrstats", e, "invalid json: $0", val.toString());
}
if (!q.isEmpty()) {
indexJoinedQuery(
q.get(),
cm::ItemEligibility::DAWANDA_ALL_NOBOTS,
&feature_index,
&analyzer,
lang,
&counters,
&global_counter);
}
if (!cursor->next()) {
break;
}
}
status_line.runForce();
}
/* write output table */
writeOutputTable(
flags.getString("output_file"),
counters,
global_counter,
start_time,
end_time);
return 0;
}
<|endoftext|>
|
<commit_before>#ifndef GUARD_arithmetic_exceptions_hpp
#define GUARD_arithmetic_exceptions_hpp
/** \file arithmetic_exceptions.hpp
*
* \brief Exceptions to be used with jewel::Decimal class
*
* These exceptions should not be inherited.
*
* \author Matthew Harvey
* \date 15 May 2012
*
* Copyright (c) 2012, Matthew Harvey. All rights reserved.
*/
#include <stdexcept>
#include <string>
namespace jewel
{
/**
* Exception to be thrown if there is an attempt to perform unsafe
* arithmetic.
*/
class UnsafeArithmeticException
{
public:
UnsafeArithmeticException(std::string p_message);
~UnsafeArithmeticException() throw();
const char* what() throw();
private:
std::string m_message;
};
} // namespace jewel
#endif // GUARD_arithmetic_exceptions_hpp
<commit_msg>Removed a pointless header inclusion.<commit_after>#ifndef GUARD_arithmetic_exceptions_hpp
#define GUARD_arithmetic_exceptions_hpp
/** \file arithmetic_exceptions.hpp
*
* \brief Exceptions to be used with jewel::Decimal class
*
* These exceptions should not be inherited.
*
* \author Matthew Harvey
* \date 15 May 2012
*
* Copyright (c) 2012, Matthew Harvey. All rights reserved.
*/
#include <string>
namespace jewel
{
/**
* Exception to be thrown if there is an attempt to perform unsafe
* arithmetic.
*/
class UnsafeArithmeticException
{
public:
UnsafeArithmeticException(std::string p_message);
~UnsafeArithmeticException() throw();
const char* what() throw();
private:
std::string m_message;
};
} // namespace jewel
#endif // GUARD_arithmetic_exceptions_hpp
<|endoftext|>
|
<commit_before>#include "Iop_Loadcore.h"
#include "Iop_Dynamic.h"
#include "IopBios.h"
#include "../Log.h"
using namespace Iop;
#define LOG_NAME "iop_loadcore"
#define FUNCTION_FLUSHDCACHE "FlushDcache"
#define FUNCTION_REGISTERLIBRARYENTRIES "RegisterLibraryEntries"
#define FUNCTION_QUERYBOOTMODE "QueryBootMode"
#define FUNCTION_SETREBOOTTIMELIBHANDLINGMODE "SetRebootTimeLibraryHandlingMode"
#define PATH_MAX_SIZE 252
#define ARGS_MAX_SIZE 252
CLoadcore::CLoadcore(CIopBios& bios, uint8* ram, CSifMan& sifMan)
: m_bios(bios)
, m_ram(ram)
{
sifMan.RegisterModule(MODULE_ID, this);
}
CLoadcore::~CLoadcore()
{
}
std::string CLoadcore::GetId() const
{
return "loadcore";
}
std::string CLoadcore::GetFunctionName(unsigned int functionId) const
{
switch(functionId)
{
case 5:
return FUNCTION_FLUSHDCACHE;
break;
case 6:
return FUNCTION_REGISTERLIBRARYENTRIES;
break;
case 12:
return FUNCTION_QUERYBOOTMODE;
break;
case 27:
return FUNCTION_SETREBOOTTIMELIBHANDLINGMODE;
break;
default:
return "unknown";
break;
}
}
void CLoadcore::Invoke(CMIPS& context, unsigned int functionId)
{
switch(functionId)
{
case 5:
//FlushDCache
break;
case 6:
context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(RegisterLibraryEntries(
context.m_State.nGPR[CMIPS::A0].nV0
));
break;
case 12:
context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(QueryBootMode(
context.m_State.nGPR[CMIPS::A0].nV0
));
break;
case 27:
context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(SetRebootTimeLibraryHandlingMode(
context.m_State.nGPR[CMIPS::A0].nV0,
context.m_State.nGPR[CMIPS::A1].nV0
));
break;
default:
CLog::GetInstance().Print(LOG_NAME, "Unknown function (%d) called (PC: 0x%0.8X).\r\n",
functionId, context.m_State.nPC);
break;
}
}
bool CLoadcore::Invoke(uint32 method, uint32* args, uint32 argsSize, uint32* ret, uint32 retSize, uint8* ram)
{
switch(method)
{
case 0x00:
return LoadModule(args, argsSize, ret, retSize);
break;
case 0x01:
LoadExecutable(args, argsSize, ret, retSize);
break;
case 0x06:
LoadModuleFromMemory(args, argsSize, ret, retSize);
return false; //Block EE till module is loaded
break;
case 0x09:
SearchModuleByName(args, argsSize, ret, retSize);
break;
case 0xFF:
//This is sometimes called after binding this server with a client
Initialize(args, argsSize, ret, retSize);
break;
default:
CLog::GetInstance().Print(LOG_NAME, "Invoking unknown function %d.\r\n", method);
break;
}
return true;
}
void CLoadcore::SetLoadExecutableHandler(const LoadExecutableHandler& loadExecutableHandler)
{
m_loadExecutableHandler = loadExecutableHandler;
}
uint32 CLoadcore::RegisterLibraryEntries(uint32 exportTablePtr)
{
CLog::GetInstance().Print(LOG_NAME, FUNCTION_REGISTERLIBRARYENTRIES "(exportTable = 0x%0.8X);\r\n", exportTablePtr);
uint32* exportTable = reinterpret_cast<uint32*>(&m_ram[exportTablePtr]);
m_bios.RegisterDynamicModule(new CDynamic(exportTable));
return 0;
}
uint32 CLoadcore::QueryBootMode(uint32 param)
{
CLog::GetInstance().Print(LOG_NAME, FUNCTION_QUERYBOOTMODE "(param = %d);\r\n", param);
return 0;
}
uint32 CLoadcore::SetRebootTimeLibraryHandlingMode(uint32 libAddr, uint32 mode)
{
CLog::GetInstance().Print(LOG_NAME, FUNCTION_SETREBOOTTIMELIBHANDLINGMODE "(libAddr = 0x%0.8X, mode = 0x%0.8X);\r\n",
libAddr, mode);
return 0;
}
bool CLoadcore::LoadModule(uint32* args, uint32 argsSize, uint32* ret, uint32 retSize)
{
char moduleName[PATH_MAX_SIZE];
char moduleArgs[ARGS_MAX_SIZE];
assert(argsSize == 512);
//Sometimes called with 4, sometimes 8
assert(retSize >= 4);
uint32 moduleArgsSize = args[0];
memcpy(moduleName, reinterpret_cast<const char*>(args) + 8, PATH_MAX_SIZE);
memcpy(moduleArgs, reinterpret_cast<const char*>(args) + 8 + PATH_MAX_SIZE, ARGS_MAX_SIZE);
//Load the module
CLog::GetInstance().Print(LOG_NAME, "Request to load module '%s' received with %d bytes arguments payload.\r\n", moduleName, moduleArgsSize);
auto moduleId = m_bios.LoadModule(moduleName);
if(moduleId >= 0)
{
moduleId = m_bios.StartModule(moduleId, moduleName, moduleArgs, moduleArgsSize);
}
//This function returns something negative upon failure
ret[0] = 0x00000000;
if(moduleId >= 0)
{
//Block EE till the IOP has completed the operation and sends its reply to the EE
return false;
}
else
{
//Loading module failed, reply can be sent over immediately
return true;
}
}
void CLoadcore::LoadExecutable(uint32* args, uint32 argsSize, uint32* ret, uint32 retSize)
{
char moduleName[PATH_MAX_SIZE];
char sectionName[ARGS_MAX_SIZE];
assert(argsSize == 512);
assert(retSize >= 8);
memcpy(moduleName, reinterpret_cast<const char*>(args) + 8, PATH_MAX_SIZE);
memcpy(sectionName, reinterpret_cast<const char*>(args) + 8 + PATH_MAX_SIZE, ARGS_MAX_SIZE);
CLog::GetInstance().Print(LOG_NAME, "Request to load section '%s' from executable '%s' received.\r\n", sectionName, moduleName);
uint32 result = 0;
//Load executable in EE memory
if(m_loadExecutableHandler)
{
result = m_loadExecutableHandler(moduleName, sectionName);
}
//This function returns something negative upon failure
ret[0] = result; //epc or result (if negative)
ret[1] = 0x00000000; //gp
}
void CLoadcore::LoadModuleFromMemory(uint32* args, uint32 argsSize, uint32* ret, uint32 retSize)
{
const char* moduleArgs = reinterpret_cast<const char*>(args) + 8 + PATH_MAX_SIZE;
uint32 moduleArgsSize = args[1];
CLog::GetInstance().Print(LOG_NAME, "Request to load module at 0x%0.8X received with %d bytes arguments payload.\r\n", args[0], moduleArgsSize);
auto moduleId = m_bios.LoadModule(args[0]);
if(moduleId >= 0)
{
moduleId = m_bios.StartModule(moduleId, "", moduleArgs, moduleArgsSize);
}
ret[0] = 0x00000000;
}
void CLoadcore::SearchModuleByName(uint32* args, uint32 argsSize, uint32* ret, uint32 retSize)
{
assert(argsSize >= 0x200);
assert(retSize >= 4);
const char* moduleName = reinterpret_cast<const char*>(args) + 8;
CLog::GetInstance().Print(LOG_NAME, "SearchModuleByName('%s');\r\n", moduleName);
auto moduleId = m_bios.SearchModuleByName(moduleName);
ret[0] = moduleId;
}
void CLoadcore::Initialize(uint32* args, uint32 argsSize, uint32* ret, uint32 retSize)
{
assert(argsSize == 0);
assert(retSize == 4);
ret[0] = 0x2E2E2E2E;
}
<commit_msg>LoadModule functions now return proper values.<commit_after>#include "Iop_Loadcore.h"
#include "Iop_Dynamic.h"
#include "IopBios.h"
#include "../Log.h"
using namespace Iop;
#define LOG_NAME "iop_loadcore"
#define FUNCTION_FLUSHDCACHE "FlushDcache"
#define FUNCTION_REGISTERLIBRARYENTRIES "RegisterLibraryEntries"
#define FUNCTION_QUERYBOOTMODE "QueryBootMode"
#define FUNCTION_SETREBOOTTIMELIBHANDLINGMODE "SetRebootTimeLibraryHandlingMode"
#define PATH_MAX_SIZE 252
#define ARGS_MAX_SIZE 252
CLoadcore::CLoadcore(CIopBios& bios, uint8* ram, CSifMan& sifMan)
: m_bios(bios)
, m_ram(ram)
{
sifMan.RegisterModule(MODULE_ID, this);
}
CLoadcore::~CLoadcore()
{
}
std::string CLoadcore::GetId() const
{
return "loadcore";
}
std::string CLoadcore::GetFunctionName(unsigned int functionId) const
{
switch(functionId)
{
case 5:
return FUNCTION_FLUSHDCACHE;
break;
case 6:
return FUNCTION_REGISTERLIBRARYENTRIES;
break;
case 12:
return FUNCTION_QUERYBOOTMODE;
break;
case 27:
return FUNCTION_SETREBOOTTIMELIBHANDLINGMODE;
break;
default:
return "unknown";
break;
}
}
void CLoadcore::Invoke(CMIPS& context, unsigned int functionId)
{
switch(functionId)
{
case 5:
//FlushDCache
break;
case 6:
context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(RegisterLibraryEntries(
context.m_State.nGPR[CMIPS::A0].nV0
));
break;
case 12:
context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(QueryBootMode(
context.m_State.nGPR[CMIPS::A0].nV0
));
break;
case 27:
context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(SetRebootTimeLibraryHandlingMode(
context.m_State.nGPR[CMIPS::A0].nV0,
context.m_State.nGPR[CMIPS::A1].nV0
));
break;
default:
CLog::GetInstance().Print(LOG_NAME, "Unknown function (%d) called (PC: 0x%0.8X).\r\n",
functionId, context.m_State.nPC);
break;
}
}
bool CLoadcore::Invoke(uint32 method, uint32* args, uint32 argsSize, uint32* ret, uint32 retSize, uint8* ram)
{
switch(method)
{
case 0x00:
return LoadModule(args, argsSize, ret, retSize);
break;
case 0x01:
LoadExecutable(args, argsSize, ret, retSize);
break;
case 0x06:
LoadModuleFromMemory(args, argsSize, ret, retSize);
return false; //Block EE till module is loaded
break;
case 0x09:
SearchModuleByName(args, argsSize, ret, retSize);
break;
case 0xFF:
//This is sometimes called after binding this server with a client
Initialize(args, argsSize, ret, retSize);
break;
default:
CLog::GetInstance().Print(LOG_NAME, "Invoking unknown function %d.\r\n", method);
break;
}
return true;
}
void CLoadcore::SetLoadExecutableHandler(const LoadExecutableHandler& loadExecutableHandler)
{
m_loadExecutableHandler = loadExecutableHandler;
}
uint32 CLoadcore::RegisterLibraryEntries(uint32 exportTablePtr)
{
CLog::GetInstance().Print(LOG_NAME, FUNCTION_REGISTERLIBRARYENTRIES "(exportTable = 0x%0.8X);\r\n", exportTablePtr);
uint32* exportTable = reinterpret_cast<uint32*>(&m_ram[exportTablePtr]);
m_bios.RegisterDynamicModule(new CDynamic(exportTable));
return 0;
}
uint32 CLoadcore::QueryBootMode(uint32 param)
{
CLog::GetInstance().Print(LOG_NAME, FUNCTION_QUERYBOOTMODE "(param = %d);\r\n", param);
return 0;
}
uint32 CLoadcore::SetRebootTimeLibraryHandlingMode(uint32 libAddr, uint32 mode)
{
CLog::GetInstance().Print(LOG_NAME, FUNCTION_SETREBOOTTIMELIBHANDLINGMODE "(libAddr = 0x%0.8X, mode = 0x%0.8X);\r\n",
libAddr, mode);
return 0;
}
bool CLoadcore::LoadModule(uint32* args, uint32 argsSize, uint32* ret, uint32 retSize)
{
char moduleName[PATH_MAX_SIZE];
char moduleArgs[ARGS_MAX_SIZE];
assert(argsSize == 512);
//Sometimes called with 4, sometimes 8
assert(retSize >= 4);
uint32 moduleArgsSize = args[0];
memcpy(moduleName, reinterpret_cast<const char*>(args) + 8, PATH_MAX_SIZE);
memcpy(moduleArgs, reinterpret_cast<const char*>(args) + 8 + PATH_MAX_SIZE, ARGS_MAX_SIZE);
//Load the module
CLog::GetInstance().Print(LOG_NAME, "Request to load module '%s' received with %d bytes arguments payload.\r\n", moduleName, moduleArgsSize);
auto moduleId = m_bios.LoadModule(moduleName);
if(moduleId >= 0)
{
moduleId = m_bios.StartModule(moduleId, moduleName, moduleArgs, moduleArgsSize);
}
//This function returns something negative upon failure
ret[0] = moduleId;
if(moduleId >= 0)
{
//Block EE till the IOP has completed the operation and sends its reply to the EE
return false;
}
else
{
//Loading module failed, reply can be sent over immediately
return true;
}
}
void CLoadcore::LoadExecutable(uint32* args, uint32 argsSize, uint32* ret, uint32 retSize)
{
char moduleName[PATH_MAX_SIZE];
char sectionName[ARGS_MAX_SIZE];
assert(argsSize == 512);
assert(retSize >= 8);
memcpy(moduleName, reinterpret_cast<const char*>(args) + 8, PATH_MAX_SIZE);
memcpy(sectionName, reinterpret_cast<const char*>(args) + 8 + PATH_MAX_SIZE, ARGS_MAX_SIZE);
CLog::GetInstance().Print(LOG_NAME, "Request to load section '%s' from executable '%s' received.\r\n", sectionName, moduleName);
uint32 result = 0;
//Load executable in EE memory
if(m_loadExecutableHandler)
{
result = m_loadExecutableHandler(moduleName, sectionName);
}
//This function returns something negative upon failure
ret[0] = result; //epc or result (if negative)
ret[1] = 0x00000000; //gp
}
void CLoadcore::LoadModuleFromMemory(uint32* args, uint32 argsSize, uint32* ret, uint32 retSize)
{
const char* moduleArgs = reinterpret_cast<const char*>(args) + 8 + PATH_MAX_SIZE;
uint32 moduleArgsSize = args[1];
CLog::GetInstance().Print(LOG_NAME, "Request to load module at 0x%0.8X received with %d bytes arguments payload.\r\n", args[0], moduleArgsSize);
auto moduleId = m_bios.LoadModule(args[0]);
if(moduleId >= 0)
{
moduleId = m_bios.StartModule(moduleId, "", moduleArgs, moduleArgsSize);
}
ret[0] = moduleId;
}
void CLoadcore::SearchModuleByName(uint32* args, uint32 argsSize, uint32* ret, uint32 retSize)
{
assert(argsSize >= 0x200);
assert(retSize >= 4);
const char* moduleName = reinterpret_cast<const char*>(args) + 8;
CLog::GetInstance().Print(LOG_NAME, "SearchModuleByName('%s');\r\n", moduleName);
auto moduleId = m_bios.SearchModuleByName(moduleName);
ret[0] = moduleId;
}
void CLoadcore::Initialize(uint32* args, uint32 argsSize, uint32* ret, uint32 retSize)
{
assert(argsSize == 0);
assert(retSize == 4);
ret[0] = 0x2E2E2E2E;
}
<|endoftext|>
|
<commit_before>/*
* (C) Copyright 2013 Kurento (http://kurento.org/)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include <config.h>
#include <glibmm.h>
#include <fstream>
#include <iostream>
#include <boost/filesystem.hpp>
#include "version.hpp"
#include <glib/gstdio.h>
#include <ftw.h>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include "TransportFactory.hpp"
#include <SignalHandler.hpp>
#include <ServerMethods.hpp>
#include <gst/gst.h>
#include <boost/program_options.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include "logging.hpp"
#include "modules.hpp"
#define GST_CAT_DEFAULT kurento_media_server
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoMediaServer"
const std::string DEFAULT_CONFIG_FILE = "/etc/kurento/kurento.conf.json";
const std::string ENV_PREFIX = "KURENTO_";
using namespace ::kurento;
Glib::RefPtr<Glib::MainLoop> loop = Glib::MainLoop::create ();
static std::shared_ptr<Transport>
load_config (boost::property_tree::ptree &config, const std::string &file_name)
{
std::shared_ptr<Transport> transport;
boost::filesystem::path configFilePath (file_name);
GST_INFO ("Reading configuration from: %s", file_name.c_str () );
try {
boost::property_tree::read_json (file_name, config);
} catch (boost::property_tree::ptree_error &e) {
GST_ERROR ("Error reading configuration: %s", e.what() );
std::cerr << "Error reading configuration: " << e.what() << std::endl;
exit (1);
}
config.add ("configPath", configFilePath.parent_path().string() );
GST_INFO ("Configuration loaded successfully");
std::shared_ptr<ServerMethods> serverMethods (new ServerMethods (config) );
try {
transport = TransportFactory::create_transport (config, serverMethods);
} catch (std::exception &e) {
GST_ERROR ("Error creating transport: %s", e.what() );
exit (1);
}
return transport;
}
static void
signal_handler (uint32_t signo)
{
static unsigned int __terminated = 0;
switch (signo) {
case SIGINT:
case SIGTERM:
if (__terminated == 0) {
GST_DEBUG ("Terminating.");
loop->quit ();
}
__terminated = 1;
break;
case SIGPIPE:
GST_DEBUG ("Ignore sigpipe signal");
break;
case SIGSEGV:
GST_DEBUG ("Segmentation fault. Aborting process execution");
abort ();
default:
break;
}
}
int
main (int argc, char **argv)
{
sigset_t mask;
std::shared_ptr <SignalHandler> signalHandler;
std::shared_ptr<Transport> transport;
boost::property_tree::ptree config;
std::string confFile;
std::string path;
Glib::init();
gst_init (&argc, &argv);
GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
GST_DEFAULT_NAME);
gst_debug_remove_log_function_by_data (NULL);
gst_debug_add_log_function (simple_log_function, NULL, NULL);
try {
boost::program_options::options_description desc ("kurento-media-server usage");
desc.add_options()
("help,h", "Display this help message")
("version,v", "Display the version number")
("list,l", "Lists all available factories")
("modules-path,p", boost::program_options::value<std::string>
(&path), "Path where kurento modules can be found")
("conf-file,f", boost::program_options::value<std::string>
(&confFile)->default_value (DEFAULT_CONFIG_FILE),
"Configuration file location");
boost::program_options::command_line_parser clp (argc, argv);
clp.options (desc).allow_unregistered();
boost::program_options::variables_map vm;
auto parsed = clp.run();
boost::program_options::store (parsed, vm);
boost::program_options::store (boost::program_options::parse_environment (desc,
[&desc] (std::string & input) -> std::string {
/* Look for KURENTO_ prefix and change to lower case */
if (input.find (ENV_PREFIX) == 0) {
std::string aux = input.substr (ENV_PREFIX.size() );
std::transform (aux.begin(), aux.end(), aux.begin(), [] (int c) -> int {
return (c == '_') ? '-' : tolower (c);
});
if (!desc.find_nothrow (aux, false) ) {
return "";
}
return aux;
}
return "";
}), vm);
boost::program_options::notify (vm);
if (vm.count ("help") ) {
std::cout << desc << "\n";
exit (0);
}
if (vm.count ("version") || vm.count ("list") ) {
// Disable log to just print version
gst_debug_remove_log_function (simple_log_function);
}
loadModules (path);
if (vm.count ("list") ) {
std::cout << "Available factories:" << std::endl;
for (auto it : kurento::getModuleManager().getLoadedFactories() ) {
std::cout << "\t" << it.first << std::endl;
}
exit (0);
}
if (vm.count ("version") ) {
print_version();
exit (0);
}
} catch (boost::program_options::error &e) {
std::cerr << "Error : " << e.what() << std::endl;
exit (1);
}
/* Install our signal handler */
sigemptyset (&mask);
sigaddset (&mask, SIGINT);
sigaddset (&mask, SIGTERM);
sigaddset (&mask, SIGSEGV);
sigaddset (&mask, SIGPIPE);
signalHandler = std::shared_ptr <SignalHandler> (new SignalHandler (mask,
signal_handler) );
GST_INFO ("Kmsc version: %s", get_version () );
transport = load_config (config, confFile);
/* Start transport */
transport->start ();
GST_INFO ("Mediaserver started");
loop->run ();
transport->stop();
return 0;
}
<commit_msg>Add info message when mediaserver exits normally<commit_after>/*
* (C) Copyright 2013 Kurento (http://kurento.org/)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include <config.h>
#include <glibmm.h>
#include <fstream>
#include <iostream>
#include <boost/filesystem.hpp>
#include "version.hpp"
#include <glib/gstdio.h>
#include <ftw.h>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include "TransportFactory.hpp"
#include <SignalHandler.hpp>
#include <ServerMethods.hpp>
#include <gst/gst.h>
#include <boost/program_options.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include "logging.hpp"
#include "modules.hpp"
#define GST_CAT_DEFAULT kurento_media_server
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoMediaServer"
const std::string DEFAULT_CONFIG_FILE = "/etc/kurento/kurento.conf.json";
const std::string ENV_PREFIX = "KURENTO_";
using namespace ::kurento;
Glib::RefPtr<Glib::MainLoop> loop = Glib::MainLoop::create ();
static std::shared_ptr<Transport>
load_config (boost::property_tree::ptree &config, const std::string &file_name)
{
std::shared_ptr<Transport> transport;
boost::filesystem::path configFilePath (file_name);
GST_INFO ("Reading configuration from: %s", file_name.c_str () );
try {
boost::property_tree::read_json (file_name, config);
} catch (boost::property_tree::ptree_error &e) {
GST_ERROR ("Error reading configuration: %s", e.what() );
std::cerr << "Error reading configuration: " << e.what() << std::endl;
exit (1);
}
config.add ("configPath", configFilePath.parent_path().string() );
GST_INFO ("Configuration loaded successfully");
std::shared_ptr<ServerMethods> serverMethods (new ServerMethods (config) );
try {
transport = TransportFactory::create_transport (config, serverMethods);
} catch (std::exception &e) {
GST_ERROR ("Error creating transport: %s", e.what() );
exit (1);
}
return transport;
}
static void
signal_handler (uint32_t signo)
{
static unsigned int __terminated = 0;
switch (signo) {
case SIGINT:
case SIGTERM:
if (__terminated == 0) {
GST_DEBUG ("Terminating.");
loop->quit ();
}
__terminated = 1;
break;
case SIGPIPE:
GST_DEBUG ("Ignore sigpipe signal");
break;
case SIGSEGV:
GST_DEBUG ("Segmentation fault. Aborting process execution");
abort ();
default:
break;
}
}
int
main (int argc, char **argv)
{
sigset_t mask;
std::shared_ptr <SignalHandler> signalHandler;
std::shared_ptr<Transport> transport;
boost::property_tree::ptree config;
std::string confFile;
std::string path;
Glib::init();
gst_init (&argc, &argv);
GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
GST_DEFAULT_NAME);
gst_debug_remove_log_function_by_data (NULL);
gst_debug_add_log_function (simple_log_function, NULL, NULL);
try {
boost::program_options::options_description desc ("kurento-media-server usage");
desc.add_options()
("help,h", "Display this help message")
("version,v", "Display the version number")
("list,l", "Lists all available factories")
("modules-path,p", boost::program_options::value<std::string>
(&path), "Path where kurento modules can be found")
("conf-file,f", boost::program_options::value<std::string>
(&confFile)->default_value (DEFAULT_CONFIG_FILE),
"Configuration file location");
boost::program_options::command_line_parser clp (argc, argv);
clp.options (desc).allow_unregistered();
boost::program_options::variables_map vm;
auto parsed = clp.run();
boost::program_options::store (parsed, vm);
boost::program_options::store (boost::program_options::parse_environment (desc,
[&desc] (std::string & input) -> std::string {
/* Look for KURENTO_ prefix and change to lower case */
if (input.find (ENV_PREFIX) == 0) {
std::string aux = input.substr (ENV_PREFIX.size() );
std::transform (aux.begin(), aux.end(), aux.begin(), [] (int c) -> int {
return (c == '_') ? '-' : tolower (c);
});
if (!desc.find_nothrow (aux, false) ) {
return "";
}
return aux;
}
return "";
}), vm);
boost::program_options::notify (vm);
if (vm.count ("help") ) {
std::cout << desc << "\n";
exit (0);
}
if (vm.count ("version") || vm.count ("list") ) {
// Disable log to just print version
gst_debug_remove_log_function (simple_log_function);
}
loadModules (path);
if (vm.count ("list") ) {
std::cout << "Available factories:" << std::endl;
for (auto it : kurento::getModuleManager().getLoadedFactories() ) {
std::cout << "\t" << it.first << std::endl;
}
exit (0);
}
if (vm.count ("version") ) {
print_version();
exit (0);
}
} catch (boost::program_options::error &e) {
std::cerr << "Error : " << e.what() << std::endl;
exit (1);
}
/* Install our signal handler */
sigemptyset (&mask);
sigaddset (&mask, SIGINT);
sigaddset (&mask, SIGTERM);
sigaddset (&mask, SIGSEGV);
sigaddset (&mask, SIGPIPE);
signalHandler = std::shared_ptr <SignalHandler> (new SignalHandler (mask,
signal_handler) );
GST_INFO ("Kmsc version: %s", get_version () );
transport = load_config (config, confFile);
/* Start transport */
transport->start ();
GST_INFO ("Mediaserver started");
loop->run ();
transport->stop();
GST_INFO ("Mediaserver stopped");
return 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
> File Name: GameAgent.cpp
> Project Name: Hearthstone++
> Author: Young-Joong Kim
> Purpose: Hearthstone Game Agent
> Created Time: 2017/09/26
> Copyright (c) 2017, Young-Joong Kim
*************************************************************************/
#include <Syncs/GameAgent.h>
#include <Tasks/BasicTask.h>
#include <Tasks/MetaData.h>
#include <random>
namespace Hearthstonepp
{
std::thread GameAgent::StartAgent()
{
auto flow = [this]() {
BeginPhase();
while (true)
{
bool isGameEnd = MainPhase();
if (isGameEnd)
{
break;
}
}
FinalPhase();
};
return std::thread(std::move(flow));
}
void GameAgent::GetTaskMeta(TaskMeta& meta)
{
m_taskAgent.Read(meta);
}
void GameAgent::WriteSyncBuffer(TaskMeta&& data, bool sideChannel)
{
m_taskAgent.Notify(std::move(data), sideChannel);
}
Player& GameAgent::GetPlayer1()
{
return m_current;
}
Player& GameAgent::GetPlayer2()
{
return m_opponent;
}
void GameAgent::Process(Player& player, Task t)
{
TaskMeta meta;
if (player == m_current)
{
m_taskAgent.Run(t, meta, m_current, m_opponent, false);
}
else
{
m_taskAgent.Run(t, meta, m_opponent, m_current, false);
}
}
void GameAgent::BeginPhase()
{
std::random_device rd;
std::default_random_engine gen(rd());
// get random number, zero or one.
std::uniform_int_distribution<int> bin(0, 1);
// swap user with 50% probability
if (bin(gen) == 1)
{
m_taskAgent.Add(BasicTask::SwapPlayerTask());
}
auto untilMulliganSuccess = [](const TaskMeta& serialized) {
return serialized.status == MetaData::MULLIGAN_SUCCESS;
};
// BeginPhase Task List
m_taskAgent.Add(BasicTask::PlayerSettingTask());
m_taskAgent.Add(BasicTask::DoBothPlayer(BasicTask::ShuffleTask()));
m_taskAgent.Add(
BasicTask::DoBothPlayer(BasicTask::DrawTask(NUM_BEGIN_DRAW)));
m_taskAgent.Add(BasicTask::BriefTask());
m_taskAgent.Add(BasicTask::DoUntil(BasicTask::MulliganTask(m_taskAgent),
untilMulliganSuccess));
m_taskAgent.Add(BasicTask::SwapPlayerTask());
m_taskAgent.Add(BasicTask::BriefTask());
m_taskAgent.Add(BasicTask::DoUntil(BasicTask::MulliganTask(m_taskAgent),
untilMulliganSuccess));
m_taskAgent.Add(BasicTask::SwapPlayerTask());
TaskMeta meta;
m_taskAgent.Run(meta, m_current, m_opponent);
m_taskAgent.Clear();
// TODO: Coin for later user
m_opponent.hand.push_back(new Card());
}
bool GameAgent::MainPhase()
{
// Ready for main phase
MainReady();
// MainMenu return isGameEnd flag
return MainMenu();
}
void GameAgent::FinalPhase()
{
TaskMeta meta;
m_taskAgent.Run(BasicTask::GameEndTask(), meta, m_current, m_opponent);
}
void GameAgent::MainReady()
{
// MainReady : Draw, ModifyMana, Clear vector `attacked`
m_taskAgent.Add(BasicTask::DrawTask(1));
m_taskAgent.Add(BasicTask::ModifyManaTask(BasicTask::NUM_ADD,
BasicTask::MANA_TOTAL, 1));
m_taskAgent.Add(BasicTask::ModifyManaByRef(
BasicTask::NUM_SYNC, BasicTask::MANA_EXIST, m_current.totalMana));
TaskMeta meta;
m_taskAgent.Run(meta, m_current, m_opponent);
m_taskAgent.Clear();
m_current.attacked.clear();
}
bool GameAgent::MainMenu()
{
// Check before starting main phase
if (IsGameEnd())
{
return true;
}
TaskMeta meta;
m_taskAgent.Run(BasicTask::BriefTask(), meta, m_current, m_opponent);
m_taskAgent.Run(BasicTask::SelectMenuTask(m_taskAgent), meta, m_current,
m_opponent);
// Interface pass menu by status of TaskMeta
TaskMeta::status_t menu = meta.status;
if (menu == GAME_MAIN_MENU_SIZE - 1)
{
// Main End phase
m_taskAgent.Run(BasicTask::SwapPlayerTask(), meta, m_current,
m_opponent);
}
else
{
if (menu < GAME_MAIN_MENU_SIZE - 1)
{
// call action method
m_mainMenuFuncs[menu](*this);
}
// Recursion
return MainMenu();
}
return false;
}
void GameAgent::MainUseCard()
{
// Read what kinds of card user wants to use
TaskMeta meta;
m_taskAgent.Run(BasicTask::SelectCardTask(m_taskAgent), meta, m_current,
m_opponent);
if (meta.status == MetaData::SELECT_CARD_MINION)
{
using Require = FlatData::RequireSummonMinionTaskMeta;
const auto& buffer = meta.GetConstBuffer();
if (buffer != nullptr)
{
auto minion = flatbuffers::GetRoot<Require>(buffer.get());
if (minion != nullptr)
{
m_taskAgent.Run(BasicTask::PlayCardTask(m_current, minion->position()),
meta, m_current, m_opponent);
}
}
}
else
{
// TODO : If else selected card is not minion
}
}
void GameAgent::MainCombat()
{
TaskMeta meta;
m_taskAgent.Run(BasicTask::SelectTargetTask(m_taskAgent), meta, m_current,
m_opponent);
using Require = FlatData::RequireTargetingTaskMeta;
const auto& buffer = meta.GetConstBuffer();
if (buffer != nullptr)
{
auto targeting = flatbuffers::GetRoot<Require>(buffer.get());
if (targeting != nullptr)
{
m_taskAgent.Run(
BasicTask::CombatTask(targeting->src(), targeting->dst()), meta,
m_current, m_opponent);
}
}
}
bool GameAgent::IsGameEnd()
{
size_t healthCurrent = m_current.hero->health;
size_t healthOpponent = m_opponent.hero->health;
if (healthCurrent < 1 || healthOpponent < 1)
{
return true;
}
else
{
return false;
}
}
} // namespace Hearthstonepp<commit_msg>[ci skip] Update GameAgent - Modify status to enum class<commit_after>/*************************************************************************
> File Name: GameAgent.cpp
> Project Name: Hearthstone++
> Author: Young-Joong Kim
> Purpose: Hearthstone Game Agent
> Created Time: 2017/09/26
> Copyright (c) 2017, Young-Joong Kim
*************************************************************************/
#include <Syncs/GameAgent.h>
#include <Tasks/BasicTask.h>
#include <Tasks/MetaData.h>
#include <random>
namespace Hearthstonepp
{
std::thread GameAgent::StartAgent()
{
auto flow = [this]() {
BeginPhase();
while (true)
{
bool isGameEnd = MainPhase();
if (isGameEnd)
{
break;
}
}
FinalPhase();
};
return std::thread(std::move(flow));
}
void GameAgent::GetTaskMeta(TaskMeta& meta)
{
m_taskAgent.Read(meta);
}
void GameAgent::WriteSyncBuffer(TaskMeta&& data, bool sideChannel)
{
m_taskAgent.Notify(std::move(data), sideChannel);
}
Player& GameAgent::GetPlayer1()
{
return m_current;
}
Player& GameAgent::GetPlayer2()
{
return m_opponent;
}
void GameAgent::Process(Player& player, Task t)
{
TaskMeta meta;
if (player == m_current)
{
m_taskAgent.Run(t, meta, m_current, m_opponent, false);
}
else
{
m_taskAgent.Run(t, meta, m_opponent, m_current, false);
}
}
void GameAgent::BeginPhase()
{
std::random_device rd;
std::default_random_engine gen(rd());
// get random number, zero or one.
std::uniform_int_distribution<int> bin(0, 1);
// swap user with 50% probability
if (bin(gen) == 1)
{
m_taskAgent.Add(BasicTask::SwapPlayerTask());
}
auto untilMulliganSuccess = [](const TaskMeta& serialized) {
return serialized.status == MetaData::MULLIGAN_SUCCESS;
};
// BeginPhase Task List
m_taskAgent.Add(BasicTask::PlayerSettingTask());
m_taskAgent.Add(BasicTask::DoBothPlayer(BasicTask::ShuffleTask()));
m_taskAgent.Add(
BasicTask::DoBothPlayer(BasicTask::DrawTask(NUM_BEGIN_DRAW)));
m_taskAgent.Add(BasicTask::BriefTask());
m_taskAgent.Add(BasicTask::DoUntil(BasicTask::MulliganTask(m_taskAgent),
untilMulliganSuccess));
m_taskAgent.Add(BasicTask::SwapPlayerTask());
m_taskAgent.Add(BasicTask::BriefTask());
m_taskAgent.Add(BasicTask::DoUntil(BasicTask::MulliganTask(m_taskAgent),
untilMulliganSuccess));
m_taskAgent.Add(BasicTask::SwapPlayerTask());
TaskMeta meta;
m_taskAgent.Run(meta, m_current, m_opponent);
m_taskAgent.Clear();
// TODO: Coin for later user
m_opponent.hand.push_back(new Card());
}
bool GameAgent::MainPhase()
{
// Ready for main phase
MainReady();
// MainMenu return isGameEnd flag
return MainMenu();
}
void GameAgent::FinalPhase()
{
TaskMeta meta;
m_taskAgent.Run(BasicTask::GameEndTask(), meta, m_current, m_opponent);
}
void GameAgent::MainReady()
{
// MainReady : Draw, ModifyMana, Clear vector `attacked`
m_taskAgent.Add(BasicTask::DrawTask(1));
m_taskAgent.Add(BasicTask::ModifyManaTask(BasicTask::NUM_ADD,
BasicTask::MANA_TOTAL, 1));
m_taskAgent.Add(BasicTask::ModifyManaByRef(
BasicTask::NUM_SYNC, BasicTask::MANA_EXIST, m_current.totalMana));
TaskMeta meta;
m_taskAgent.Run(meta, m_current, m_opponent);
m_taskAgent.Clear();
m_current.attacked.clear();
}
bool GameAgent::MainMenu()
{
// Check before starting main phase
if (IsGameEnd())
{
return true;
}
TaskMeta meta;
m_taskAgent.Run(BasicTask::BriefTask(), meta, m_current, m_opponent);
m_taskAgent.Run(BasicTask::SelectMenuTask(m_taskAgent), meta, m_current,
m_opponent);
// Interface pass menu by status of TaskMeta
status_t menu = static_cast<status_t>(meta.status);
if (menu == GAME_MAIN_MENU_SIZE - 1)
{
// Main End phase
m_taskAgent.Run(BasicTask::SwapPlayerTask(), meta, m_current,
m_opponent);
}
else
{
if (menu < GAME_MAIN_MENU_SIZE - 1)
{
// call action method
m_mainMenuFuncs[menu](*this);
}
// Recursion
return MainMenu();
}
return false;
}
void GameAgent::MainUseCard()
{
// Read what kinds of card user wants to use
TaskMeta meta;
m_taskAgent.Run(BasicTask::SelectCardTask(m_taskAgent), meta, m_current,
m_opponent);
if (meta.status == MetaData::SELECT_CARD_MINION)
{
using Require = FlatData::RequireSummonMinionTaskMeta;
const auto& buffer = meta.GetConstBuffer();
if (buffer != nullptr)
{
auto minion = flatbuffers::GetRoot<Require>(buffer.get());
if (minion != nullptr)
{
m_taskAgent.Run(
BasicTask::PlayCardTask(m_current, minion->position()),
meta, m_current, m_opponent);
}
}
}
else
{
// TODO : If else selected card is not minion
}
}
void GameAgent::MainCombat()
{
TaskMeta meta;
m_taskAgent.Run(BasicTask::SelectTargetTask(m_taskAgent), meta, m_current,
m_opponent);
using Require = FlatData::RequireTargetingTaskMeta;
const auto& buffer = meta.GetConstBuffer();
if (buffer != nullptr)
{
auto targeting = flatbuffers::GetRoot<Require>(buffer.get());
if (targeting != nullptr)
{
m_taskAgent.Run(
BasicTask::CombatTask(targeting->src(), targeting->dst()), meta,
m_current, m_opponent);
}
}
}
bool GameAgent::IsGameEnd()
{
size_t healthCurrent = m_current.hero->health;
size_t healthOpponent = m_opponent.hero->health;
if (healthCurrent < 1 || healthOpponent < 1)
{
return true;
}
else
{
return false;
}
}
} // namespace Hearthstonepp<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2016 musikcube team
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the author nor the names of other 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.
//
//////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <cursespp/App.h>
#include <cursespp/Screen.h>
#include <app/layout/ConsoleLayout.h>
#include <app/layout/LibraryLayout.h>
#include <app/layout/SettingsLayout.h>
#include <app/layout/MainLayout.h>
#include <app/util/GlobalHotkeys.h>
#include <app/util/Hotkeys.h>
#include <app/service/PlaybackService.h>
#include <core/library/LibraryFactory.h>
#include <core/audio/GaplessTransport.h>
#include <cstdio>
#ifdef WIN32
#undef MOUSE_MOVED
#endif
using namespace musik::core;
using namespace musik::core::audio;
using namespace musik::box;
using namespace cursespp;
#define MIN_WIDTH 22
#define MIN_HEIGHT 11
#ifdef WIN32
int _main(int argc, _TCHAR* argv[]);
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow) {
_main(0, 0);
}
int _main(int argc, _TCHAR* argv[])
#else
int main(int argc, char* argv[])
#endif
{
#ifndef WIN32
#if 1 /*DEBUG*/
freopen("/tmp/musikbox.log", "w", stderr);
#else
freopen("/dev/null", "w", stderr);
#endif
#endif
#ifdef __PDCURSES__
PDC_set_resize_limits(MIN_HEIGHT, MIN_WIDTH, 60, 250);
resize_term(26, 100); /* must be before app init */
#endif
musik::debug::init();
LibraryPtr library = LibraryFactory::Libraries().at(0);
GaplessTransport transport;
PlaybackService playback(library, transport);
GlobalHotkeys globalHotkeys(playback, library);
{
App app("musikbox"); /* must be before layout creation */
using Layout = std::shared_ptr<LayoutBase>;
using Main = std::shared_ptr<MainLayout>;
Layout libraryLayout(new LibraryLayout(playback, library));
Layout consoleLayout(new ConsoleLayout(transport, library));
Layout settingsLayout(new SettingsLayout(library));
Main mainLayout(new MainLayout());
mainLayout->Layout();
mainLayout->SetMainLayout(libraryLayout);
app.SetKeyHandler([&](const std::string& kn) {
if (Hotkeys::Is(Hotkeys::NavigateConsole, kn)) {
mainLayout->SetMainLayout(consoleLayout);
return true;
}
else if (Hotkeys::Is(Hotkeys::NavigateLibrary, kn)) {
mainLayout->SetMainLayout(libraryLayout);
return true;
}
else if (Hotkeys::Is(Hotkeys::NavigateSettings, kn)) {
mainLayout->SetMainLayout(settingsLayout);
return true;
}
return globalHotkeys.Handle(kn);
});
app.SetResizeHandler([&]() {
int cx = Screen::GetWidth();
int cy = Screen::GetHeight();
if (cx < MIN_WIDTH || cy < MIN_HEIGHT) {
Window::Freeze();
}
else {
Window::Unfreeze();
mainLayout->Layout();
}
});
app.Run(mainLayout);
}
endwin();
LibraryFactory::Instance().Shutdown();
musik::debug::deinit();
return 0;
}
<commit_msg>One more min-size adjustment.<commit_after>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2016 musikcube team
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the author nor the names of other 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.
//
//////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <cursespp/App.h>
#include <cursespp/Screen.h>
#include <app/layout/ConsoleLayout.h>
#include <app/layout/LibraryLayout.h>
#include <app/layout/SettingsLayout.h>
#include <app/layout/MainLayout.h>
#include <app/util/GlobalHotkeys.h>
#include <app/util/Hotkeys.h>
#include <app/service/PlaybackService.h>
#include <core/library/LibraryFactory.h>
#include <core/audio/GaplessTransport.h>
#include <cstdio>
#ifdef WIN32
#undef MOUSE_MOVED
#endif
using namespace musik::core;
using namespace musik::core::audio;
using namespace musik::box;
using namespace cursespp;
#define MIN_WIDTH 36
#define MIN_HEIGHT 12
#ifdef WIN32
int _main(int argc, _TCHAR* argv[]);
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow) {
_main(0, 0);
}
int _main(int argc, _TCHAR* argv[])
#else
int main(int argc, char* argv[])
#endif
{
#ifndef WIN32
#if 1 /*DEBUG*/
freopen("/tmp/musikbox.log", "w", stderr);
#else
freopen("/dev/null", "w", stderr);
#endif
#endif
#ifdef __PDCURSES__
PDC_set_resize_limits(MIN_HEIGHT, 1000, MIN_WIDTH, 1000);
resize_term(26, 100); /* must be before app init */
#endif
musik::debug::init();
LibraryPtr library = LibraryFactory::Libraries().at(0);
GaplessTransport transport;
PlaybackService playback(library, transport);
GlobalHotkeys globalHotkeys(playback, library);
{
App app("musikbox"); /* must be before layout creation */
using Layout = std::shared_ptr<LayoutBase>;
using Main = std::shared_ptr<MainLayout>;
Layout libraryLayout(new LibraryLayout(playback, library));
Layout consoleLayout(new ConsoleLayout(transport, library));
Layout settingsLayout(new SettingsLayout(library));
Main mainLayout(new MainLayout());
mainLayout->Layout();
mainLayout->SetMainLayout(libraryLayout);
app.SetKeyHandler([&](const std::string& kn) {
if (Hotkeys::Is(Hotkeys::NavigateConsole, kn)) {
mainLayout->SetMainLayout(consoleLayout);
return true;
}
else if (Hotkeys::Is(Hotkeys::NavigateLibrary, kn)) {
mainLayout->SetMainLayout(libraryLayout);
return true;
}
else if (Hotkeys::Is(Hotkeys::NavigateSettings, kn)) {
mainLayout->SetMainLayout(settingsLayout);
return true;
}
return globalHotkeys.Handle(kn);
});
app.SetResizeHandler([&]() {
int cx = Screen::GetWidth();
int cy = Screen::GetHeight();
if (cx < MIN_WIDTH || cy < MIN_HEIGHT) {
Window::Freeze();
}
else {
Window::Unfreeze();
mainLayout->Layout();
}
});
app.Run(mainLayout);
}
endwin();
LibraryFactory::Instance().Shutdown();
musik::debug::deinit();
return 0;
}
<|endoftext|>
|
<commit_before>#include "bwpathfinder.hpp"
#include "network_simulation.hpp"
#include <queue>
#include <unordered_set>
#include <cstdio>
namespace bwpathfinder {
__attribute__((weak)) void check_pyerror() { }
size_t Node::id_counter = 0;
void Network::simulateDeliveredBandwidth() {
NetworkSimulation sim(shared_from_this());
simfw::Timer<Time> checkup(&sim, 1e-8, [] (uint64_t i) {
check_pyerror();
return true;
});
sim.simulate();
sim.setDeliveredBandwidths();
sim.flushMessages();
// Zero all state variables
for (LinkPtr link : this->links) {
link->paths.clear();
link->bwRequested = 0.0;
}
for (PathPtr path : this->paths) {
path->assign(path->path, path->delivered_bw);
path->num_wires = -1;
}
}
void Network::calcCircuitSwitchedBandwidth() {
// Zero all state variables
for (LinkPtr link : this->links) {
link->paths.clear();
link->bwRequested = 0.0;
}
for (PathPtr path : this->paths) {
path->assign(path->path, path->delivered_bw);
}
for (LinkPtr link : this->links) {
link->allocateWires();
}
}
void Link::allocateWires() {
if (this->maximum_paths <= 0)
return;
const size_t num_wires = this->maximum_paths;
size_t wires_allocated = 0;
float bwPerWire = this->bandwidth / this->maximum_paths;
typedef std::pair<double, PathPtr> dppair;
std::map<PathPtr, int> allocation;
std::priority_queue<dppair, std::vector<dppair>, compare_first> paths;
for (auto path : this->paths) {
paths.push(std::make_pair(path->requested_bw, path));
allocation[path] = 0;
}
while (paths.size() > 0 && wires_allocated <num_wires) {
dppair p = paths.top();
paths.pop();
allocation[p.second] += 1;
p.first -= bwPerWire;
if (p.first > 0) {
paths.push(p);
}
}
for (auto pipair : allocation) {
assert(pipair.second > 0);
pipair.first->assign_wire(shared_from_this(), pipair.second);
}
}
float Link::costToUse(float hopCost, float bw) const {
// float totBW = bwRequested + bw;
// float overage = totBW > bandwidth ? totBW - bandwidth : 0;
float overage = std::max((float)0.0, bw - this->bwShareW(bw));
return hopCost + (overage * overageExponent) + historyPenalty;
}
float Pathfinder::solveToBwPcnt(float desiredPcnt, uint64_t maxIter) {
desiredPcnt = std::min((float)100.0, desiredPcnt);
float requested_bw = 0.0;
for (PathPtr path: this->network->paths) {
requested_bw += path->requested_bw;
}
// printf("Pathfinder solveToBwPcnt:\n");
// printf("\tNodes: %lu\n\tLinks: %lu\n\tPaths: %lu\n\tHopCost:%e\n\tGoal: %f%%\n\tBandwidth: %e\n",
// network->nodes.size(), network->links.size(), network->paths.size(),
// hopCost, desiredPcnt, requested_bw);
while (iteration < maxIter) {
iterate();
cost = solutionCost();
float bw = deliveredBw();
float pcnt = 100 * bw / requested_bw;
iteration += 1;
// printf("\tIteration %lu cost: %e linkcost: %e bw: %e (%f%%)\n",
// iteration, icost, cost, bw, 100.0 * bw / requested_bw);
if (pcnt >= desiredPcnt && numOverShared() == 0)
break;
}
return cost;
}
float Pathfinder::solveConverge(float improvementThreshold, uint64_t maxIter) {
std::deque<float> costs;
float requested_bw = 0.0;
for (PathPtr path: this->network->paths) {
requested_bw += path->requested_bw;
}
// printf("Pathfinder solveConverge:\n");
// printf("\tNodes: %lu\n\tLinks: %lu\n\tPaths: %lu\n\tHopCost:%e\n\tThresh: %e\n\tBandwidth: %e\n",
// network->nodes.size(), network->links.size(), network->paths.size(),
// hopCost, improvementThreshold, requested_bw);
while (iteration < maxIter) {
iterate();
cost = solutionCost();
// float bw = deliveredBw();
costs.push_back(cost);
while (costs.size() > 3) {
costs.pop_front();
}
iteration += 1;
float min = costs.front();
float max = min;
for (float c : costs) {
min = std::min(min, c);
max = std::max(max, c);
}
// printf("\tIteration %lu cost: %e linkcost: %e bw: %e (%f%%)\n",
// iteration, icost, cost, bw, 100.0 * bw / requested_bw);
float diff = max - min;
if (costs.size() >= 3 && diff < improvementThreshold) {
break;
}
if (cost < 0.1) {
// < 1 is a very small cost
break;
}
}
return cost;
}
float Pathfinder::solve(float desiredCost, uint64_t maxIter) {
while (cost > desiredCost && iteration < maxIter) {
iterate();
cost = solutionCost();
iteration += 1;
}
return cost;
}
struct PartialPath {
Path* defn;
float cost;
float bw;
Node* node;
std::vector<Link*> path;
PartialPath(const PathPtr& defn) :
defn(defn.get()),
cost(0),
bw(defn->requested_bw),
node(defn->src.get()) {
}
PartialPath(float hopCost, const PartialPath& orig, Link* next) :
defn(orig.defn),
cost(orig.cost),
bw(next->bwShareW(orig.bw)),
node(orig.nextOverLink(next)),
path(orig.path) {
path.push_back(next);
float nextCost = next->costToUse(hopCost, bw);
cost = cost + nextCost;
}
Node* nextOverLink(Link* next) const {
if (node == next->a.get())
return next->b.get();
else if (node == next->b.get())
return next->a.get();
else
assert(false && "Link being added doesn't connect");
}
void print() {
const char* fullPart = sinkFound() ? "Full" : "Part";
printf("%s path cost: %e node: %p\n", fullPart, cost, node);
for (Link* link : path) {
printf("\t%s -- %s : bw %e, req_bw: %e, paths: %lu\n",
link->a->label.c_str(), link->b->label.c_str(), link->bandwidth,
link->bwRequested, link->paths.size());
}
}
Link* last() {
if (path.size() == 0)
return NULL;
return path.back();
}
bool sinkFound() {
if (path.size() == 0)
return defn->src == defn->dst;
Link* lst = path.back();
return lst->a == defn->dst || lst->b == defn->dst;
}
bool operator<(const PartialPath& other) const {
return this->cost > other.cost;
}
};
float Pathfinder::iterate() {
std::vector<PathPtr> allPaths;
if (iteration == 0) {
allPaths = this->network->getPaths();
} else {
std::set<PathPtr, smart_ptr_less_than> congestedPaths;
for (LinkPtr link : this->network->links) {
if (link->bwRequested > link->bandwidth) {
congestedPaths.insert(link->paths.begin(), link->paths.end());
}
}
allPaths = std::vector<PathPtr>(congestedPaths.begin(), congestedPaths.end());
}
std::random_shuffle(allPaths.begin(), allPaths.end());
float cost = 0.0;
for (PathPtr path : allPaths) {
check_pyerror();
path->ripup();
// Find a new path
std::unordered_set<Node*> nodesSeen;
std::priority_queue<PartialPath> q;
q.push(PartialPath(path));
bool sinkFound = false;
while (!sinkFound) {
assert(!q.empty() && "Could not find path!");
PartialPath bestPath = q.top();
q.pop();
// bestPath.print();
if (bestPath.sinkFound()) {
// The current best path has found its destination
sinkFound = true;
path->assign(bestPath.path, bestPath.bw);
cost += bestPath.cost;
// printf("\t=== Assigned! === \n");
} else if (nodesSeen.find(bestPath.node) == nodesSeen.end()) {
nodesSeen.insert(bestPath.node);
// printf("\tAt node: %s\n", node->label.c_str());
auto& links = this->network->linkIndex[bestPath.node];
for (Link* link : links) {
// printf("\tConsidering: %s -- %s\n",
// link->a->label.c_str(), link->b->label.c_str());
// Don't include the link we just used
if (link != bestPath.last()) {
Node* next = bestPath.nextOverLink(link);
if (nodesSeen.find(next) == nodesSeen.end()) {
PartialPath pp(this->hopCost, bestPath, link);
q.push(pp);
}
}
}
}
}
}
// Increment history penalties
for (LinkPtr link : this->network->links) {
link->incrementPenalties(this->historyCostIncrement, this->overageCostIncrement);
}
return cost;
}
float Pathfinder::solutionCost() {
float cost = 0.0;
for (LinkPtr link : this->network->links) {
cost += link->solutionPartialCost();
}
return cost;
}
size_t Pathfinder::numOverShared() {
size_t num = 0;
for (LinkPtr link : this->network->links) {
if (link->maximum_paths > 0 && link->paths.size() > (size_t)link->maximum_paths)
num += 1;
}
return num;
}
float Pathfinder::deliveredBw() {
float bw = 0.0;
for (PathPtr path: this->network->paths) {
bw += path->delivered_bw;
}
return bw;
}
}
<commit_msg>Make sure everyone gets a wire.<commit_after>#include "bwpathfinder.hpp"
#include "network_simulation.hpp"
#include <queue>
#include <unordered_set>
#include <cstdio>
namespace bwpathfinder {
__attribute__((weak)) void check_pyerror() { }
size_t Node::id_counter = 0;
void Network::simulateDeliveredBandwidth() {
NetworkSimulation sim(shared_from_this());
simfw::Timer<Time> checkup(&sim, 1e-8, [] (uint64_t i) {
check_pyerror();
return true;
});
sim.simulate();
sim.setDeliveredBandwidths();
sim.flushMessages();
// Zero all state variables
for (LinkPtr link : this->links) {
link->paths.clear();
link->bwRequested = 0.0;
}
for (PathPtr path : this->paths) {
path->assign(path->path, path->delivered_bw);
path->num_wires = -1;
}
}
void Network::calcCircuitSwitchedBandwidth() {
// Zero all state variables
for (LinkPtr link : this->links) {
link->paths.clear();
link->bwRequested = 0.0;
}
for (PathPtr path : this->paths) {
path->assign(path->path, path->delivered_bw);
}
for (LinkPtr link : this->links) {
link->allocateWires();
}
}
void Link::allocateWires() {
if (this->maximum_paths <= 0)
return;
const size_t num_wires = this->maximum_paths;
size_t wires_allocated = 0;
float bwPerWire = this->bandwidth / this->maximum_paths;
typedef std::pair<double, PathPtr> dppair;
std::map<PathPtr, int> allocation;
std::priority_queue<dppair, std::vector<dppair>, compare_first> paths;
for (auto path : this->paths) {
allocation[path] = 1;
wires_allocated += 1;
auto p = std::make_pair(path->requested_bw - bwPerWire, path);
if (p.first > 0)
paths.push(p);
}
assert(wires_allocated <= num_wires);
while (paths.size() > 0 && wires_allocated < num_wires) {
dppair p = paths.top();
paths.pop();
allocation[p.second] += 1;
p.first -= bwPerWire;
if (p.first > 0) {
paths.push(p);
}
}
for (auto pipair : allocation) {
assert(pipair.second > 0);
pipair.first->assign_wire(shared_from_this(), pipair.second);
}
}
float Link::costToUse(float hopCost, float bw) const {
// float totBW = bwRequested + bw;
// float overage = totBW > bandwidth ? totBW - bandwidth : 0;
float overage = std::max((float)0.0, bw - this->bwShareW(bw));
return hopCost + (overage * overageExponent) + historyPenalty;
}
float Pathfinder::solveToBwPcnt(float desiredPcnt, uint64_t maxIter) {
desiredPcnt = std::min((float)100.0, desiredPcnt);
float requested_bw = 0.0;
for (PathPtr path: this->network->paths) {
requested_bw += path->requested_bw;
}
// printf("Pathfinder solveToBwPcnt:\n");
// printf("\tNodes: %lu\n\tLinks: %lu\n\tPaths: %lu\n\tHopCost:%e\n\tGoal: %f%%\n\tBandwidth: %e\n",
// network->nodes.size(), network->links.size(), network->paths.size(),
// hopCost, desiredPcnt, requested_bw);
while (iteration < maxIter) {
iterate();
cost = solutionCost();
float bw = deliveredBw();
float pcnt = 100 * bw / requested_bw;
iteration += 1;
// printf("\tIteration %lu cost: %e linkcost: %e bw: %e (%f%%)\n",
// iteration, icost, cost, bw, 100.0 * bw / requested_bw);
if (pcnt >= desiredPcnt && numOverShared() == 0)
break;
}
return cost;
}
float Pathfinder::solveConverge(float improvementThreshold, uint64_t maxIter) {
std::deque<float> costs;
float requested_bw = 0.0;
for (PathPtr path: this->network->paths) {
requested_bw += path->requested_bw;
}
// printf("Pathfinder solveConverge:\n");
// printf("\tNodes: %lu\n\tLinks: %lu\n\tPaths: %lu\n\tHopCost:%e\n\tThresh: %e\n\tBandwidth: %e\n",
// network->nodes.size(), network->links.size(), network->paths.size(),
// hopCost, improvementThreshold, requested_bw);
while (iteration < maxIter) {
iterate();
cost = solutionCost();
// float bw = deliveredBw();
costs.push_back(cost);
while (costs.size() > 3) {
costs.pop_front();
}
iteration += 1;
float min = costs.front();
float max = min;
for (float c : costs) {
min = std::min(min, c);
max = std::max(max, c);
}
// printf("\tIteration %lu cost: %e linkcost: %e bw: %e (%f%%)\n",
// iteration, icost, cost, bw, 100.0 * bw / requested_bw);
float diff = max - min;
if (costs.size() >= 3 && diff < improvementThreshold) {
break;
}
if (cost < 0.1) {
// < 1 is a very small cost
break;
}
}
return cost;
}
float Pathfinder::solve(float desiredCost, uint64_t maxIter) {
while (cost > desiredCost && iteration < maxIter) {
iterate();
cost = solutionCost();
iteration += 1;
}
return cost;
}
struct PartialPath {
Path* defn;
float cost;
float bw;
Node* node;
std::vector<Link*> path;
PartialPath(const PathPtr& defn) :
defn(defn.get()),
cost(0),
bw(defn->requested_bw),
node(defn->src.get()) {
}
PartialPath(float hopCost, const PartialPath& orig, Link* next) :
defn(orig.defn),
cost(orig.cost),
bw(next->bwShareW(orig.bw)),
node(orig.nextOverLink(next)),
path(orig.path) {
path.push_back(next);
float nextCost = next->costToUse(hopCost, bw);
cost = cost + nextCost;
}
Node* nextOverLink(Link* next) const {
if (node == next->a.get())
return next->b.get();
else if (node == next->b.get())
return next->a.get();
else
assert(false && "Link being added doesn't connect");
}
void print() {
const char* fullPart = sinkFound() ? "Full" : "Part";
printf("%s path cost: %e node: %p\n", fullPart, cost, node);
for (Link* link : path) {
printf("\t%s -- %s : bw %e, req_bw: %e, paths: %lu\n",
link->a->label.c_str(), link->b->label.c_str(), link->bandwidth,
link->bwRequested, link->paths.size());
}
}
Link* last() {
if (path.size() == 0)
return NULL;
return path.back();
}
bool sinkFound() {
if (path.size() == 0)
return defn->src == defn->dst;
Link* lst = path.back();
return lst->a == defn->dst || lst->b == defn->dst;
}
bool operator<(const PartialPath& other) const {
return this->cost > other.cost;
}
};
float Pathfinder::iterate() {
std::vector<PathPtr> allPaths;
if (iteration == 0) {
allPaths = this->network->getPaths();
} else {
std::set<PathPtr, smart_ptr_less_than> congestedPaths;
for (LinkPtr link : this->network->links) {
if (link->bwRequested > link->bandwidth) {
congestedPaths.insert(link->paths.begin(), link->paths.end());
}
}
allPaths = std::vector<PathPtr>(congestedPaths.begin(), congestedPaths.end());
}
std::random_shuffle(allPaths.begin(), allPaths.end());
float cost = 0.0;
for (PathPtr path : allPaths) {
check_pyerror();
path->ripup();
// Find a new path
std::unordered_set<Node*> nodesSeen;
std::priority_queue<PartialPath> q;
q.push(PartialPath(path));
bool sinkFound = false;
while (!sinkFound) {
assert(!q.empty() && "Could not find path!");
PartialPath bestPath = q.top();
q.pop();
// bestPath.print();
if (bestPath.sinkFound()) {
// The current best path has found its destination
sinkFound = true;
path->assign(bestPath.path, bestPath.bw);
cost += bestPath.cost;
// printf("\t=== Assigned! === \n");
} else if (nodesSeen.find(bestPath.node) == nodesSeen.end()) {
nodesSeen.insert(bestPath.node);
// printf("\tAt node: %s\n", node->label.c_str());
auto& links = this->network->linkIndex[bestPath.node];
for (Link* link : links) {
// printf("\tConsidering: %s -- %s\n",
// link->a->label.c_str(), link->b->label.c_str());
// Don't include the link we just used
if (link != bestPath.last()) {
Node* next = bestPath.nextOverLink(link);
if (nodesSeen.find(next) == nodesSeen.end()) {
PartialPath pp(this->hopCost, bestPath, link);
q.push(pp);
}
}
}
}
}
}
// Increment history penalties
for (LinkPtr link : this->network->links) {
link->incrementPenalties(this->historyCostIncrement, this->overageCostIncrement);
}
return cost;
}
float Pathfinder::solutionCost() {
float cost = 0.0;
for (LinkPtr link : this->network->links) {
cost += link->solutionPartialCost();
}
return cost;
}
size_t Pathfinder::numOverShared() {
size_t num = 0;
for (LinkPtr link : this->network->links) {
if (link->maximum_paths > 0 && link->paths.size() > (size_t)link->maximum_paths)
num += 1;
}
return num;
}
float Pathfinder::deliveredBw() {
float bw = 0.0;
for (PathPtr path: this->network->paths) {
bw += path->delivered_bw;
}
return bw;
}
}
<|endoftext|>
|
<commit_before>#include "FileClient.h"
#include "../util.h"
#include <iostream>
#include <cstring>
#include <stdint.h>
#include <sstream>
#define MAX_SIZE 100
#define BYTE_TO_RECEIVE 100
FileClient::FileClient() {
}
FileClient::~FileClient() {
}
uint64_t FileClient::send(
const std::string & host,
std::string & file_path,
uint64_t from,
uint64_t to)
{
uint64_t data_length = to - from;
if(data_length <= 0) {
std::cerr << "Length is <= 0" << std::endl;
return 0;
}
std::string ip = getHost(host);
unsigned short host_port = getPort(host);
Socket host_socket;
host_socket.connectTo(ip, host_port);
if(!sendNumber(host_socket, data_length)) {
std::cerr << "Failed to send file of length - " << data_length << std::endl;
}
FILE* file_to_send;
file_to_send = fopen(file_path.c_str(), "r");
if(!file_to_send) {
std::cerr << "Failed to open file to send" << std::endl;
fclose(file_to_send);
return 0;
}
if(fseek(file_to_send, from, SEEK_SET)) {
std::cerr << "Failed to seek to position " << from << std::endl;
fclose(file_to_send);
return 0;
}
std::unique_ptr<char[]> buffer(new char[MAX_SIZE + 1]);
// std::unique_ptr<char> buffer(new char);
while(data_length) {
fread(buffer.get(), sizeof(char), MAX_SIZE, file_to_send);
data_length -= MAX_SIZE;
if(ferror(file_to_send)) {
std::cerr << "Failed to read file content" << std::endl;
fclose(file_to_send);
return 0;
}
// std::cout << buffer.get();
int bytes_sent = ::send(host_socket.getFd(), buffer.get(), strlen(buffer.get()), 0);
if(bytes_sent == -1) {
std::cerr << "Failed to write to socket" << std::endl;
fclose(file_to_send);
return 0;
}
if(feof(file_to_send)) {
break;
}
}
uint64_t fileID = getFileID(host_socket);
// std::cout << "FileID: " << fileID << std::endl;
fclose(file_to_send);
return fileID;
}
std::unique_ptr<char[]> FileClient::getFile(const std::string& host, uint64_t id) {
std::string ip = getHost(host);
unsigned short port = getPort(host);
Socket host_socket;
host_socket.connectTo(ip, port);
if(!sendNumber(host_socket, id)) {
std::cerr << "Failed to send file ID" << std::endl;
return nullptr;
}
uint64_t file_size;
if(::recv(host_socket.getFd(), reinterpret_cast<char*>(&file_size), sizeof(uint64_t), 0) == -1) {
std::cerr << "Failed to receive file size" << std::endl;
return nullptr;
}
std::cout << "File size: " << file_size << std::endl;
std::unique_ptr<char[]> file_content(new char[file_size+1]);
while(file_size) {
int byte_read = ::recv(
host_socket.getFd(),
reinterpret_cast<char*>(file_content.get()),
file_size,
0);
printf("byte read: %d \n Message: %s\n", byte_read, file_content.get());
memset(file_content.get(), 0, BYTE_TO_RECEIVE);
file_size -= byte_read;
}
// std::cout << file_content.get() << std::endl;
return std::move(file_content);
}
bool FileClient::sendNumber(const Socket& host_socket, uint64_t number) {
int byte_sent = ::send(
host_socket.getFd(),
reinterpret_cast<const char *>(&number),
sizeof(uint64_t),
0);
if(byte_sent == -1) {
return false;
}
return true;
}
uint64_t FileClient::getFileID(const Socket& host_socket) {
uint64_t file_id;
int file_read = ::recv(host_socket.getFd(), reinterpret_cast<char *>(&file_id), sizeof(uint64_t), 0);
if(file_read == -1) {
std::cerr << "Failed to read from socket" << std::endl;
return 0;
}
return file_id;
}
<commit_msg>fixes in ::send() and getFile()<commit_after>#include "FileClient.h"
#include "../util.h"
#include <iostream>
#include <cstring>
#include <stdint.h>
#include <sstream>
#define MAX_SIZE 100
#define BYTE_TO_RECEIVE 100
FileClient::FileClient() {
}
FileClient::~FileClient() {
}
uint64_t FileClient::send(
const std::string & host,
std::string & file_path,
uint64_t from,
uint64_t to)
{
uint64_t data_length = to - from;
if (data_length <= 0) {
std::cerr << "Length is <= 0" << std::endl;
return 0;
}
std::string ip = getHost(host);
unsigned short host_port = getPort(host);
Socket host_socket;
host_socket.connectTo(ip, host_port);
uint64_t send_file_event = 0;
if (!sendNumber(host_socket, send_file_event)) {
std::cerr << "Failed to send event" << std::endl;
return 0;
}
if (!sendNumber(host_socket, data_length)) {
std::cerr << "Failed to send file of length - " << data_length << std::endl;
return 0;
}
FILE* file_to_send;
file_to_send = fopen(file_path.c_str(), "r");
if (!file_to_send) {
std::cerr << "Failed to open file to send" << std::endl;
fclose(file_to_send);
return 0;
}
if (fseek(file_to_send, from, SEEK_SET)) {
std::cerr << "Failed to seek to position " << from << std::endl;
fclose(file_to_send);
return 0;
}
std::unique_ptr<char[]> buffer(new char[MAX_SIZE + 1]);
while (data_length) {
int byte_read = fread(buffer.get(), sizeof(char), MAX_SIZE, file_to_send);
data_length -= byte_read;
if (ferror(file_to_send)) {
std::cerr << "Failed to read file content" << std::endl;
fclose(file_to_send);
return 0;
}
int bytes_sent = ::send(host_socket.getFd(), buffer.get(), byte_read, 0);
if (bytes_sent == -1) {
std::cerr << "Failed to write to socket" << std::endl;
fclose(file_to_send);
return 0;
}
}
uint64_t fileID = getFileID(host_socket);
// std::cout << "FileID: " << fileID << std::endl;
fclose(file_to_send);
return fileID;
}
std::unique_ptr<char[]> FileClient::getFile(const std::string& host, uint64_t id) {
std::string ip = getHost(host);
unsigned short port = getPort(host);
Socket host_socket;
host_socket.connectTo(ip, port);
uint64_t request_file_event = 1;
if (!sendNumber(host_socket, request_file_event)) {
std::cerr << "Failed to send event" << std::endl;
return nullptr;
}
if (!sendNumber(host_socket, id)) {
std::cerr << "Failed to send file ID" << std::endl;
return nullptr;
}
uint64_t file_size;
if (::recv(host_socket.getFd(), reinterpret_cast<char*>(&file_size), sizeof(uint64_t), 0) != sizeof(uint64_t)) {
std::cerr << "Failed to receive file size" << std::endl;
return nullptr;
}
std::cout << "File size: " << file_size << std::endl;
std::unique_ptr<char[]> file_content(new char[file_size]);
//TODO: remove
uint64_t x;
::recv(host_socket, reinterpret_cast<char*>(&x), sizeof(x), 0);
std::cout << x << std::endl;
::recv(host_socket, reinterpret_cast<char*>(&x), sizeof(x), 0);
std::cout << x << std::endl;
file_size -= 8 * 2;
int offset = 0;
while (file_size > 0) {
int byte_read = ::recv(
host_socket.getFd(),
reinterpret_cast<char*>(file_content.get() + offset),
file_size,
0);
//printf("byte read: %d \n Message: %s\n", byte_read, file_content.get());
file_size -= byte_read;
offset += byte_read;
}
//printf("byte read: %d \n Message: %s\n", offset, file_content.get());
return std::move(file_content);
}
bool FileClient::sendNumber(const Socket& host_socket, uint64_t number) {
int byte_sent = ::send(
host_socket.getFd(),
reinterpret_cast<const char *>(&number),
sizeof(number),
0);
if (byte_sent != sizeof(number)) {
return false;
}
return true;
}
uint64_t FileClient::getFileID(const Socket& host_socket) {
uint64_t file_id;
int file_read = ::recv(host_socket.getFd(), reinterpret_cast<char *>(&file_id), sizeof(uint64_t), 0);
if (file_read != sizeof(uint64_t)) {
std::cerr << "Failed to read from socket" << std::endl;
return 0;
}
return file_id;
}<|endoftext|>
|
<commit_before>//
// calcPWP.cpp
//
//
// Created by Evan McCartney-Melstad on 1/10/15.
//
//
#include "calcPWP.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <thread>
#include <string>
int calcPWPfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int numThreads) {
//****MODIFY THIS TO ONLY READ IN N LOCI AT A TIME, INSTEAD OF USING THE ENTIRE FILE****
std::streampos size;
std::ifstream file (binaryFile, std::ios::in|std::ios::binary|std::ios::ate);
//ifstream file ("test500k.binary8bitunsigned", ios::in|ios::binary|ios::ate);
if (file.is_open()) {
size = file.tellg(); // Just a variable that shows position of stream--at end since ios::ate, so it's the file size. PROBABLY WON'T WORK FOR FILES LARGER THAN ~ 2GB!
file.seekg (0, std::ios::beg); // Go back to the beginning of the file
//file.read((char*)readCounts, size); // cast to a char* to give to file.read
//unsigned char* readCounts;
//readCounts = new unsigned char[size];
std::vector<unsigned char> readCounts(size);
file.read((char*) &readCounts[0], size);
file.close();
std::cout << "the entire file content is in memory" << std::endl;
std::cout << "the total size of the file is " << size << std::endl;
std::cout << "the number of elements in the readCounts vector is: " << readCounts.size() << std::endl; // Will give the total size bytes divided by the size of one element--so it gives the number of elements
// We now have an array of numIndividuals * 2 (major and minor allele) * 1million (loci)
//int totalLoci = (int)size / (numIndividuals*2); // The 1 million locus file has 999,999 sites in it (because of header line)
//int totalLoci = size/(272*2);
//std::vector< std::vector<long double> > pwp(numIndividuals, std::vector<long double>(numIndividuals,0));
//std::vector< std::vector<unsigned long long int> > weightings(numIndividuals, std::vector<unsigned long long int>(numIndividuals,0));
//long double pwp[numIndividuals][numIndividuals] = {0.0}; // This is the matrix that will hold the pwp estimates
//unsigned long long int weightings[numIndividuals][numIndividuals] = {0.0}; // This is the matrix that will hold the weightings--need to use a long long because the values are basically equal to the coverage squared by the end
/* We are going to split the loci between numThreads threads. Each thread will modify two multidimensional
vectors of the forms std::vector< std::vector<long double> > pwp(numIndividuals, std::vector<long double>(numIndividuals,0)) and std::vector< std::vector<unsigned long long int> > weightings(numIndividuals, std::vector<unsigned long long int>(numIndividuals,0))
First, we'll generate all of these vectors, which apparently in C++ needs to be constructed of a
vector of two-dimensional vectors...
*/
std::vector<std::vector<std::vector<long double>>> pwpThreads(numThreads, std::vector<std::vector<long double>> (numIndividuals, std::vector<long double> (numIndividuals,0) ) ); //pwpThreads[0] is the first 2D array for the first thread, etc...
std::vector<std::vector<std::vector<unsigned long long int>>> weightingsThreads(numThreads, std::vector<std::vector<unsigned long long int> > (numIndividuals, std::vector<unsigned long long int> (numIndividuals,0) ) );
// Now we need to determine how many loci for each thread. If we want to use the entire binary file, instead of numLoci loci, then change this to lociPerThread = (size/(numIndividuals*2))/numThreads
//unsigned long long int lociPerThread = numLoci / numThreads;
unsigned long long int lociPerThread = numLoci;
//std::thread t;
//std::thread t[numThreads];
std::vector<std::thread> threadsVec;
for (int threadRunning = 0; threadRunning < numThreads; threadRunning++) {
unsigned long long int firstLocus = (unsigned long long int) threadRunning * lociPerThread;
unsigned long long int finishingLocus = ((unsigned long long int) threadRunning * lociPerThread) + lociPerThread - (unsigned long long)1.0;
std::cout << "Got to the function call" << std::endl;
//calcPWPforRange(firstLocus, finishingLocus, 272, readCounts, pwp, weightings);
threadsVec.push_back(std::thread(calcPWPforRange, firstLocus, finishingLocus, numIndividuals, std::ref(readCounts), std::ref(pwpThreads[threadRunning]), std::ref(weightingsThreads[threadRunning])));
//std::thread t = std::thread(calcPWPforRange, firstLocus, finishingLocus, std::thread(readCounts), std::thread(pwpThreads[threadRunning]), std::thread(weightingsThreads[threadRunning]));
}
//t.join();
// Wait on threads to finish
for (int i = 0; i < numThreads; ++i) {
threadsVec[i].join();
}
// Now aggregate the results of the threads and print final results
std::vector<std::vector<long double>> weightingsSum(272, std::vector<long double>(272,0));
std::vector<std::vector<long double>> pwpSum(272, std::vector<long double>(272,0));
for (int element = 0; element < 272; element++) {
for (int comparisonElement = 0; comparisonElement <= element; comparisonElement++) {
for (int threadVector = 0; threadVector <= numThreads; threadVector++) {
weightingsSum[element][comparisonElement] += weightingsThreads[threadVector][element][comparisonElement];
pwpSum[element][comparisonElement] += pwpThreads[threadVector][element][comparisonElement];
}
}
}
// Now print out the final output to the pairwise pi file:
std::ofstream pwpOUT (outFile);
int rowCounter = 0;
if (!pwpOUT) {
std::cerr << "Crap, " << outFile << "didn't open!" << std::endl;
} else {
for (int tortoise=0; tortoise <= (numIndividuals-1); tortoise++) {
for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {
rowCounter++;
//std::cout << "Made it past the beginning of the last end for loop" << std::endl;
//std::cout << "Tortoise numbers: " << tortoise << " and " << comparisonTortoise << std::endl;
if (weightingsSum[tortoise][comparisonTortoise] > 0) {
//std::cout << weightings[tortoise][comparisonTortoise] << std::endl;
//std::cout << pwp[tortoise][comparisonTortoise] / weightings[tortoise][comparisonTortoise] << std::endl;
pwpOUT << pwpSum[tortoise][comparisonTortoise] / weightingsSum[tortoise][comparisonTortoise] << std::endl;
} else {
pwpOUT << "NA" << std::endl;
}
}
}
}
} else std::cout << "Unable to open file";
return 0;
}
//int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, const std::vector<BYTE>& mainReadCountVector, std::vector< std::vector<long double> > & threadPWP, std::vector< std::vector<long double> > & threadWeightings) {
int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, std::vector<unsigned char>& mainReadCountVector, std::vector<std::vector<long double>>& threadPWP, std::vector<std::vector<unsigned long long int>>& threadWeightings) {
std::cout << "Calculating PWP for the following locus range: " << startingLocus << " to " << endingLocus << std::endl;
for( unsigned long long locus = startingLocus; locus < endingLocus; locus++) {
//std::cout << "Processing locus # " << locus << std::endl;
if (locus % 100000 == 0) {
std::cout << locus << " loci processed through calcPWPfromBinaryFile" << std::endl;
}
int coverages[numIndividuals];
double *majorAlleleFreqs = new double[numIndividuals]; // This will hold the major allele frequencies for that locus for each tortoise
for( int tortoise = 0; tortoise <= (numIndividuals-1); tortoise++ ) {
unsigned long long majorIndex = locus * (numIndividuals*2) + 2 * tortoise;
unsigned long long minorIndex = locus * (numIndividuals*2) + 2 * tortoise + 1;
coverages[tortoise] = int(mainReadCountVector[majorIndex]) + int(mainReadCountVector[minorIndex]); // Hold the coverages for each locus
if ( coverages[tortoise] > 0 ) {
//std::cout << "Made it to line 222 for locus " << locus << std::endl;
majorAlleleFreqs[tortoise] = (double)mainReadCountVector[majorIndex] / (double)coverages[tortoise]; // Not necessarily an int, but could be 0 or 1
if (coverages[tortoise] > 1) {
unsigned long long locusWeighting = coverages[tortoise]*(coverages[tortoise]-1);
threadWeightings[tortoise][tortoise] += (unsigned long long)locusWeighting; // This is an int--discrete number of reads
threadPWP[tortoise][tortoise] += double(locusWeighting) * (2.0 * majorAlleleFreqs[tortoise] * (double(coverages[tortoise]) - double(mainReadCountVector[majorIndex]))) / (double((coverages[tortoise])-1.0));
}
for( int comparisonTortoise = 0; comparisonTortoise < tortoise; comparisonTortoise++) {
if (coverages[comparisonTortoise] > 0) {
double locusWeighting = (double)coverages[tortoise] * (double)coverages[comparisonTortoise];
threadWeightings[tortoise][comparisonTortoise] += locusWeighting;
threadPWP[tortoise][comparisonTortoise] += (double)locusWeighting * (majorAlleleFreqs[tortoise] * (1.0-majorAlleleFreqs[comparisonTortoise]) + majorAlleleFreqs[comparisonTortoise] * (1.0-majorAlleleFreqs[tortoise]));
}
}
}
}
delete[] majorAlleleFreqs; // Needed to avoid memory leaks
}
return 0;
}
<commit_msg>Minor changes<commit_after>//
// calcPWP.cpp
//
//
// Created by Evan McCartney-Melstad on 1/10/15.
//
//
#include "calcPWP.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <thread>
#include <string>
int calcPWPfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int numThreads) {
//****MODIFY THIS TO ONLY READ IN N LOCI AT A TIME, INSTEAD OF USING THE ENTIRE FILE****
std::streampos size;
std::ifstream file (binaryFile, std::ios::in|std::ios::binary|std::ios::ate);
//ifstream file ("test500k.binary8bitunsigned", ios::in|ios::binary|ios::ate);
if (file.is_open()) {
size = file.tellg(); // Just a variable that shows position of stream--at end since ios::ate, so it's the file size. PROBABLY WON'T WORK FOR FILES LARGER THAN ~ 2GB!
file.seekg (0, std::ios::beg); // Go back to the beginning of the file
//file.read((char*)readCounts, size); // cast to a char* to give to file.read
//unsigned char* readCounts;
//readCounts = new unsigned char[size];
std::vector<unsigned char> readCounts(size);
file.read((char*) &readCounts[0], size);
file.close();
std::cout << "the entire file content is in memory" << std::endl;
std::cout << "the total size of the file is " << size << std::endl;
std::cout << "the number of elements in the readCounts vector is: " << readCounts.size() << std::endl; // Will give the total size bytes divided by the size of one element--so it gives the number of elements
// We now have an array of numIndividuals * 2 (major and minor allele) * 1million (loci)
//int totalLoci = (int)size / (numIndividuals*2); // The 1 million locus file has 999,999 sites in it (because of header line)
//int totalLoci = size/(272*2);
//std::vector< std::vector<long double> > pwp(numIndividuals, std::vector<long double>(numIndividuals,0));
//std::vector< std::vector<unsigned long long int> > weightings(numIndividuals, std::vector<unsigned long long int>(numIndividuals,0));
//long double pwp[numIndividuals][numIndividuals] = {0.0}; // This is the matrix that will hold the pwp estimates
//unsigned long long int weightings[numIndividuals][numIndividuals] = {0.0}; // This is the matrix that will hold the weightings--need to use a long long because the values are basically equal to the coverage squared by the end
/* We are going to split the loci between numThreads threads. Each thread will modify two multidimensional
vectors of the forms std::vector< std::vector<long double> > pwp(numIndividuals, std::vector<long double>(numIndividuals,0)) and std::vector< std::vector<unsigned long long int> > weightings(numIndividuals, std::vector<unsigned long long int>(numIndividuals,0))
First, we'll generate all of these vectors, which apparently in C++ needs to be constructed of a
vector of two-dimensional vectors...
*/
std::vector<std::vector<std::vector<long double>>> pwpThreads(numThreads, std::vector<std::vector<long double>> (numIndividuals, std::vector<long double> (numIndividuals,0) ) ); //pwpThreads[0] is the first 2D array for the first thread, etc...
std::vector<std::vector<std::vector<unsigned long long int>>> weightingsThreads(numThreads, std::vector<std::vector<unsigned long long int> > (numIndividuals, std::vector<unsigned long long int> (numIndividuals,0) ) );
// Now we need to determine how many loci for each thread. If we want to use the entire binary file, instead of numLoci loci, then change this to lociPerThread = (size/(numIndividuals*2))/numThreads
//unsigned long long int lociPerThread = numLoci / numThreads;
unsigned long long int lociPerThread = numLoci;
//std::thread t;
//std::thread t[numThreads];
std::vector<std::thread> threadsVec;
for (int threadRunning = 0; threadRunning < numThreads; threadRunning++) {
unsigned long long int firstLocus = (unsigned long long int) threadRunning * lociPerThread;
unsigned long long int finishingLocus = ((unsigned long long int) threadRunning * lociPerThread) + lociPerThread - (unsigned long long)1.0;
std::cout << "Got to the function call. Running thread # " << threadRunning << std::endl;
//calcPWPforRange(firstLocus, finishingLocus, 272, readCounts, pwp, weightings);
threadsVec.push_back(std::thread(calcPWPforRange, firstLocus, finishingLocus, numIndividuals, std::ref(readCounts), std::ref(pwpThreads[threadRunning]), std::ref(weightingsThreads[threadRunning])));
//std::thread t = std::thread(calcPWPforRange, firstLocus, finishingLocus, std::thread(readCounts), std::thread(pwpThreads[threadRunning]), std::thread(weightingsThreads[threadRunning]));
}
//t.join();
// Wait on threads to finish
for (int i = 0; i < numThreads; ++i) {
threadsVec[i].join();
}
// Now aggregate the results of the threads and print final results
std::vector<std::vector<long double>> weightingsSum(272, std::vector<long double>(272,0));
std::vector<std::vector<long double>> pwpSum(272, std::vector<long double>(272,0));
for (int element = 0; element < 272; element++) {
for (int comparisonElement = 0; comparisonElement <= element; comparisonElement++) {
for (int threadVector = 0; threadVector <= numThreads; threadVector++) {
weightingsSum[element][comparisonElement] += weightingsThreads[threadVector][element][comparisonElement];
pwpSum[element][comparisonElement] += pwpThreads[threadVector][element][comparisonElement];
}
}
}
// Now print out the final output to the pairwise pi file:
std::ofstream pwpOUT (outFile);
int rowCounter = 0;
if (!pwpOUT) {
std::cerr << "Crap, " << outFile << "didn't open!" << std::endl;
} else {
for (int tortoise=0; tortoise <= (numIndividuals-1); tortoise++) {
for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {
rowCounter++;
//std::cout << "Made it past the beginning of the last end for loop" << std::endl;
//std::cout << "Tortoise numbers: " << tortoise << " and " << comparisonTortoise << std::endl;
if (weightingsSum[tortoise][comparisonTortoise] > 0) {
//std::cout << weightings[tortoise][comparisonTortoise] << std::endl;
//std::cout << pwp[tortoise][comparisonTortoise] / weightings[tortoise][comparisonTortoise] << std::endl;
pwpOUT << pwpSum[tortoise][comparisonTortoise] / weightingsSum[tortoise][comparisonTortoise] << std::endl;
} else {
pwpOUT << "NA" << std::endl;
}
}
}
}
} else std::cout << "Unable to open file";
return 0;
}
//int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, const std::vector<BYTE>& mainReadCountVector, std::vector< std::vector<long double> > & threadPWP, std::vector< std::vector<long double> > & threadWeightings) {
int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, std::vector<unsigned char>& mainReadCountVector, std::vector<std::vector<long double>>& threadPWP, std::vector<std::vector<unsigned long long int>>& threadWeightings) {
std::cout << "Calculating PWP for the following locus range: " << startingLocus << " to " << endingLocus << std::endl;
for( unsigned long long locus = startingLocus; locus < endingLocus; locus++) {
//std::cout << "Processing locus # " << locus << std::endl;
if (locus % 100000 == 0) {
std::cout << locus << " loci processed through calcPWPfromBinaryFile" << std::endl;
}
int coverages[numIndividuals];
double *majorAlleleFreqs = new double[numIndividuals]; // This will hold the major allele frequencies for that locus for each tortoise
for( int tortoise = 0; tortoise <= (numIndividuals-1); tortoise++ ) {
unsigned long long majorIndex = locus * (numIndividuals*2) + 2 * tortoise;
unsigned long long minorIndex = locus * (numIndividuals*2) + 2 * tortoise + 1;
coverages[tortoise] = int(mainReadCountVector[majorIndex]) + int(mainReadCountVector[minorIndex]); // Hold the coverages for each locus
if ( coverages[tortoise] > 0 ) {
//std::cout << "Made it to line 222 for locus " << locus << std::endl;
majorAlleleFreqs[tortoise] = (double)mainReadCountVector[majorIndex] / (double)coverages[tortoise]; // Not necessarily an int, but could be 0 or 1
if (coverages[tortoise] > 1) {
unsigned long long locusWeighting = coverages[tortoise]*(coverages[tortoise]-1);
threadWeightings[tortoise][tortoise] += (unsigned long long)locusWeighting; // This is an int--discrete number of reads
threadPWP[tortoise][tortoise] += double(locusWeighting) * (2.0 * majorAlleleFreqs[tortoise] * (double(coverages[tortoise]) - double(mainReadCountVector[majorIndex]))) / (double((coverages[tortoise])-1.0));
}
for( int comparisonTortoise = 0; comparisonTortoise < tortoise; comparisonTortoise++) {
if (coverages[comparisonTortoise] > 0) {
double locusWeighting = (double)coverages[tortoise] * (double)coverages[comparisonTortoise];
threadWeightings[tortoise][comparisonTortoise] += locusWeighting;
threadPWP[tortoise][comparisonTortoise] += (double)locusWeighting * (majorAlleleFreqs[tortoise] * (1.0-majorAlleleFreqs[comparisonTortoise]) + majorAlleleFreqs[comparisonTortoise] * (1.0-majorAlleleFreqs[tortoise]));
}
}
}
}
delete[] majorAlleleFreqs; // Needed to avoid memory leaks
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
* The MIT License
*
* Copyright 2017-2018 Norwegian University of Technology
*
* 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 <fmicpp/fmi2/xml/ScalarVariable.hpp>
using namespace std;
using namespace fmicpp::fmi2::xml;
void ScalarVariable::load(const ptree &node) {
name_ = node.get<string>("<xmlattr>.name");
description_ = node.get<string>("<xmlattr>.description", "");
valueReference_ = node.get<fmi2ValueReference>("<xmlattr>.valueReference");
canHandleMultipleSetPerTimelnstant_ = node.get<bool>("<xmlattr>.canHandleMultipleSetPerTimelnstant", false);
causality_ = parseCausality(node.get<string>("<xmlattr>.causality", ""));
variability_ = parseVariability(node.get<string>("<xmlattr>.variability", ""));
initial_ = parseInitial(node.get<string>("<xmlattr>.initial", ""));
for (const ptree::value_type &v : node) {
if (v.first == "Integer") {
integerAttribute_ = make_unique<IntegerAttribute>(IntegerAttribute());
integerAttribute_->load(v.second);
} else if (v.first == "Real") {
realAttribute_ = make_unique<RealAttribute>(RealAttribute());
realAttribute_->load(v.second);
} else if (v.first == "String") {
stringAttribute_ = make_unique<StringAttribute>(StringAttribute());
stringAttribute_->load(v.second);
} else if (v.first == "Boolean") {
booleanAttribute_ = make_unique<BooleanAttribute>(BooleanAttribute());
booleanAttribute_->load(v.second);
} else if (v.first == "Enumeration") {
enumerationAttribute_ = make_unique<EnumerationAttribute>(EnumerationAttribute());
enumerationAttribute_->load(v.second);
}
}
}
IntegerVariable ScalarVariable::asIntegerVariable() {
if (integerAttribute_ == nullptr) {
throw runtime_error(getName() + "is not of type Integer!");
}
return IntegerVariable(*this, *integerAttribute_);
}
RealVariable ScalarVariable::asRealVariable() {
if (realAttribute_ == nullptr) {
throw runtime_error(getName() + "is not of type Real!");
}
return RealVariable(*this, *realAttribute_);
}
StringVariable ScalarVariable::asStringVariable() {
if (stringAttribute_ == nullptr) {
throw runtime_error(getName() + "is not of type String!");
}
return StringVariable(*this, *stringAttribute_);
}
BooleanVariable ScalarVariable::asBooleanVariable() {
if (booleanAttribute_ == nullptr) {
throw runtime_error(getName() + "is not of type Boolean!");
}
return BooleanVariable(*this, *booleanAttribute_);
}
EnumerationVariable ScalarVariable::asEnumerationVariable() {
if (enumerationAttribute_ == nullptr) {
throw runtime_error(getName() + "is not of type Enumeration!");
}
return EnumerationVariable(*this, *enumerationAttribute_);
}
string ScalarVariable::getName() const {
return name_;
}
string ScalarVariable::getDescription() const {
return description_;
}
fmi2ValueReference ScalarVariable::getValueReference() const {
return valueReference_;
}
bool ScalarVariable::canHandleMultipleSetPerTimelnstant() const {
return canHandleMultipleSetPerTimelnstant_;
}
fmi2Causality ScalarVariable::getCausality() const {
return causality_;
}
fmi2Variability ScalarVariable::getVariability() const {
return variability_;
}
fmi2Initial ScalarVariable::getInitial() const {
return initial_;
}
IntegerVariable::IntegerVariable(const ScalarVariable &var, IntegerAttribute &attribute)
: ScalarVariable(var), attribute_(attribute) {}
boost::optional<int> IntegerVariable::getMin() const {
return attribute_.min;
}
boost::optional<int> IntegerVariable::getMax() const {
return attribute_.max;
}
boost::optional<int> IntegerVariable::getStart() const {
return attribute_.start;
}
void IntegerVariable::setStart(const int start) {
attribute_.start = start;
}
boost::optional<string> IntegerVariable::getQuantity() const {
return attribute_.quantity;
}
RealVariable::RealVariable(const ScalarVariable &var, RealAttribute &attribute)
: ScalarVariable(var), attribute_(attribute) {}
boost::optional<double> RealVariable::getMin() const {
return attribute_.min;
}
boost::optional<double> RealVariable::getMax() const {
return attribute_.max;
}
boost::optional<double> RealVariable::getStart() const {
return attribute_.start;
}
void RealVariable::setStart(const double start) {
attribute_.start = start;
}
boost::optional<double> RealVariable::getNominal() const {
return attribute_.nominal;
}
bool RealVariable::getReinit() const {
return attribute_.reinit;
}
bool RealVariable::getUnbounded() const {
return attribute_.unbounded;
}
bool RealVariable::getRelativeQuantity() const {
return attribute_.relativeQuantity;
}
boost::optional<string> RealVariable::getQuantity() const {
return attribute_.quantity;
}
boost::optional<string> RealVariable::getUnit() const {
return attribute_.unit;
}
boost::optional<string> RealVariable::getDisplayUnit() const {
return attribute_.displayUnit;
}
boost::optional<unsigned int> RealVariable::getDerivative() const {
return attribute_.derivative;
}
StringVariable::StringVariable(const ScalarVariable &var, StringAttribute &attribute)
: ScalarVariable(var), attribute_(attribute) {}
boost::optional<string> StringVariable::getStart() const {
return attribute_.start;
}
void StringVariable::setStart(const string &start) {
attribute_.start = start;
}
BooleanVariable::BooleanVariable(const ScalarVariable &var, BooleanAttribute &attribute)
: ScalarVariable(var), attribute_(attribute) {}
boost::optional<bool> BooleanVariable::getStart() const {
return attribute_.start;
}
void BooleanVariable::setStart(const bool start) {
attribute_.start = make_shared<bool>(start);
}
EnumerationVariable::EnumerationVariable(const ScalarVariable &var, EnumerationAttribute &attribute)
: ScalarVariable(var), attribute_(attribute) {}
boost::optional<int> EnumerationVariable::getMin() const {
return attribute_.min;
}
boost::optional<int> EnumerationVariable::getMax() const {
return attribute_.max;
}
boost::optional<int> EnumerationVariable::getStart() const {
return attribute_.start;
}
void EnumerationVariable::setStart(const int start) {
attribute_.start = start;
}
boost::optional<string> EnumerationVariable::getQuantity() const {
return attribute_.quantity;
}
<commit_msg>Fix compilation on Ubuntu 18.04<commit_after>/*
* The MIT License
*
* Copyright 2017-2018 Norwegian University of Technology
*
* 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 <fmicpp/fmi2/xml/ScalarVariable.hpp>
using namespace std;
using namespace fmicpp::fmi2::xml;
void ScalarVariable::load(const ptree &node) {
name_ = node.get<string>("<xmlattr>.name");
description_ = node.get<string>("<xmlattr>.description", "");
valueReference_ = node.get<fmi2ValueReference>("<xmlattr>.valueReference");
canHandleMultipleSetPerTimelnstant_ = node.get<bool>("<xmlattr>.canHandleMultipleSetPerTimelnstant", false);
causality_ = parseCausality(node.get<string>("<xmlattr>.causality", ""));
variability_ = parseVariability(node.get<string>("<xmlattr>.variability", ""));
initial_ = parseInitial(node.get<string>("<xmlattr>.initial", ""));
for (const ptree::value_type &v : node) {
if (v.first == "Integer") {
integerAttribute_ = make_unique<IntegerAttribute>(IntegerAttribute());
integerAttribute_->load(v.second);
} else if (v.first == "Real") {
realAttribute_ = make_unique<RealAttribute>(RealAttribute());
realAttribute_->load(v.second);
} else if (v.first == "String") {
stringAttribute_ = make_unique<StringAttribute>(StringAttribute());
stringAttribute_->load(v.second);
} else if (v.first == "Boolean") {
booleanAttribute_ = make_unique<BooleanAttribute>(BooleanAttribute());
booleanAttribute_->load(v.second);
} else if (v.first == "Enumeration") {
enumerationAttribute_ = make_unique<EnumerationAttribute>(EnumerationAttribute());
enumerationAttribute_->load(v.second);
}
}
}
IntegerVariable ScalarVariable::asIntegerVariable() {
if (integerAttribute_ == nullptr) {
throw runtime_error(getName() + "is not of type Integer!");
}
return IntegerVariable(*this, *integerAttribute_);
}
RealVariable ScalarVariable::asRealVariable() {
if (realAttribute_ == nullptr) {
throw runtime_error(getName() + "is not of type Real!");
}
return RealVariable(*this, *realAttribute_);
}
StringVariable ScalarVariable::asStringVariable() {
if (stringAttribute_ == nullptr) {
throw runtime_error(getName() + "is not of type String!");
}
return StringVariable(*this, *stringAttribute_);
}
BooleanVariable ScalarVariable::asBooleanVariable() {
if (booleanAttribute_ == nullptr) {
throw runtime_error(getName() + "is not of type Boolean!");
}
return BooleanVariable(*this, *booleanAttribute_);
}
EnumerationVariable ScalarVariable::asEnumerationVariable() {
if (enumerationAttribute_ == nullptr) {
throw runtime_error(getName() + "is not of type Enumeration!");
}
return EnumerationVariable(*this, *enumerationAttribute_);
}
string ScalarVariable::getName() const {
return name_;
}
string ScalarVariable::getDescription() const {
return description_;
}
fmi2ValueReference ScalarVariable::getValueReference() const {
return valueReference_;
}
bool ScalarVariable::canHandleMultipleSetPerTimelnstant() const {
return canHandleMultipleSetPerTimelnstant_;
}
fmi2Causality ScalarVariable::getCausality() const {
return causality_;
}
fmi2Variability ScalarVariable::getVariability() const {
return variability_;
}
fmi2Initial ScalarVariable::getInitial() const {
return initial_;
}
IntegerVariable::IntegerVariable(const ScalarVariable &var, IntegerAttribute &attribute)
: ScalarVariable(var), attribute_(attribute) {}
boost::optional<int> IntegerVariable::getMin() const {
return attribute_.min;
}
boost::optional<int> IntegerVariable::getMax() const {
return attribute_.max;
}
boost::optional<int> IntegerVariable::getStart() const {
return attribute_.start;
}
void IntegerVariable::setStart(const int start) {
attribute_.start = start;
}
boost::optional<string> IntegerVariable::getQuantity() const {
return attribute_.quantity;
}
RealVariable::RealVariable(const ScalarVariable &var, RealAttribute &attribute)
: ScalarVariable(var), attribute_(attribute) {}
boost::optional<double> RealVariable::getMin() const {
return attribute_.min;
}
boost::optional<double> RealVariable::getMax() const {
return attribute_.max;
}
boost::optional<double> RealVariable::getStart() const {
return attribute_.start;
}
void RealVariable::setStart(const double start) {
attribute_.start = start;
}
boost::optional<double> RealVariable::getNominal() const {
return attribute_.nominal;
}
bool RealVariable::getReinit() const {
return attribute_.reinit;
}
bool RealVariable::getUnbounded() const {
return attribute_.unbounded;
}
bool RealVariable::getRelativeQuantity() const {
return attribute_.relativeQuantity;
}
boost::optional<string> RealVariable::getQuantity() const {
return attribute_.quantity;
}
boost::optional<string> RealVariable::getUnit() const {
return attribute_.unit;
}
boost::optional<string> RealVariable::getDisplayUnit() const {
return attribute_.displayUnit;
}
boost::optional<unsigned int> RealVariable::getDerivative() const {
return attribute_.derivative;
}
StringVariable::StringVariable(const ScalarVariable &var, StringAttribute &attribute)
: ScalarVariable(var), attribute_(attribute) {}
boost::optional<string> StringVariable::getStart() const {
return attribute_.start;
}
void StringVariable::setStart(const string &start) {
attribute_.start = start;
}
BooleanVariable::BooleanVariable(const ScalarVariable &var, BooleanAttribute &attribute)
: ScalarVariable(var), attribute_(attribute) {}
boost::optional<bool> BooleanVariable::getStart() const {
return attribute_.start;
}
void BooleanVariable::setStart(const bool start) {
attribute_.start = start;
}
EnumerationVariable::EnumerationVariable(const ScalarVariable &var, EnumerationAttribute &attribute)
: ScalarVariable(var), attribute_(attribute) {}
boost::optional<int> EnumerationVariable::getMin() const {
return attribute_.min;
}
boost::optional<int> EnumerationVariable::getMax() const {
return attribute_.max;
}
boost::optional<int> EnumerationVariable::getStart() const {
return attribute_.start;
}
void EnumerationVariable::setStart(const int start) {
attribute_.start = start;
}
boost::optional<string> EnumerationVariable::getQuantity() const {
return attribute_.quantity;
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
shared_bus.cpp
This file belongs to the KisTA library
All rights reserved by the authors (until further License definition)
Author: F. Herrera
Institution: University of Cantabria
Deparment: Electronic Systems
Date: 2015 April
Last Date revision:
Notes: Implementation of the shared bus model supporting
* worst case analysis, with previous check that the assumsions to provide
a WCCT are fulfilled. Otherwise, an error is raised
* model for actual, precise commuication time (CT), based on the current state and activity
in the bus and on the arbitration policy
* Support of priorities (e.g. to model architectures, such as AXI
which can give support to mixed-criticality applications
* statistical CT, (as a faster model, which can be reused in other tools,
like VIPPE)
*****************************************************************************/
#ifndef SHARED_BUS_CPP
#define SHARED_BUS_CPP
#include <map>
//#include <string>
#include <systemc.h>
#include "defaults.hpp"
#include "global_elements.hpp"
#include "shared_bus.hpp"
#include "processing_element.hpp"
#include "draw.hpp"
#include "utils.hpp"
namespace kista {
#define MAX_SHARED_BUS_CONFIGURATION_ERROR 0.001
// 0.1%
void shared_bus::set_default_params() {
// initialization values according to the default values
bus_width_bits = 32; // in bits
bus_bandwidth_bps = 100000;
bus_frequency_Hz = 3200000;
}
shared_bus::shared_bus(sc_module_name name) {
set_default_params();
}
// Bus attribute setters/getters
void shared_bus::set_width(unsigned int width_bits){
check_call_before_sim_start("set_width");
bus_width_bits = width_bits;
}
unsigned int& shared_bus::get_width() { // return bus width in bits
return bus_width_bits;
}
void shared_bus::set_frequency(double frequency_Hz){
check_call_before_sim_start("set_frequency");
bus_frequency_Hz = frequency_Hz;
}
double& shared_bus::get_frequency() { // return bus frequency in Hz
return bus_frequency_Hz;
}
void shared_bus::set_bandwidth(double bandwith_bps) {
check_call_before_sim_start("set_bandwidth");
bus_bandwidth_bps = bandwith_bps;
}
double& shared_bus::get_bandwidth() { // return bus bandwidth in bps
return bus_bandwidth_bps;
}
void shared_bus::before_end_of_elaboration() {
double calc_bandwidth_bps;
double error; // percentual error, deviation over the lower bandwidth value,
// either settled or calculated, to make consider the more restrictive case
std::string msg;
calc_bandwidth_bps = bus_width_bits*bus_frequency_Hz;
// calculates the biggest error possible (as an absolute value, always positive)
if(bus_width_bits==0.0) {
msg="Setting shared bus \"";
msg += this->name();
msg += "\". Bus width cannot be 0 bits.";
SC_REPORT_ERROR("KisTA",msg.c_str());
}
if(bus_bandwidth_bps==0.0) {
msg="Setting shared bus \"";
msg += this->name();
msg += "\". Bus bandwidth cannot be 0 bps.";
SC_REPORT_ERROR("KisTA",msg.c_str());
}
if(bus_frequency_Hz==0.0) {
msg="Setting shared bus \"";
msg += this->name();
msg += "\". Bus frequency cannot be 0.0 Hz.";
SC_REPORT_ERROR("KisTA",msg.c_str());
}
if(calc_bandwidth_bps<bus_bandwidth_bps) {
error = (bus_bandwidth_bps-calc_bandwidth_bps)/calc_bandwidth_bps;
} else {
error = (calc_bandwidth_bps-bus_bandwidth_bps)/bus_bandwidth_bps;
}
if(error>MAX_SHARED_BUS_CONFIGURATION_ERROR) {
msg="Setting shared bus \"";
msg += this->name();
msg += "\". Incoherent setting of attributes. The product of the current bus bandwidth (";
msg += bus_bandwidth_bps;
msg += " bits), per the bus frequency (";
msg += bus_frequency_Hz;
msg += " Hz) yields a deviation from the configured bus bandwith (";
msg += error;
msg += " bps) bigger than the maximum allowed deviation configured (";
msg += MAX_SHARED_BUS_CONFIGURATION_ERROR;
msg += " )";
SC_REPORT_ERROR("KisTA",msg.c_str());
}
}
void shared_bus::report_bus_configuration() {
cout << "Shared Bus " << name() << " configuration completed: " << endl;
cout << "\t\t bus width (bits) = " << bus_width_bits << endl;
cout << "\t\t bus bandwidth (bps) = " << bus_bandwidth_bps << endl;
cout << "\t\t bus frequency (frequency) = " << bus_frequency_Hz << endl;
}
} // namespace kista
#endif
<commit_msg>provides void implementation of e2e delay methods for shared bus to let the compilation of the library<commit_after>/*****************************************************************************
shared_bus.cpp
This file belongs to the KisTA library
All rights reserved by the authors (until further License definition)
Author: F. Herrera
Institution: University of Cantabria
Deparment: Electronic Systems
Date: 2015 April
Last Date revision:
Notes: Implementation of the shared bus model supporting
* worst case analysis, with previous check that the assumsions to provide
a WCCT are fulfilled. Otherwise, an error is raised
* model for actual, precise commuication time (CT), based on the current state and activity
in the bus and on the arbitration policy
* Support of priorities (e.g. to model architectures, such as AXI
which can give support to mixed-criticality applications
* statistical CT, (as a faster model, which can be reused in other tools,
like VIPPE)
*****************************************************************************/
#ifndef SHARED_BUS_CPP
#define SHARED_BUS_CPP
#include <map>
//#include <string>
#include <systemc.h>
#include "defaults.hpp"
#include "global_elements.hpp"
#include "shared_bus.hpp"
#include "processing_element.hpp"
#include "draw.hpp"
#include "utils.hpp"
namespace kista {
#define MAX_SHARED_BUS_CONFIGURATION_ERROR 0.001
// 0.1%
void shared_bus::set_default_params() {
// initialization values according to the default values
bus_width_bits = 32; // in bits
bus_bandwidth_bps = 100000;
bus_frequency_Hz = 3200000;
}
shared_bus::shared_bus(sc_module_name name) {
set_default_params();
}
// Bus attribute setters/getters
void shared_bus::set_width(unsigned int width_bits){
check_call_before_sim_start("set_width");
bus_width_bits = width_bits;
}
unsigned int& shared_bus::get_width() { // return bus width in bits
return bus_width_bits;
}
void shared_bus::set_frequency(double frequency_Hz){
check_call_before_sim_start("set_frequency");
bus_frequency_Hz = frequency_Hz;
}
double& shared_bus::get_frequency() { // return bus frequency in Hz
return bus_frequency_Hz;
}
void shared_bus::set_bandwidth(double bandwith_bps) {
check_call_before_sim_start("set_bandwidth");
bus_bandwidth_bps = bandwith_bps;
}
double& shared_bus::get_bandwidth() { // return bus bandwidth in bps
return bus_bandwidth_bps;
}
void shared_bus::before_end_of_elaboration() {
double calc_bandwidth_bps;
double error; // percentual error, deviation over the lower bandwidth value,
// either settled or calculated, to make consider the more restrictive case
std::string msg;
calc_bandwidth_bps = bus_width_bits*bus_frequency_Hz;
// calculates the biggest error possible (as an absolute value, always positive)
if(bus_width_bits==0.0) {
msg="Setting shared bus \"";
msg += this->name();
msg += "\". Bus width cannot be 0 bits.";
SC_REPORT_ERROR("KisTA",msg.c_str());
}
if(bus_bandwidth_bps==0.0) {
msg="Setting shared bus \"";
msg += this->name();
msg += "\". Bus bandwidth cannot be 0 bps.";
SC_REPORT_ERROR("KisTA",msg.c_str());
}
if(bus_frequency_Hz==0.0) {
msg="Setting shared bus \"";
msg += this->name();
msg += "\". Bus frequency cannot be 0.0 Hz.";
SC_REPORT_ERROR("KisTA",msg.c_str());
}
if(calc_bandwidth_bps<bus_bandwidth_bps) {
error = (bus_bandwidth_bps-calc_bandwidth_bps)/calc_bandwidth_bps;
} else {
error = (calc_bandwidth_bps-bus_bandwidth_bps)/bus_bandwidth_bps;
}
if(error>MAX_SHARED_BUS_CONFIGURATION_ERROR) {
msg="Setting shared bus \"";
msg += this->name();
msg += "\". Incoherent setting of attributes. The product of the current bus bandwidth (";
msg += bus_bandwidth_bps;
msg += " bits), per the bus frequency (";
msg += bus_frequency_Hz;
msg += " Hz) yields a deviation from the configured bus bandwith (";
msg += error;
msg += " bps) bigger than the maximum allowed deviation configured (";
msg += MAX_SHARED_BUS_CONFIGURATION_ERROR;
msg += " )";
SC_REPORT_ERROR("KisTA",msg.c_str());
}
}
void shared_bus::report_bus_configuration() {
cout << "Shared Bus " << name() << " configuration completed: " << endl;
cout << "\t\t bus width (bits) = " << bus_width_bits << endl;
cout << "\t\t bus bandwidth (bps) = " << bus_bandwidth_bps << endl;
cout << "\t\t bus frequency (frequency) = " << bus_frequency_Hz << endl;
}
// -------------------------------------------------------------
// Overloading Implementation of virtual assessment methods
// -------------------------------------------------------------
void shared_bus::set_MaxP2Pdelay(phy_address src, phy_address dest, unsigned int msg_size)
{
SC_REPORT_ERROR("KisTA","method of shared bus not implemented");
}
void shared_bus::set_MaxP2Pdelay(phy_link_t &link, unsigned int msg_size)
{
SC_REPORT_ERROR("KisTA","method of shared bus not implemented");
}
sc_time& shared_bus::get_MaxP2Pdelay(phy_address src, phy_address dest, unsigned int msg_size) {
SC_REPORT_ERROR("KisTA","method of shared bus not implemented");
}
sc_time& shared_bus::get_MaxP2Pdelay(phy_link_t &link, unsigned int msg_size) {
SC_REPORT_ERROR("KisTA","method of shared bus not implemented");
}
void shared_bus::set_CurrentP2Pdelay(phy_address src, phy_address dest, unsigned int msg_size) {
SC_REPORT_ERROR("KisTA","method of shared bus not implemented");
}
void shared_bus::set_CurrentP2Pdelay(phy_link_t &link, unsigned int msg_size)
{
SC_REPORT_ERROR("KisTA","method of shared bus not implemented");
}
sc_time& shared_bus::get_CurrentP2Pdelay(phy_address src, phy_address dest, unsigned int msg_size)
{
SC_REPORT_ERROR("KisTA","method of shared bus not implemented");
}
sc_time& shared_bus::get_CurrentP2Pdelay(phy_link_t &link, unsigned int msg_size) {
SC_REPORT_ERROR("KisTA","method of shared bus not implemented");
}
} // namespace kista
#endif
<|endoftext|>
|
<commit_before>//===- CodeEmitterGen.cpp - Code Emitter Generator ------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// CodeEmitterGen uses the descriptions of instructions and their fields to
// construct an automated code emitter: a function that, given a MachineInstr,
// returns the (currently, 32-bit unsigned) value of the instruction.
//
//===----------------------------------------------------------------------===//
#include "CodeEmitterGen.h"
#include "CodeGenTarget.h"
#include "llvm/TableGen/Record.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include <map>
using namespace llvm;
// FIXME: Somewhat hackish to use a command line option for this. There should
// be a CodeEmitter class in the Target.td that controls this sort of thing
// instead.
static cl::opt<bool>
MCEmitter("mc-emitter",
cl::desc("Generate CodeEmitter for use with the MC library."),
cl::init(false));
void CodeEmitterGen::reverseBits(std::vector<Record*> &Insts) {
for (std::vector<Record*>::iterator I = Insts.begin(), E = Insts.end();
I != E; ++I) {
Record *R = *I;
if (R->getValueAsString("Namespace") == "TargetOpcode" ||
R->getValueAsBit("isPseudo"))
continue;
BitsInit *BI = R->getValueAsBitsInit("Inst");
unsigned numBits = BI->getNumBits();
SmallVector<Init *, 16> NewBits(numBits);
for (unsigned bit = 0, end = numBits / 2; bit != end; ++bit) {
unsigned bitSwapIdx = numBits - bit - 1;
Init *OrigBit = BI->getBit(bit);
Init *BitSwap = BI->getBit(bitSwapIdx);
NewBits[bit] = BitSwap;
NewBits[bitSwapIdx] = OrigBit;
}
if (numBits % 2) {
unsigned middle = (numBits + 1) / 2;
NewBits[middle] = BI->getBit(middle);
}
BitsInit *NewBI = BitsInit::get(NewBits);
// Update the bits in reversed order so that emitInstrOpBits will get the
// correct endianness.
R->getValue("Inst")->setValue(NewBI);
}
}
// If the VarBitInit at position 'bit' matches the specified variable then
// return the variable bit position. Otherwise return -1.
int CodeEmitterGen::getVariableBit(const std::string &VarName,
BitsInit *BI, int bit) {
if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(BI->getBit(bit))) {
if (VarInit *VI = dynamic_cast<VarInit*>(VBI->getVariable()))
if (VI->getName() == VarName)
return VBI->getBitNum();
} else if (VarInit *VI = dynamic_cast<VarInit*>(BI->getBit(bit))) {
if (VI->getName() == VarName)
return 0;
}
return -1;
}
void CodeEmitterGen::
AddCodeToMergeInOperand(Record *R, BitsInit *BI, const std::string &VarName,
unsigned &NumberedOp,
std::string &Case, CodeGenTarget &Target) {
CodeGenInstruction &CGI = Target.getInstruction(R);
// Determine if VarName actually contributes to the Inst encoding.
int bit = BI->getNumBits()-1;
// Scan for a bit that this contributed to.
for (; bit >= 0; ) {
if (getVariableBit(VarName, BI, bit) != -1)
break;
--bit;
}
// If we found no bits, ignore this value, otherwise emit the call to get the
// operand encoding.
if (bit < 0) return;
// If the operand matches by name, reference according to that
// operand number. Non-matching operands are assumed to be in
// order.
unsigned OpIdx;
if (CGI.Operands.hasOperandNamed(VarName, OpIdx)) {
// Get the machine operand number for the indicated operand.
OpIdx = CGI.Operands[OpIdx].MIOperandNo;
assert(!CGI.Operands.isFlatOperandNotEmitted(OpIdx) &&
"Explicitly used operand also marked as not emitted!");
} else {
/// If this operand is not supposed to be emitted by the
/// generated emitter, skip it.
while (CGI.Operands.isFlatOperandNotEmitted(NumberedOp))
++NumberedOp;
OpIdx = NumberedOp++;
}
std::pair<unsigned, unsigned> SO = CGI.Operands.getSubOperandNumber(OpIdx);
std::string &EncoderMethodName = CGI.Operands[SO.first].EncoderMethodName;
// If the source operand has a custom encoder, use it. This will
// get the encoding for all of the suboperands.
if (!EncoderMethodName.empty()) {
// A custom encoder has all of the information for the
// sub-operands, if there are more than one, so only
// query the encoder once per source operand.
if (SO.second == 0) {
Case += " // op: " + VarName + "\n" +
" op = " + EncoderMethodName + "(MI, " + utostr(OpIdx);
if (MCEmitter)
Case += ", Fixups";
Case += ");\n";
}
} else {
Case += " // op: " + VarName + "\n" +
" op = getMachineOpValue(MI, MI.getOperand(" + utostr(OpIdx) + ")";
if (MCEmitter)
Case += ", Fixups";
Case += ");\n";
}
for (; bit >= 0; ) {
int varBit = getVariableBit(VarName, BI, bit);
// If this bit isn't from a variable, skip it.
if (varBit == -1) {
--bit;
continue;
}
// Figure out the consecutive range of bits covered by this operand, in
// order to generate better encoding code.
int beginInstBit = bit;
int beginVarBit = varBit;
int N = 1;
for (--bit; bit >= 0;) {
varBit = getVariableBit(VarName, BI, bit);
if (varBit == -1 || varBit != (beginVarBit - N)) break;
++N;
--bit;
}
unsigned opMask = ~0U >> (32-N);
int opShift = beginVarBit - N + 1;
opMask <<= opShift;
opShift = beginInstBit - beginVarBit;
if (opShift > 0) {
Case += " Value |= (op & UINT64_C(" + utostr(opMask) + ")) << " +
itostr(opShift) + ";\n";
} else if (opShift < 0) {
Case += " Value |= (op & UINT64_C(" + utostr(opMask) + ")) >> " +
itostr(-opShift) + ";\n";
} else {
Case += " Value |= op & UINT64_C(" + utostr(opMask) + ");\n";
}
}
}
std::string CodeEmitterGen::getInstructionCase(Record *R,
CodeGenTarget &Target) {
std::string Case;
BitsInit *BI = R->getValueAsBitsInit("Inst");
const std::vector<RecordVal> &Vals = R->getValues();
unsigned NumberedOp = 0;
// Loop over all of the fields in the instruction, determining which are the
// operands to the instruction.
for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
// Ignore fixed fields in the record, we're looking for values like:
// bits<5> RST = { ?, ?, ?, ?, ? };
if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
continue;
AddCodeToMergeInOperand(R, BI, Vals[i].getName(), NumberedOp, Case, Target);
}
std::string PostEmitter = R->getValueAsString("PostEncoderMethod");
if (!PostEmitter.empty())
Case += " Value = " + PostEmitter + "(MI, Value);\n";
return Case;
}
void CodeEmitterGen::run(raw_ostream &o) {
CodeGenTarget Target(Records);
std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
// For little-endian instruction bit encodings, reverse the bit order
if (Target.isLittleEndianEncoding()) reverseBits(Insts);
EmitSourceFileHeader("Machine Code Emitter", o);
const std::vector<const CodeGenInstruction*> &NumberedInstructions =
Target.getInstructionsByEnumValue();
// Emit function declaration
o << "uint64_t " << Target.getName();
if (MCEmitter)
o << "MCCodeEmitter::getBinaryCodeForInstr(const MCInst &MI,\n"
<< " SmallVectorImpl<MCFixup> &Fixups) const {\n";
else
o << "CodeEmitter::getBinaryCodeForInstr(const MachineInstr &MI) const {\n";
// Emit instruction base values
o << " static const unsigned InstBits[] = {\n";
for (std::vector<const CodeGenInstruction*>::const_iterator
IN = NumberedInstructions.begin(),
EN = NumberedInstructions.end();
IN != EN; ++IN) {
const CodeGenInstruction *CGI = *IN;
Record *R = CGI->TheDef;
if (R->getValueAsString("Namespace") == "TargetOpcode" ||
R->getValueAsBit("isPseudo")) {
o << " UINT64_C(0),\n";
continue;
}
BitsInit *BI = R->getValueAsBitsInit("Inst");
// Start by filling in fixed values.
unsigned Value = 0;
for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {
if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1)))
Value |= B->getValue() << (e-i-1);
}
o << " UINT64_C(" << Value << ")," << '\t' << "// " << R->getName() << "\n";
}
o << " UINT64_C(0)\n };\n";
// Map to accumulate all the cases.
std::map<std::string, std::vector<std::string> > CaseMap;
// Construct all cases statement for each opcode
for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end();
IC != EC; ++IC) {
Record *R = *IC;
if (R->getValueAsString("Namespace") == "TargetOpcode" ||
R->getValueAsBit("isPseudo"))
continue;
const std::string &InstName = R->getValueAsString("Namespace") + "::"
+ R->getName();
std::string Case = getInstructionCase(R, Target);
CaseMap[Case].push_back(InstName);
}
// Emit initial function code
o << " const unsigned opcode = MI.getOpcode();\n"
<< " unsigned Value = InstBits[opcode];\n"
<< " unsigned op = 0;\n"
<< " (void)op; // suppress warning\n"
<< " switch (opcode) {\n";
// Emit each case statement
std::map<std::string, std::vector<std::string> >::iterator IE, EE;
for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) {
const std::string &Case = IE->first;
std::vector<std::string> &InstList = IE->second;
for (int i = 0, N = InstList.size(); i < N; i++) {
if (i) o << "\n";
o << " case " << InstList[i] << ":";
}
o << " {\n";
o << Case;
o << " break;\n"
<< " }\n";
}
// Default case: unhandled opcode
o << " default:\n"
<< " std::string msg;\n"
<< " raw_string_ostream Msg(msg);\n"
<< " Msg << \"Not supported instr: \" << MI;\n"
<< " report_fatal_error(Msg.str());\n"
<< " }\n"
<< " return Value;\n"
<< "}\n\n";
}
<commit_msg>Fix support for encodings up to 64-bits in length. TableGen was silently truncating them to 32-bits prior to this.<commit_after>//===- CodeEmitterGen.cpp - Code Emitter Generator ------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// CodeEmitterGen uses the descriptions of instructions and their fields to
// construct an automated code emitter: a function that, given a MachineInstr,
// returns the (currently, 32-bit unsigned) value of the instruction.
//
//===----------------------------------------------------------------------===//
#include "CodeEmitterGen.h"
#include "CodeGenTarget.h"
#include "llvm/TableGen/Record.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include <map>
using namespace llvm;
// FIXME: Somewhat hackish to use a command line option for this. There should
// be a CodeEmitter class in the Target.td that controls this sort of thing
// instead.
static cl::opt<bool>
MCEmitter("mc-emitter",
cl::desc("Generate CodeEmitter for use with the MC library."),
cl::init(false));
void CodeEmitterGen::reverseBits(std::vector<Record*> &Insts) {
for (std::vector<Record*>::iterator I = Insts.begin(), E = Insts.end();
I != E; ++I) {
Record *R = *I;
if (R->getValueAsString("Namespace") == "TargetOpcode" ||
R->getValueAsBit("isPseudo"))
continue;
BitsInit *BI = R->getValueAsBitsInit("Inst");
unsigned numBits = BI->getNumBits();
SmallVector<Init *, 16> NewBits(numBits);
for (unsigned bit = 0, end = numBits / 2; bit != end; ++bit) {
unsigned bitSwapIdx = numBits - bit - 1;
Init *OrigBit = BI->getBit(bit);
Init *BitSwap = BI->getBit(bitSwapIdx);
NewBits[bit] = BitSwap;
NewBits[bitSwapIdx] = OrigBit;
}
if (numBits % 2) {
unsigned middle = (numBits + 1) / 2;
NewBits[middle] = BI->getBit(middle);
}
BitsInit *NewBI = BitsInit::get(NewBits);
// Update the bits in reversed order so that emitInstrOpBits will get the
// correct endianness.
R->getValue("Inst")->setValue(NewBI);
}
}
// If the VarBitInit at position 'bit' matches the specified variable then
// return the variable bit position. Otherwise return -1.
int CodeEmitterGen::getVariableBit(const std::string &VarName,
BitsInit *BI, int bit) {
if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(BI->getBit(bit))) {
if (VarInit *VI = dynamic_cast<VarInit*>(VBI->getVariable()))
if (VI->getName() == VarName)
return VBI->getBitNum();
} else if (VarInit *VI = dynamic_cast<VarInit*>(BI->getBit(bit))) {
if (VI->getName() == VarName)
return 0;
}
return -1;
}
void CodeEmitterGen::
AddCodeToMergeInOperand(Record *R, BitsInit *BI, const std::string &VarName,
unsigned &NumberedOp,
std::string &Case, CodeGenTarget &Target) {
CodeGenInstruction &CGI = Target.getInstruction(R);
// Determine if VarName actually contributes to the Inst encoding.
int bit = BI->getNumBits()-1;
// Scan for a bit that this contributed to.
for (; bit >= 0; ) {
if (getVariableBit(VarName, BI, bit) != -1)
break;
--bit;
}
// If we found no bits, ignore this value, otherwise emit the call to get the
// operand encoding.
if (bit < 0) return;
// If the operand matches by name, reference according to that
// operand number. Non-matching operands are assumed to be in
// order.
unsigned OpIdx;
if (CGI.Operands.hasOperandNamed(VarName, OpIdx)) {
// Get the machine operand number for the indicated operand.
OpIdx = CGI.Operands[OpIdx].MIOperandNo;
assert(!CGI.Operands.isFlatOperandNotEmitted(OpIdx) &&
"Explicitly used operand also marked as not emitted!");
} else {
/// If this operand is not supposed to be emitted by the
/// generated emitter, skip it.
while (CGI.Operands.isFlatOperandNotEmitted(NumberedOp))
++NumberedOp;
OpIdx = NumberedOp++;
}
std::pair<unsigned, unsigned> SO = CGI.Operands.getSubOperandNumber(OpIdx);
std::string &EncoderMethodName = CGI.Operands[SO.first].EncoderMethodName;
// If the source operand has a custom encoder, use it. This will
// get the encoding for all of the suboperands.
if (!EncoderMethodName.empty()) {
// A custom encoder has all of the information for the
// sub-operands, if there are more than one, so only
// query the encoder once per source operand.
if (SO.second == 0) {
Case += " // op: " + VarName + "\n" +
" op = " + EncoderMethodName + "(MI, " + utostr(OpIdx);
if (MCEmitter)
Case += ", Fixups";
Case += ");\n";
}
} else {
Case += " // op: " + VarName + "\n" +
" op = getMachineOpValue(MI, MI.getOperand(" + utostr(OpIdx) + ")";
if (MCEmitter)
Case += ", Fixups";
Case += ");\n";
}
for (; bit >= 0; ) {
int varBit = getVariableBit(VarName, BI, bit);
// If this bit isn't from a variable, skip it.
if (varBit == -1) {
--bit;
continue;
}
// Figure out the consecutive range of bits covered by this operand, in
// order to generate better encoding code.
int beginInstBit = bit;
int beginVarBit = varBit;
int N = 1;
for (--bit; bit >= 0;) {
varBit = getVariableBit(VarName, BI, bit);
if (varBit == -1 || varBit != (beginVarBit - N)) break;
++N;
--bit;
}
uint64_t opMask = ~0U >> (64-N);
int opShift = beginVarBit - N + 1;
opMask <<= opShift;
opShift = beginInstBit - beginVarBit;
if (opShift > 0) {
Case += " Value |= (op & UINT64_C(" + utostr(opMask) + ")) << " +
itostr(opShift) + ";\n";
} else if (opShift < 0) {
Case += " Value |= (op & UINT64_C(" + utostr(opMask) + ")) >> " +
itostr(-opShift) + ";\n";
} else {
Case += " Value |= op & UINT64_C(" + utostr(opMask) + ");\n";
}
}
}
std::string CodeEmitterGen::getInstructionCase(Record *R,
CodeGenTarget &Target) {
std::string Case;
BitsInit *BI = R->getValueAsBitsInit("Inst");
const std::vector<RecordVal> &Vals = R->getValues();
unsigned NumberedOp = 0;
// Loop over all of the fields in the instruction, determining which are the
// operands to the instruction.
for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
// Ignore fixed fields in the record, we're looking for values like:
// bits<5> RST = { ?, ?, ?, ?, ? };
if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
continue;
AddCodeToMergeInOperand(R, BI, Vals[i].getName(), NumberedOp, Case, Target);
}
std::string PostEmitter = R->getValueAsString("PostEncoderMethod");
if (!PostEmitter.empty())
Case += " Value = " + PostEmitter + "(MI, Value);\n";
return Case;
}
void CodeEmitterGen::run(raw_ostream &o) {
CodeGenTarget Target(Records);
std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
// For little-endian instruction bit encodings, reverse the bit order
if (Target.isLittleEndianEncoding()) reverseBits(Insts);
EmitSourceFileHeader("Machine Code Emitter", o);
const std::vector<const CodeGenInstruction*> &NumberedInstructions =
Target.getInstructionsByEnumValue();
// Emit function declaration
o << "uint64_t " << Target.getName();
if (MCEmitter)
o << "MCCodeEmitter::getBinaryCodeForInstr(const MCInst &MI,\n"
<< " SmallVectorImpl<MCFixup> &Fixups) const {\n";
else
o << "CodeEmitter::getBinaryCodeForInstr(const MachineInstr &MI) const {\n";
// Emit instruction base values
o << " static const uint64_t InstBits[] = {\n";
for (std::vector<const CodeGenInstruction*>::const_iterator
IN = NumberedInstructions.begin(),
EN = NumberedInstructions.end();
IN != EN; ++IN) {
const CodeGenInstruction *CGI = *IN;
Record *R = CGI->TheDef;
if (R->getValueAsString("Namespace") == "TargetOpcode" ||
R->getValueAsBit("isPseudo")) {
o << " UINT64_C(0),\n";
continue;
}
BitsInit *BI = R->getValueAsBitsInit("Inst");
// Start by filling in fixed values.
uint64_t Value = 0;
for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {
if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1)))
Value |= (uint64_t)B->getValue() << (e-i-1);
}
o << " UINT64_C(" << Value << ")," << '\t' << "// " << R->getName() << "\n";
}
o << " UINT64_C(0)\n };\n";
// Map to accumulate all the cases.
std::map<std::string, std::vector<std::string> > CaseMap;
// Construct all cases statement for each opcode
for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end();
IC != EC; ++IC) {
Record *R = *IC;
if (R->getValueAsString("Namespace") == "TargetOpcode" ||
R->getValueAsBit("isPseudo"))
continue;
const std::string &InstName = R->getValueAsString("Namespace") + "::"
+ R->getName();
std::string Case = getInstructionCase(R, Target);
CaseMap[Case].push_back(InstName);
}
// Emit initial function code
o << " const unsigned opcode = MI.getOpcode();\n"
<< " uint64_t Value = InstBits[opcode];\n"
<< " uint64_t op = 0;\n"
<< " (void)op; // suppress warning\n"
<< " switch (opcode) {\n";
// Emit each case statement
std::map<std::string, std::vector<std::string> >::iterator IE, EE;
for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) {
const std::string &Case = IE->first;
std::vector<std::string> &InstList = IE->second;
for (int i = 0, N = InstList.size(); i < N; i++) {
if (i) o << "\n";
o << " case " << InstList[i] << ":";
}
o << " {\n";
o << Case;
o << " break;\n"
<< " }\n";
}
// Default case: unhandled opcode
o << " default:\n"
<< " std::string msg;\n"
<< " raw_string_ostream Msg(msg);\n"
<< " Msg << \"Not supported instr: \" << MI;\n"
<< " report_fatal_error(Msg.str());\n"
<< " }\n"
<< " return Value;\n"
<< "}\n\n";
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <vector>
#include <tuple>
#include <cereal/archives/portable_binary.hpp>
#include <cereal/archives/binary.hpp>
#include <cereal/archives/json.hpp>
#include "locale"
#include "gmpfse.h"
#include "Benchmark.h"
using namespace std;
using namespace forwardsec;
using namespace relicxx;
bytes testVector = {{0x3a, 0x5d, 0x7a, 0x42, 0x44, 0xd3, 0xd8, 0xaf, 0xf5, 0xf3, 0xf1, 0x87, 0x81, 0x82, 0xb2,
0x53, 0x57, 0x30, 0x59, 0x75, 0x8d, 0xe6, 0x18, 0x17, 0x14, 0xdf, 0xa5, 0xa4, 0x0b,0x43,0xAD,0xBC}};
std::vector<string>makeTags(unsigned int n){
std::vector<string> tags(n);
for(unsigned int i=0;i<n;i++){
tags[i] = "tag"+std::to_string(i);
}
return tags;
}
Benchmark benchKeygen(const unsigned int iterations, const unsigned int d =31,
const unsigned int n = 1){
Benchmark b;
for(unsigned int i=0;i < iterations;i++){
GMPfse test(d,n);
b.start();
GMPfsePublicKey pk;
GMPfsePrivateKey sk;
test.keygen(pk,sk);
b.stop();
b.computeTimeInMilliseconds();
}
return b;
}
Benchmark benchEnc(const unsigned int iterations, const unsigned int d =31,
const unsigned int n = 1){
GMPfse test(d,n);
GMPfsePublicKey pk;
GMPfsePrivateKey sk;
test.keygen(pk,sk); Benchmark benchE;
for(unsigned int i=0;i < iterations;i++){
benchE.start();
test.encrypt(pk,testVector,1,makeTags(n));
benchE.stop();
benchE.computeTimeInMilliseconds();
}
return benchE;
}
Benchmark benchDec(const unsigned int iterations, const unsigned int d =31,
const unsigned int n = 1){
GMPfse test(d,n);
GMPfsePublicKey pk;
GMPfsePrivateKey sk;
test.keygen(pk,sk); Benchmark benchD;
GMPfseCiphertext ct = test.encrypt(pk,testVector,1,makeTags(n));;
for(unsigned int i=0;i < iterations;i++){
benchD.start();
test.decrypt(pk,sk,ct);
benchD.stop();
benchD.computeTimeInMilliseconds();
}
return benchD;
}
Benchmark benchPuncFirst(const unsigned int iterations, const unsigned int d =31,
const unsigned int n = 1){
Benchmark benchP;
for(unsigned int i=0;i < iterations;i++){
GMPfse test(d,n);
GMPfsePublicKey pk;
GMPfsePrivateKey sk;
test.keygen(pk,sk);
benchP.start();
test.puncture(pk,sk,"punc"+std::to_string(i));
benchP.stop();
benchP.computeTimeInMilliseconds();
}
return benchP;
}
Benchmark benchPunc(const unsigned int iterations, const unsigned int d =31,
const unsigned int n = 1){
Benchmark benchP;
for(unsigned int i=0;i < iterations;i++){
GMPfse test(d,n);
GMPfsePublicKey pk;
GMPfsePrivateKey sk;
test.keygen(pk,sk);
test.puncture(pk,sk,"punc");
benchP.start();
test.puncture(pk,sk,"punc"+std::to_string(i));
benchP.stop();
benchP.computeTimeInMilliseconds();
}
return benchP;
}
Benchmark benchNextInterval(const unsigned int iterations, const unsigned int d =31,
const unsigned int n = 1){
Benchmark benchN;
for(unsigned int i=0;i < iterations;i++){
GMPfse test(d,n);
GMPfsePublicKey pk;
GMPfsePrivateKey sk;
test.keygen(pk,sk);
benchN.start();
test.prepareNextInterval(pk,sk);
benchN.stop();
benchN.computeTimeInMilliseconds();
}
return benchN;
}
std::vector<std::tuple<unsigned int ,Benchmark>> benchDecPunctured(const unsigned int iterations,
const unsigned int punctures, const unsigned int puncture_steps,
const unsigned int d =31,
const unsigned int n = 1){
std::vector<std::tuple<unsigned int ,Benchmark>> b;
for(unsigned int p = 0; p <= punctures;p+=puncture_steps){
cout << ".";
cout.flush();
Benchmark benchDP;
GMPfse test(d,n);
GMPfsePublicKey pk;
GMPfsePrivateKey sk;
test.keygen(pk,sk);
GMPfseCiphertext ct = test.encrypt(pk,testVector,1,makeTags(n));;
for(unsigned int i =0;i<=p;i++){
if(i%10 == 0) cout << ".";
test.puncture(pk,sk,"punc"+std::to_string(i));
}
for(unsigned int i=0;i <= iterations;i++){
if(i%10 == 0) cout << ".";
benchDP.start();
test.decrypt(pk,sk,ct);
benchDP.stop();
benchDP.computeTimeInMilliseconds();
}
b.push_back(std::make_tuple (p,benchDP));
}
cout <<endl;
return b;
}
void relicSizes(){
PairingGroup group;
ZR z = group.randomZR();
G1 g1 = group.randomG1();
G2 g2 = group.randomG2();
GT gt = group.randomGT();
cout << " Relic byte array sizes non point compressed:" << endl;
cout << "\t ZR: " << z.getBytes().size() << endl;
cout << "\t G1: " << g1.getBytes().size() << endl;
cout << "\t G2: " << g2.getBytes().size() << endl;
cout << "\t GT: " << gt.getBytes().size() << endl;
cout << " Relic byte array sizes point compressed:" << endl;
cout << "\t ZR: " << z.getBytes().size() << endl;
cout << "\t G1: " << g1.getBytes(true).size() << endl;
cout << "\t G2: " << g2.getBytes(true).size() << endl;
cout << "\t GT: " << gt.getBytes(true).size() << endl;
}
template <class T>
void sizes(const unsigned int d =31,const unsigned int n = 1){
GMPfse test(d,n);
GMPfsePublicKey pk;
GMPfsePrivateKey sk;
test.keygen(pk,sk);
PairingGroup group;
{
ZR z = group.randomZR();
stringstream ss;
{
T oarchive(ss);
oarchive(z);
}
cout << "\tZR size:\t" << ss.tellp() <<" bytes " << endl;
}
{
G1 g = group.randomG1();
stringstream ss;
{
T oarchive(ss);
oarchive(g);
}
cout << "\tG1 size:\t" << ss.tellp() <<" bytes " << endl;
}
{
G2 g = group.randomG2();
stringstream ss;
{
T oarchive(ss);
oarchive(g);
}
cout << "\tG2 size:\t" << ss.tellp() <<" bytes " << endl;
}
{
GT g = group.randomGT();
stringstream ss;
{
T oarchive(ss);
oarchive(g);
}
cout << "\tGT size:\t" << ss.tellp() <<" bytes " << endl;
}
{
stringstream ss;
{
T oarchive(ss);
oarchive(pk);
}
cout << "\tPK size:\t" << ss.tellp() <<" bytes " << endl;
}
{
stringstream ss;
{
T oarchive(ss);
oarchive(sk);
}
cout << "\tSK size:\t" << ss.tellp() <<" bytes " << endl;
}
GMPfseCiphertext ct = test.encrypt(pk,testVector,1,makeTags(n));;
{
stringstream ss;
{
T oarchive(ss);
oarchive(ct);
}
cout << "\tCT size:\t" << ss.tellp() <<" bytes " << endl;
}
}
int main()
{
relicResourceHandle h;
unsigned int i = 500;
unsigned int d = 31;
unsigned int n = 1;
Benchmark K,E,D,PF,PS,N,DP;
cout << "Benchmarking " << i << " iterations of Puncturable forward secure encryption with depth " <<
d << " and " << n << " tags" << endl;
std::locale::global(std::locale(""));
std::cout.imbue(std::locale());
relicSizes();
cout <<"Sizes(BinaryOutputArchive) POINT_COMPRESSION=" << POINT_COMPRESS << ":"<< endl;
sizes<cereal::BinaryOutputArchive>();
cout <<"Sizes(PortableBinaryOutputArchive) POINT_COMPRESSION=" << POINT_COMPRESS << ":"<< endl;
sizes<cereal::PortableBinaryOutputArchive>();
cout <<"Sizes(JSONOutputArchive) POINT_COMPRESSION=" << POINT_COMPRESS << ":"<< endl;
sizes<cereal::JSONOutputArchive>();
cout <<"Performance:" << endl;
K = benchKeygen(i,d,n);
cout << "\tkeygen:\t\t\t" << K << endl;
E = benchEnc(i,d,n);
cout << "\tEnc:\t\t\t" << E << endl;
D = benchDec(i,d,n);
cout << "\tDec(unpunctured):\t" << D << endl;
PF = benchPuncFirst(i,d,n);
cout << "\tInitial Puncture:\t" << PF << endl;
PS = benchPunc(i,d,n);
cout << "\tSubsequent Puncture:\t" << PS << endl;
N = benchNextInterval(i,d,n);
cout << "\tNextInterval:\t\t" << N << endl;
cout << "\tDec(punctured):" << endl;
auto marks = benchDecPunctured(i,100,20,d,n);
for(auto m:marks){
cout <<"\t\t" << std::get<0>(m) <<"\t" << std::get<1>(m) << endl;
}
}
<commit_msg>benchnextinervalall<commit_after>#include <iostream>
#include <vector>
#include <tuple>
#include <cereal/archives/portable_binary.hpp>
#include <cereal/archives/binary.hpp>
#include <cereal/archives/json.hpp>
#include "locale"
#include "gmpfse.h"
#include "Benchmark.h"
using namespace std;
using namespace forwardsec;
using namespace relicxx;
bytes testVector = {{0x3a, 0x5d, 0x7a, 0x42, 0x44, 0xd3, 0xd8, 0xaf, 0xf5, 0xf3, 0xf1, 0x87, 0x81, 0x82, 0xb2,
0x53, 0x57, 0x30, 0x59, 0x75, 0x8d, 0xe6, 0x18, 0x17, 0x14, 0xdf, 0xa5, 0xa4, 0x0b,0x43,0xAD,0xBC}};
std::vector<string>makeTags(unsigned int n){
std::vector<string> tags(n);
for(unsigned int i=0;i<n;i++){
tags[i] = "tag"+std::to_string(i);
}
return tags;
}
Benchmark benchKeygen(const unsigned int iterations, const unsigned int d =31,
const unsigned int n = 1){
Benchmark b;
for(unsigned int i=0;i < iterations;i++){
GMPfse test(d,n);
b.start();
GMPfsePublicKey pk;
GMPfsePrivateKey sk;
test.keygen(pk,sk);
b.stop();
b.computeTimeInMilliseconds();
}
return b;
}
Benchmark benchEnc(const unsigned int iterations, const unsigned int d =31,
const unsigned int n = 1){
GMPfse test(d,n);
GMPfsePublicKey pk;
GMPfsePrivateKey sk;
test.keygen(pk,sk); Benchmark benchE;
for(unsigned int i=0;i < iterations;i++){
benchE.start();
test.encrypt(pk,testVector,1,makeTags(n));
benchE.stop();
benchE.computeTimeInMilliseconds();
}
return benchE;
}
Benchmark benchDec(const unsigned int iterations, const unsigned int d =31,
const unsigned int n = 1){
GMPfse test(d,n);
GMPfsePublicKey pk;
GMPfsePrivateKey sk;
test.keygen(pk,sk); Benchmark benchD;
GMPfseCiphertext ct = test.encrypt(pk,testVector,1,makeTags(n));;
for(unsigned int i=0;i < iterations;i++){
benchD.start();
test.decrypt(pk,sk,ct);
benchD.stop();
benchD.computeTimeInMilliseconds();
}
return benchD;
}
Benchmark benchPuncFirst(const unsigned int iterations, const unsigned int d =31,
const unsigned int n = 1){
Benchmark benchP;
for(unsigned int i=0;i < iterations;i++){
GMPfse test(d,n);
GMPfsePublicKey pk;
GMPfsePrivateKey sk;
test.keygen(pk,sk);
benchP.start();
test.puncture(pk,sk,"punc"+std::to_string(i));
benchP.stop();
benchP.computeTimeInMilliseconds();
}
return benchP;
}
Benchmark benchPunc(const unsigned int iterations, const unsigned int d =31,
const unsigned int n = 1){
Benchmark benchP;
for(unsigned int i=0;i < iterations;i++){
GMPfse test(d,n);
GMPfsePublicKey pk;
GMPfsePrivateKey sk;
test.keygen(pk,sk);
test.puncture(pk,sk,"punc");
benchP.start();
test.puncture(pk,sk,"punc"+std::to_string(i));
benchP.stop();
benchP.computeTimeInMilliseconds();
}
return benchP;
}
Benchmark benchNextInterval(const unsigned int iterations, const unsigned int d =31,
const unsigned int n = 1){
Benchmark benchN;
for(unsigned int i=0;i < iterations;i++){
GMPfse test(d,n);
GMPfsePublicKey pk;
GMPfsePrivateKey sk;
test.keygen(pk,sk);
benchN.start();
test.prepareNextInterval(pk,sk);
benchN.stop();
benchN.computeTimeInMilliseconds();
}
return benchN;
}
std::vector<Benchmark> benchNextIntFull(const unsigned int iterations, const unsigned int d =31,
const unsigned int n = 1){
std::vector<Benchmark> b(d);
for(unsigned int i=0;i < iterations;i++){
GMPfse test(d,n);
GMPfsePublicKey pk;
GMPfsePrivateKey sk;
test.keygen(pk,sk);
for(unsigned int dd = 0;dd<d;dd++){
b[dd].start();
test.prepareNextInterval(pk,sk);
b[dd].stop();
b[dd].computeTimeInMilliseconds();
}
}
return b;
}
std::vector<std::tuple<unsigned int ,Benchmark>> benchDecPunctured(const unsigned int iterations,
const unsigned int punctures, const unsigned int puncture_steps,
const unsigned int d =31,
const unsigned int n = 1){
std::vector<std::tuple<unsigned int ,Benchmark>> b;
for(unsigned int p = 0; p <= punctures;p+=puncture_steps){
cout << ".";
cout.flush();
Benchmark benchDP;
GMPfse test(d,n);
GMPfsePublicKey pk;
GMPfsePrivateKey sk;
test.keygen(pk,sk);
GMPfseCiphertext ct = test.encrypt(pk,testVector,1,makeTags(n));;
for(unsigned int i =0;i<=p;i++){
if(i%10 == 0) cout << ".";
test.puncture(pk,sk,"punc"+std::to_string(i));
}
for(unsigned int i=0;i <= iterations;i++){
if(i%10 == 0) cout << ".";
benchDP.start();
test.decrypt(pk,sk,ct);
benchDP.stop();
benchDP.computeTimeInMilliseconds();
}
b.push_back(std::make_tuple (p,benchDP));
}
cout <<endl;
return b;
}
void relicSizes(){
PairingGroup group;
ZR z = group.randomZR();
G1 g1 = group.randomG1();
G2 g2 = group.randomG2();
GT gt = group.randomGT();
cout << " Relic byte array sizes non point compressed:" << endl;
cout << "\t ZR: " << z.getBytes().size() << endl;
cout << "\t G1: " << g1.getBytes().size() << endl;
cout << "\t G2: " << g2.getBytes().size() << endl;
cout << "\t GT: " << gt.getBytes().size() << endl;
cout << " Relic byte array sizes point compressed:" << endl;
cout << "\t ZR: " << z.getBytes().size() << endl;
cout << "\t G1: " << g1.getBytes(true).size() << endl;
cout << "\t G2: " << g2.getBytes(true).size() << endl;
cout << "\t GT: " << gt.getBytes(true).size() << endl;
}
template <class T>
void sizes(const unsigned int d =31,const unsigned int n = 1){
GMPfse test(d,n);
GMPfsePublicKey pk;
GMPfsePrivateKey sk;
test.keygen(pk,sk);
PairingGroup group;
{
ZR z = group.randomZR();
stringstream ss;
{
T oarchive(ss);
oarchive(z);
}
cout << "\tZR size:\t" << ss.tellp() <<" bytes " << endl;
}
{
G1 g = group.randomG1();
stringstream ss;
{
T oarchive(ss);
oarchive(g);
}
cout << "\tG1 size:\t" << ss.tellp() <<" bytes " << endl;
}
{
G2 g = group.randomG2();
stringstream ss;
{
T oarchive(ss);
oarchive(g);
}
cout << "\tG2 size:\t" << ss.tellp() <<" bytes " << endl;
}
{
GT g = group.randomGT();
stringstream ss;
{
T oarchive(ss);
oarchive(g);
}
cout << "\tGT size:\t" << ss.tellp() <<" bytes " << endl;
}
{
stringstream ss;
{
T oarchive(ss);
oarchive(pk);
}
cout << "\tPK size:\t" << ss.tellp() <<" bytes " << endl;
}
{
stringstream ss;
{
T oarchive(ss);
oarchive(sk);
}
cout << "\tSK size:\t" << ss.tellp() <<" bytes " << endl;
}
GMPfseCiphertext ct = test.encrypt(pk,testVector,1,makeTags(n));;
{
stringstream ss;
{
T oarchive(ss);
oarchive(ct);
}
cout << "\tCT size:\t" << ss.tellp() <<" bytes " << endl;
}
}
int main()
{
relicResourceHandle h;
unsigned int i = 500;
unsigned int d = 31;
unsigned int n = 1;
Benchmark K,E,D,PF,PS,N,DP;
cout << "Benchmarking " << i << " iterations of Puncturable forward secure encryption with depth " <<
d << " and " << n << " tags" << endl;
std::locale::global(std::locale(""));
std::cout.imbue(std::locale());
relicSizes();
cout <<"Sizes(BinaryOutputArchive) POINT_COMPRESSION=" << POINT_COMPRESS << ":"<< endl;
sizes<cereal::BinaryOutputArchive>();
cout <<"Sizes(PortableBinaryOutputArchive) POINT_COMPRESSION=" << POINT_COMPRESS << ":"<< endl;
sizes<cereal::PortableBinaryOutputArchive>();
cout <<"Sizes(JSONOutputArchive) POINT_COMPRESSION=" << POINT_COMPRESS << ":"<< endl;
sizes<cereal::JSONOutputArchive>();
cout <<"Performance:" << endl;
K = benchKeygen(i,d,n);
cout << "\tkeygen:\t\t\t" << K << endl;
E = benchEnc(i,d,n);
cout << "\tEnc:\t\t\t" << E << endl;
D = benchDec(i,d,n);
cout << "\tDec(unpunctured):\t" << D << endl;
PF = benchPuncFirst(i,d,n);
cout << "\tInitial Puncture:\t" << PF << endl;
PS = benchPunc(i,d,n);
cout << "\tSubsequent Puncture:\t" << PS << endl;
N = benchNextInterval(i,d,n);
cout << "\tNextInterval:\t\t" << N << endl;
cout << "\tNextIntervals:\n";
auto res = benchNextIntFull(i,d,n);
for(unsigned int j=0;j<res.size();j++){
cout <<"\t\t " << j << "\t" << res[j] <<endl;
}
cout << "\tDec(punctured):" << endl;
auto marks = benchDecPunctured(i,100,20,d,n);
for(auto m:marks){
cout <<"\t\t" << std::get<0>(m) <<"\t" << std::get<1>(m) << endl;
}
}
<|endoftext|>
|
<commit_before>//===- MapFile.cpp --------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the -Map option. It shows lists in order and
// hierarchically the output sections, input sections, input files and
// symbol:
//
// Address Size Align Out In Symbol
// 00201000 00000015 4 .text
// 00201000 0000000e 4 test.o:(.text)
// 0020100e 00000000 0 local
// 00201005 00000000 0 f(int)
//
//===----------------------------------------------------------------------===//
#include "MapFile.h"
#include "InputFiles.h"
#include "LinkerScript.h"
#include "OutputSections.h"
#include "Strings.h"
#include "SymbolTable.h"
#include "SyntheticSections.h"
#include "Threads.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace llvm::object;
using namespace lld;
using namespace lld::elf;
typedef DenseMap<const SectionBase *, SmallVector<Defined *, 4>> SymbolMapTy;
// Print out the first three columns of a line.
static void writeHeader(raw_ostream &OS, uint64_t Addr, uint64_t Size,
uint64_t Align) {
int W = Config->Is64 ? 16 : 8;
OS << format("%0*llx %0*llx %5lld ", W, Addr, W, Size, Align);
}
static std::string indent(int Depth) { return std::string(Depth * 8, ' '); }
// Returns a list of all symbols that we want to print out.
template <class ELFT> static std::vector<Defined *> getSymbols() {
std::vector<Defined *> V;
for (ObjFile<ELFT> *File : ObjFile<ELFT>::Instances) {
for (SymbolBody *B : File->getSymbols()) {
if (auto *DR = dyn_cast<DefinedRegular>(B)) {
if (DR->getFile() == File && !DR->isSection() && DR->Section &&
DR->Section->Live)
V.push_back(DR);
} else if (auto *DC = dyn_cast<DefinedCommon>(B)) {
if (InX::Common)
V.push_back(cast<DefinedCommon>(B));
}
}
}
return V;
}
// Returns a map from sections to their symbols.
static SymbolMapTy getSectionSyms(ArrayRef<Defined *> Syms) {
SymbolMapTy Ret;
for (Defined *S : Syms) {
if (auto *DR = dyn_cast<DefinedRegular>(S))
Ret[DR->Section].push_back(S);
else
Ret[InX::Common].push_back(S);
}
// Sort symbols by address. We want to print out symbols in the
// order in the output file rather than the order they appeared
// in the input files.
for (auto &It : Ret) {
SmallVectorImpl<Defined *> &V = It.second;
std::sort(V.begin(), V.end(),
[](Defined *A, Defined *B) { return A->getVA() < B->getVA(); });
}
return Ret;
}
// Construct a map from symbols to their stringified representations.
// Demangling symbols (which is what toString() does) is slow, so
// we do that in batch using parallel-for.
template <class ELFT>
static DenseMap<Defined *, std::string>
getSymbolStrings(ArrayRef<Defined *> Syms) {
std::vector<std::string> Str(Syms.size());
parallelForEachN(0, Syms.size(), [&](size_t I) {
raw_string_ostream OS(Str[I]);
writeHeader(OS, Syms[I]->getVA(), Syms[I]->template getSize<ELFT>(), 0);
OS << indent(2) << toString(*Syms[I]);
});
DenseMap<Defined *, std::string> Ret;
for (size_t I = 0, E = Syms.size(); I < E; ++I)
Ret[Syms[I]] = std::move(Str[I]);
return Ret;
}
template <class ELFT> void elf::writeMapFile() {
if (Config->MapFile.empty())
return;
// Open a map file for writing.
std::error_code EC;
raw_fd_ostream OS(Config->MapFile, EC, sys::fs::F_None);
if (EC) {
error("cannot open " + Config->MapFile + ": " + EC.message());
return;
}
// Collect symbol info that we want to print out.
std::vector<Defined *> Syms = getSymbols<ELFT>();
SymbolMapTy SectionSyms = getSectionSyms(Syms);
DenseMap<Defined *, std::string> SymStr = getSymbolStrings<ELFT>(Syms);
// Print out the header line.
int W = ELFT::Is64Bits ? 16 : 8;
OS << left_justify("Address", W) << ' ' << left_justify("Size", W)
<< " Align Out In Symbol\n";
// Print out file contents.
for (OutputSection *OSec : OutputSections) {
writeHeader(OS, OSec->Addr, OSec->Size, OSec->Alignment);
OS << OSec->Name << '\n';
// Dump symbols for each input section.
for (BaseCommand *Base : OSec->Commands) {
auto *ISD = dyn_cast<InputSectionDescription>(Base);
if (!ISD)
continue;
for (InputSection *IS : ISD->Sections) {
writeHeader(OS, OSec->Addr + IS->OutSecOff, IS->getSize(),
IS->Alignment);
OS << indent(1) << toString(IS) << '\n';
for (Defined *Sym : SectionSyms[IS])
OS << SymStr[Sym] << '\n';
}
}
}
}
template void elf::writeMapFile<ELF32LE>();
template void elf::writeMapFile<ELF32BE>();
template void elf::writeMapFile<ELF64LE>();
template void elf::writeMapFile<ELF64BE>();
<commit_msg>[ELF] - Fixing buildbot.<commit_after>//===- MapFile.cpp --------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the -Map option. It shows lists in order and
// hierarchically the output sections, input sections, input files and
// symbol:
//
// Address Size Align Out In Symbol
// 00201000 00000015 4 .text
// 00201000 0000000e 4 test.o:(.text)
// 0020100e 00000000 0 local
// 00201005 00000000 0 f(int)
//
//===----------------------------------------------------------------------===//
#include "MapFile.h"
#include "InputFiles.h"
#include "LinkerScript.h"
#include "OutputSections.h"
#include "Strings.h"
#include "SymbolTable.h"
#include "SyntheticSections.h"
#include "Threads.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace llvm::object;
using namespace lld;
using namespace lld::elf;
typedef DenseMap<const SectionBase *, SmallVector<Defined *, 4>> SymbolMapTy;
// Print out the first three columns of a line.
static void writeHeader(raw_ostream &OS, uint64_t Addr, uint64_t Size,
uint64_t Align) {
int W = Config->Is64 ? 16 : 8;
OS << format("%0*llx %0*llx %5lld ", W, Addr, W, Size, Align);
}
static std::string indent(int Depth) { return std::string(Depth * 8, ' '); }
// Returns a list of all symbols that we want to print out.
template <class ELFT> static std::vector<Defined *> getSymbols() {
std::vector<Defined *> V;
for (ObjFile<ELFT> *File : ObjFile<ELFT>::Instances) {
for (SymbolBody *B : File->getSymbols()) {
if (auto *DR = dyn_cast<DefinedRegular>(B)) {
if (DR->getFile() == File && !DR->isSection() && DR->Section &&
DR->Section->Live)
V.push_back(DR);
} else if (auto *DC = dyn_cast<DefinedCommon>(B)) {
if (InX::Common)
V.push_back(DC);
}
}
}
return V;
}
// Returns a map from sections to their symbols.
static SymbolMapTy getSectionSyms(ArrayRef<Defined *> Syms) {
SymbolMapTy Ret;
for (Defined *S : Syms) {
if (auto *DR = dyn_cast<DefinedRegular>(S))
Ret[DR->Section].push_back(S);
else
Ret[InX::Common].push_back(S);
}
// Sort symbols by address. We want to print out symbols in the
// order in the output file rather than the order they appeared
// in the input files.
for (auto &It : Ret) {
SmallVectorImpl<Defined *> &V = It.second;
std::sort(V.begin(), V.end(),
[](Defined *A, Defined *B) { return A->getVA() < B->getVA(); });
}
return Ret;
}
// Construct a map from symbols to their stringified representations.
// Demangling symbols (which is what toString() does) is slow, so
// we do that in batch using parallel-for.
template <class ELFT>
static DenseMap<Defined *, std::string>
getSymbolStrings(ArrayRef<Defined *> Syms) {
std::vector<std::string> Str(Syms.size());
parallelForEachN(0, Syms.size(), [&](size_t I) {
raw_string_ostream OS(Str[I]);
writeHeader(OS, Syms[I]->getVA(), Syms[I]->template getSize<ELFT>(), 0);
OS << indent(2) << toString(*Syms[I]);
});
DenseMap<Defined *, std::string> Ret;
for (size_t I = 0, E = Syms.size(); I < E; ++I)
Ret[Syms[I]] = std::move(Str[I]);
return Ret;
}
template <class ELFT> void elf::writeMapFile() {
if (Config->MapFile.empty())
return;
// Open a map file for writing.
std::error_code EC;
raw_fd_ostream OS(Config->MapFile, EC, sys::fs::F_None);
if (EC) {
error("cannot open " + Config->MapFile + ": " + EC.message());
return;
}
// Collect symbol info that we want to print out.
std::vector<Defined *> Syms = getSymbols<ELFT>();
SymbolMapTy SectionSyms = getSectionSyms(Syms);
DenseMap<Defined *, std::string> SymStr = getSymbolStrings<ELFT>(Syms);
// Print out the header line.
int W = ELFT::Is64Bits ? 16 : 8;
OS << left_justify("Address", W) << ' ' << left_justify("Size", W)
<< " Align Out In Symbol\n";
// Print out file contents.
for (OutputSection *OSec : OutputSections) {
writeHeader(OS, OSec->Addr, OSec->Size, OSec->Alignment);
OS << OSec->Name << '\n';
// Dump symbols for each input section.
for (BaseCommand *Base : OSec->Commands) {
auto *ISD = dyn_cast<InputSectionDescription>(Base);
if (!ISD)
continue;
for (InputSection *IS : ISD->Sections) {
writeHeader(OS, OSec->Addr + IS->OutSecOff, IS->getSize(),
IS->Alignment);
OS << indent(1) << toString(IS) << '\n';
for (Defined *Sym : SectionSyms[IS])
OS << SymStr[Sym] << '\n';
}
}
}
}
template void elf::writeMapFile<ELF32LE>();
template void elf::writeMapFile<ELF32BE>();
template void elf::writeMapFile<ELF64LE>();
template void elf::writeMapFile<ELF64BE>();
<|endoftext|>
|
<commit_before>#ifndef POSTFIX_HPP
#define POSTFIX_HPP
#include <iostream>
#include <iterator>
#include <stdexcept>
namespace dragon {namespace ch2 {
class Postfix
{
public:
using Iter = std::istream_iterator<char>;
Postfix():
curr{std::cin},eos{}
{}
void expr()
{
term();
++curr;
while(true)
{
if( *curr == '+')
{
match('+');
term();
std::cout << '+';
++curr;
}
else if(*curr == '-')
{
match('-');
term();
std::cout << '-';
++curr;
}
else
return;
}
}
private:
Iter curr;
Iter eos;
void term()
{
if(std::isdigit(*curr))
{
std::cout << *curr;
// match(*curr);
}
else
throw std::runtime_error{"syntax error"};
}
void match(char t)
{
if(*curr == t)
++curr;
else
throw std::runtime_error{"syntax error"};
}
};
}}//namespace
#endif // POSTFIX_HPP
<commit_msg>optimizing modified: postfix.hpp<commit_after>#ifndef POSTFIX_HPP
#define POSTFIX_HPP
#include <iostream>
#include <iterator>
#include <stdexcept>
namespace dragon {namespace ch2 {
class Postfix
{
public:
using Iter = std::istream_iterator<char>;
Postfix():
curr{std::cin}
{}
void expr()
{
term();
for(++curr; *curr == '+' || *curr == '-'; ++curr)
{
auto optr = *curr++;
term();
std::cout << optr;
}
}
private:
Iter curr;
void term()
{
if(std::isdigit(*curr))
std::cout << *curr;
else
throw std::runtime_error{"syntax error"};
}
void match(char t)
{
if(*curr == t)
++curr;
else
throw std::runtime_error{"syntax error"};
}
};
}}//namespace
#endif // POSTFIX_HPP
<|endoftext|>
|
<commit_before>//
// ex13_39.cpp
// Exercise 13.39
//
// Created by pezy on 2/3/15.
// Copyright (c) 2015 pezy. All rights reserved.
//
// Write your own version of StrVec, including versions of
// reserve, capacity (9.4, p. 356), and resize (9.3.5, p. 352).
//
#include "ex13_39.h"
void StrVec::push_back(const std::string& s)
{
chk_n_alloc();
alloc.construct(first_free++, s);
}
std::pair<std::string*, std::string*> StrVec::alloc_n_copy(const std::string* b,
const std::string* e)
{
auto data = alloc.allocate(e - b);
return {data, std::uninitialized_copy(b, e, data)};
}
void StrVec::free()
{
if (elements) {
for (auto p = first_free; p != elements;) alloc.destroy(--p);
alloc.deallocate(elements, cap - elements);
}
}
StrVec::StrVec(const StrVec& rhs)
{
auto newdata = alloc_n_copy(rhs.begin(), rhs.end());
elements = newdata.first;
first_free = cap = newdata.second;
}
StrVec::~StrVec()
{
free();
}
StrVec& StrVec::operator=(const StrVec& rhs)
{
auto data = alloc_n_copy(rhs.begin(), rhs.end());
free();
elements = data.first;
first_free = cap = data.second;
return *this;
}
void StrVec::alloc_n_move(size_t new_cap)
{
auto newdata = alloc.allocate(new_cap);
auto dest = newdata;
auto elem = elements;
for (size_t i = 0; i != size(); ++i)
alloc.construct(dest++, std::move(*elem++));
free();
elements = newdata;
first_free = dest;
cap = elements + new_cap;
}
void StrVec::reallocate()
{
auto newcapacity = size() ? 2 * size() : 1;
alloc_n_move(newcapacity);
}
void StrVec::reserve(size_t new_cap)
{
if (new_cap <= capacity()) return;
alloc_n_move(new_cap);
}
void StrVec::resize(size_t count)
{
resize(count, std::string());
}
void StrVec::resize(size_t count, const std::string& s)
{
if (count > size()) {
if (count > capacity()) reserve(count * 2);
for (size_t i = size(); i != count; ++i)
alloc.construct(first_free++, s);
}
else if (count < size()) {
while (first_free != elements + count) alloc.destroy(--first_free);
}
}
<commit_msg>Update ex13_39.cpp<commit_after>//
// ex13_39.cpp
// Exercise 13.39
//
#include <string>
#include <memory>
#include <utility>
#include "ex13_39.h"
using namespace std;
void StrVec::push_back(const string &s)
{
chk_n_alloc();
alloc.construct(first_free++, s);
}
pair<string*, string*> StrVec::alloc_n_copy(const string *b, const string *e)
{
auto data=alloc.allocate(e-b);
return {data, unitialized_copy(b, e, data)};
}
void StrVec::free()
{
if(elements)
{
for(auto p=first_free; p!=elements; )
alloc.destroy(--p);
alloc.deallocate(elements, cap-elements);
}
}
StrVec::StrVec(const StrVec &s)
{
auto newdata=alloc_n_copy(s.begin(), s.end());
elements=newdata.first;
first_free=cap=newdata.second;
}
StrVec::~StrVec()
{
free();
}
StrVec &StrVec::operator=(const StrVec &rhs)
{
auto data=alloc_n_copy(rhs.begin(), rhs.end());
free();
elements=data.first;
first_free=cap=data.second;
return *this;
}
void StrVec::alloc_n_move(size_t new_cap)
{
auto newdata=alloc.allocate(new_cap);
auto dest=newdata;
auto elem=elements;
for(size_t i=0; i!=size(); ++i)
alloc.construct(dest++, std::move(*elem++));
free();
elements=newdata;
first_free=dest;
cap=elements+new_cap;
}
void StrVec::reallocate()
{
auto newcapacity=size() ? 2*size() : 1;
alloc_n_move(newcapacity);
}
void StrVec::reserve(size_t new_cap)
{
if(new_cap<=capacity())
return;
alloc_n_move(new_cap);
}
void StrVec::resize(size_t count)
{
resize(count, string());
}
void StrVec::resize(size_t, const string &s)
{
if(count>size())
{
if(count>capacity())
reserve(2*count);
for(size_t i=size(); i!=count; ++i)
alloc.construct(first_free++, s);
}
else if(count<size())
{
while(first_free!=elements+count)
alloc.destroy(--first_free);
}
}
<|endoftext|>
|
<commit_before>#include "ex14_23.h"
#include <algorithm> // for_each, equal
void StrVec::push_back(const std::string& s)
{
chk_n_alloc();
alloc.construct(first_free++, s);
}
std::pair<std::string*, std::string*> StrVec::alloc_n_copy(const std::string* b,
const std::string* e)
{
auto data = alloc.allocate(e - b);
return {data, std::uninitialized_copy(b, e, data)};
}
void StrVec::free()
{
if (elements) {
for_each(elements, first_free,
[this](std::string& rhs) { alloc.destroy(&rhs); });
alloc.deallocate(elements, cap - elements);
}
}
void StrVec::range_initialize(const std::string* first, const std::string* last)
{
auto newdata = alloc_n_copy(first, last);
elements = newdata.first;
first_free = cap = newdata.second;
}
StrVec::StrVec(const StrVec& rhs)
{
range_initialize(rhs.begin(), rhs.end());
}
StrVec::StrVec(std::initializer_list<std::string> il)
{
range_initialize(il.begin(), il.end());
}
StrVec::~StrVec()
{
free();
}
StrVec& StrVec::operator=(const StrVec& rhs)
{
auto data = alloc_n_copy(rhs.begin(), rhs.end());
free();
elements = data.first;
first_free = cap = data.second;
return *this;
}
void StrVec::alloc_n_move(size_t new_cap)
{
auto newdata = alloc.allocate(new_cap);
auto dest = newdata;
auto elem = elements;
for (size_t i = 0; i != size(); ++i)
alloc.construct(dest++, std::move(*elem++));
free();
elements = newdata;
first_free = dest;
cap = elements + new_cap;
}
void StrVec::reallocate()
{
auto newcapacity = size() ? 2 * size() : 1;
alloc_n_move(newcapacity);
}
void StrVec::reserve(size_t new_cap)
{
if (new_cap <= capacity()) return;
alloc_n_move(new_cap);
}
void StrVec::resize(size_t count)
{
resize(count, std::string());
}
void StrVec::resize(size_t count, const std::string& s)
{
if (count > size()) {
if (count > capacity()) reserve(count * 2);
for (size_t i = size(); i != count; ++i)
alloc.construct(first_free++, s);
}
else if (count < size()) {
while (first_free != elements + count) alloc.destroy(--first_free);
}
}
StrVec::StrVec(StrVec&& s) NOEXCEPT : elements(s.elements),
first_free(s.first_free),
cap(s.cap)
{
// leave s in a state in which it is safe to run the destructor.
s.elements = s.first_free = s.cap = nullptr;
}
StrVec& StrVec::operator=(StrVec&& rhs) NOEXCEPT
{
if (this != &rhs) {
free();
elements = rhs.elements;
first_free = rhs.first_free;
cap = rhs.cap;
rhs.elements = rhs.first_free = rhs.cap = nullptr;
}
return *this;
}
bool operator==(const StrVec& lhs, const StrVec& rhs)
{
return (lhs.size() == rhs.size() &&
std::equal(lhs.begin(), lhs.end(), rhs.begin()));
}
bool operator!=(const StrVec& lhs, const StrVec& rhs)
{
return !(lhs == rhs);
}
bool operator<(const StrVec& lhs, const StrVec& rhs)
{
return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(),
rhs.end());
}
bool operator>(const StrVec& lhs, const StrVec& rhs)
{
return rhs < lhs;
}
bool operator<=(const StrVec& lhs, const StrVec& rhs)
{
return !(rhs < lhs);
}
bool operator>=(const StrVec& lhs, const StrVec& rhs)
{
return !(lhs < rhs);
}
StrVec& StrVec::operator=(std::initializer_list<std::string> il)
{
*this = StrVec(il);
return *this;
}
<commit_msg>improving 14_23<commit_after>#include "ex14_23.h"
#include <algorithm> // for_each, equal
void StrVec::push_back(const std::string& s)
{
chk_n_alloc();
alloc.construct(first_free++, s);
}
std::pair<std::string*, std::string*> StrVec::alloc_n_copy(const std::string* b,
const std::string* e)
{
auto data = alloc.allocate(e - b);
return {data, std::uninitialized_copy(b, e, data)};
}
void StrVec::free()
{
if (elements) {
for_each(elements, first_free,
[this](std::string& rhs) { alloc.destroy(&rhs); });
alloc.deallocate(elements, cap - elements);
}
}
void StrVec::range_initialize(const std::string* first, const std::string* last)
{
auto newdata = alloc_n_copy(first, last);
elements = newdata.first;
first_free = cap = newdata.second;
}
StrVec::StrVec(const StrVec& rhs)
{
range_initialize(rhs.begin(), rhs.end());
}
StrVec::StrVec(std::initializer_list<std::string> il)
{
range_initialize(il.begin(), il.end());
}
StrVec::~StrVec()
{
free();
}
StrVec& StrVec::operator=(const StrVec& rhs)
{
auto data = alloc_n_copy(rhs.begin(), rhs.end());
free();
elements = data.first;
first_free = cap = data.second;
return *this;
}
void StrVec::alloc_n_move(size_t new_cap)
{
auto newdata = alloc.allocate(new_cap);
auto dest = newdata;
auto elem = elements;
for (size_t i = 0; i != size(); ++i)
alloc.construct(dest++, std::move(*elem++));
free();
elements = newdata;
first_free = dest;
cap = elements + new_cap;
}
void StrVec::reallocate()
{
auto newcapacity = size() ? 2 * size() : 1;
alloc_n_move(newcapacity);
}
void StrVec::reserve(size_t new_cap)
{
if (new_cap <= capacity()) return;
alloc_n_move(new_cap);
}
void StrVec::resize(size_t count)
{
resize(count, std::string());
}
void StrVec::resize(size_t count, const std::string& s)
{
if (count > size()) {
if (count > capacity()) reserve(count * 2);
for (size_t i = size(); i != count; ++i)
alloc.construct(first_free++, s);
}
else if (count < size()) {
while (first_free != elements + count) alloc.destroy(--first_free);
}
}
StrVec::StrVec(StrVec&& s) NOEXCEPT : elements(s.elements),
first_free(s.first_free),
cap(s.cap)
{
// leave s in a state in which it is safe to run the destructor.
s.elements = s.first_free = s.cap = nullptr;
}
StrVec& StrVec::operator=(StrVec&& rhs) NOEXCEPT
{
if (this != &rhs) {
free();
elements = rhs.elements;
first_free = rhs.first_free;
cap = rhs.cap;
rhs.elements = rhs.first_free = rhs.cap = nullptr;
}
return *this;
}
bool operator==(const StrVec& lhs, const StrVec& rhs)
{
return (lhs.size() == rhs.size() &&
std::equal(lhs.begin(), lhs.end(), rhs.begin()));
}
bool operator!=(const StrVec& lhs, const StrVec& rhs)
{
return !(lhs == rhs);
}
bool operator<(const StrVec& lhs, const StrVec& rhs)
{
return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(),
rhs.end());
}
bool operator>(const StrVec& lhs, const StrVec& rhs)
{
return rhs < lhs;
}
bool operator<=(const StrVec& lhs, const StrVec& rhs)
{
return !(rhs < lhs);
}
bool operator>=(const StrVec& lhs, const StrVec& rhs)
{
return !(lhs < rhs);
}
StrVec& StrVec::operator=(std::initializer_list<std::string> il)
{
auto data = alloc_n_copy(il.begin(), il.end());
free();
elements = data.first;
first_free = cap = data.second;
return *this;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: prtqry.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2006-06-19 15:26:42 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SVX_DIALOGS_HRC
#include <dialogs.hrc>
#endif
#ifndef _SVX_PRTQRY_HXX
#include <prtqry.hxx>
#endif
#ifndef _SVX_DIALMGR_HXX
#include <dialmgr.hxx>
#endif
#ifndef _SHL_HXX
#include <tools/shl.hxx>
#endif
/* -----------------------------01.02.00 13:57--------------------------------
---------------------------------------------------------------------------*/
SvxPrtQryBox::SvxPrtQryBox(Window* pParent) :
MessBox(pParent, 0,
String(SVX_RES(RID_SVXSTR_QRY_PRINT_TITLE)),
String(SVX_RES(RID_SVXSTR_QRY_PRINT_MSG)))
{
SetImage( QueryBox::GetStandardImage() );
AddButton(String(SVX_RES(RID_SVXSTR_QRY_PRINT_SELECTION)), RET_OK,
BUTTONDIALOG_DEFBUTTON | BUTTONDIALOG_OKBUTTON | BUTTONDIALOG_FOCUSBUTTON);
AddButton(String(SVX_RES(RID_SVXSTR_QRY_PRINT_ALL)), 2, 0);
AddButton(BUTTON_CANCEL, RET_CANCEL, BUTTONDIALOG_CANCELBUTTON);
SetButtonHelpText( RET_OK, String() );
}
/* -----------------------------01.02.00 13:57--------------------------------
---------------------------------------------------------------------------*/
SvxPrtQryBox::~SvxPrtQryBox()
{
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.3.116); FILE MERGED 2006/09/01 17:46:21 kaib 1.3.116.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: prtqry.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-17 04:35:33 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#ifndef _SVX_DIALOGS_HRC
#include <dialogs.hrc>
#endif
#ifndef _SVX_PRTQRY_HXX
#include <prtqry.hxx>
#endif
#ifndef _SVX_DIALMGR_HXX
#include <dialmgr.hxx>
#endif
#ifndef _SHL_HXX
#include <tools/shl.hxx>
#endif
/* -----------------------------01.02.00 13:57--------------------------------
---------------------------------------------------------------------------*/
SvxPrtQryBox::SvxPrtQryBox(Window* pParent) :
MessBox(pParent, 0,
String(SVX_RES(RID_SVXSTR_QRY_PRINT_TITLE)),
String(SVX_RES(RID_SVXSTR_QRY_PRINT_MSG)))
{
SetImage( QueryBox::GetStandardImage() );
AddButton(String(SVX_RES(RID_SVXSTR_QRY_PRINT_SELECTION)), RET_OK,
BUTTONDIALOG_DEFBUTTON | BUTTONDIALOG_OKBUTTON | BUTTONDIALOG_FOCUSBUTTON);
AddButton(String(SVX_RES(RID_SVXSTR_QRY_PRINT_ALL)), 2, 0);
AddButton(BUTTON_CANCEL, RET_CANCEL, BUTTONDIALOG_CANCELBUTTON);
SetButtonHelpText( RET_OK, String() );
}
/* -----------------------------01.02.00 13:57--------------------------------
---------------------------------------------------------------------------*/
SvxPrtQryBox::~SvxPrtQryBox()
{
}
<|endoftext|>
|
<commit_before>//
// Exponent.cpp
// Calculator
//
// Created by Gavin Scheele on 3/27/14.
// Copyright (c) 2014 Gavin Scheele. All rights reserved.
//
#include "Exponential.h"
Exponential::Exponential(Expression* base, Rational* exponent){
this->type = "exponential";
this->base = base;
this->exponent = exponent;
this->exde = new Integer(exponent->getDenominator());
if (exde->getValue() != 1) {
//if the denominator of the exponent is not 1, make the base a root of the denominator, then setting the denominator equal to 1
Integer* baseAsInteger = (Integer *) base;
base = new nthRoot(exde->getValue(), baseAsInteger->getValue(), 1);
Integer* one = new Integer(1);
exponent->setDenominator(one);
}
this->exnu = new Integer(exponent->getNumerator());
if (canExponentiate()) {
exponentiate();
}
}
Exponential::~Exponential(){
}
bool Exponential::canExponentiate() {
if(base->type == "euler"){
return false;
}else if(base->type == "exponential"){
Exponential* ex = (Exponential *) base;
this->exponent->multiply(ex->getExponent());
Integer* numSum = new Integer (1);
ex->getExponent()->setNumerator(numSum);
return false;
// false is returned because the base itself would have already been exponentiated if it were possible
}else if(base->type == "integer"){
return true;
}else if(base->type == "logarithm"){
return false;
}else if(base->type == "nthRoot"){
nthRoot* nr = (nthRoot *) base;
Rational* r = new Rational(this->exponent->getNumerator(), nr->getRoot()*this->exponent->getDenominator());
//makes a new exponent, multiplying the denominator by the root, allowing the root to be simplified to one
this->exponent = r;
nr->setRoot(1);
return false;
}else if(base->type == "pi"){
return false;
}else if(base->type == "rational"){
Rational* r = (Rational *) base;
if (r->geteNumerator()->type == "integer" && r->geteDenominator()->type == "integer") {
Exponential* nu = new Exponential(r->geteNumerator(), this->exponent);
r->setNumerator(nu);
Exponential* de = new Exponential(r->geteDenominator(), this->exponent);
r->setDenominator(de);
}
}else{
cout << "type not recognized" << endl;
}
return false;
}
void Exponential::exponentiate(){
if (this->base->type = "rational") {
Rational* ratBase = (Rational *) this->base;
ratBase->getNumerator()->exponeniate();
ratBase->getDenominator()->exponentiate();
}
else {
if (this->exponent->getNumerator()==0) {
Integer* oneInt = new Integer(1);
Rational* oneRat = new Rational(1, 1);
this->exponent=oneRat;
this->base=oneInt;
}
bool toFlip = false;
if (exnu->getValue()<0) {
exnu->setValue(exnu->getValue()*-1);
toFlip = true;
//handles negative exponents
}
Expression* constantBase = 0;
if (base->type == "integer") { //fixed the problem for integers but nothing else
Integer *a = (Integer *)base;
constantBase = new Integer(a->getValue());
}
while (exponent->getNumerator()>1)
{
base->multiply(constantBase);
Integer* one = new Integer(1);
exponent->setNumerator(exponent->geteNumerator()->subtract(one));
}
if (toFlip) {
Integer* one = new Integer(1);
Rational* mouse = new Rational(one, base);
base = mouse;
}
}
}
Expression* Exponential::add(Expression* a){
if(a->type == "euler"){
}else if(a->type == "exponential"){
Exponential* ex = (Exponential *) a;
if (ex->getBase()==this->base) {
if (ex->getExponent()==this->exponent) {
Integer* two = new Integer(2);
this->multiply(two);
}
}
}else if(a->type == "integer"){
}else if(a->type == "logarithm"){
}else if(a->type == "nthRoot"){
}else if(a->type == "pi"){
}else if(a->type == "rational"){
}else{
cout << "type not recognized" << endl;
}
return this;
}
Expression* Exponential::subtract(Expression* a){
if(a->type == "euler"){
}else if(a->type == "exponential"){
Exponential* ex = (Exponential *) a;
if (ex->getBase()==this->base) {
if (ex->getExponent()==this->exponent) {
Integer* zero = new Integer(0);
this->multiply(zero);
}
}
}else if(a->type == "integer"){
}else if(a->type == "logarithm"){
}else if(a->type == "nthRoot"){
}else if(a->type == "pi"){
}else if(a->type == "rational"){
}else{
cout << "type not recognized" << endl;
}
return this;
}
Expression* Exponential::multiply(Expression* a){
if(a->type == "euler"){
if (this->base->type == "euler") {
Rational* oneRat = new Rational(1, 1);
this->exponent->add(oneRat);
}
}else if(a->type == "exponential"){
Exponential* ex = (Exponential *) a;
if (this->base == ex->getBase()) {
this->exponent->add(ex->getExponent());
}
}else if(a->type == "integer"){
}else if(a->type == "logarithm"){
}else if(a->type == "nthRoot"){
}else if(a->type == "pi"){
if (this->base->type == "pi") {
Rational* oneRat = new Rational(1, 1);
this->exponent->add(oneRat);
}
}else if(a->type == "rational"){
Rational* r = (Rational *) a;
r->setNumerator(r->geteNumerator()->multiply(this)); //Error: expected expression
return r;
}else{
cout << "type not recognized" << endl;
}
return this;
}
Expression* Exponential::divide(Expression* a){
if(a->type == "euler"){
if (this->base->type == "euler") {
Rational* oneRat = new Rational(1, 1);
this->exponent->subtract(oneRat);
}
}else if(a->type == "exponential"){
Exponential* ex = (Exponential *) a;
if (this->base == ex->getBase()) {
this->exponent->subtract(ex->getExponent());
}
}else if(a->type == "integer"){
}else if(a->type == "logarithm"){
}else if(a->type == "nthRoot"){
}else if(a->type == "pi"){
if (this->base->type == "pi") {
Rational* oneRat = new Rational(1, 1);
this->exponent->subtract(oneRat);
}
}else if(a->type == "rational"){
Rational* r = (Rational *) a;
r->setDenominator(r->geteDenominator()->multiply(this)); //Error: member reference type 'int' is not a pointer
return r;
}else{
cout << "type not recognized" << endl;
}
return this;
}
Rational* Exponential::getExponent() {
return exponent;
}
Expression* Exponential::getBase() {
return base;
}
Integer* Exponential::getExnu() {
return exnu;
}
Integer* Exponential::getExde() {
return exde;
}
void Exponential::setExnu(Integer* n) {
exnu = n;
}
void Exponential::setExde(Integer* n) {
exde = n;
}
void Exponential::setExponent(Rational* e) {
exponent = e;
}
void Exponential::setBase(Expression* e) {
base = e;
}
string Exponential::toString() {
stringstream str;
if(exponent->getNumerator() == 1 && exponent->getDenominator() == 1){
str << *base;
}
else if(exponent->getDenominator() == 1){
str << *base << "^" << *exponent->geteNumerator();
}else{
str << *base << "^" << *exponent;
}
return str.str();
}
ostream& Exponential::print(std::ostream& output) const{
Exponential *a = (Exponential *)this;
output << a->toString();
return output;
}
bool Exponential::canAdd(Expression* b){ //use "this" as comparison. Solver will call someExpression.canAdd(&someOtherExpression)
if (this->type == b->type && this->type != "logarithm") {
if (this->type == "nthRoot") {
}
return true;
}else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){
return true;
}else if(this->type == "multiple" && b->type == "multiple"){
MultipleExpressions *t = (MultipleExpressions *)this;
MultipleExpressions *m = (MultipleExpressions *)b;
if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) {
return true;
}
}else if(this->type == "multiple" || b->type == "multiple") return true;
return false;
}
bool Exponential::canSubtract(Expression* b){
if (this->type == b->type) {
return true;
}else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){
return true;
}else if(this->type == "multiple" && b->type == "multiple"){
MultipleExpressions *t = (MultipleExpressions *)this;
MultipleExpressions *m = (MultipleExpressions *)b;
if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) {
return true;
}
}else if(this->type == "multiple" || b->type == "multiple") return true;
return false;
}
bool Exponential::canMultiply(Expression* b){
if (this->type == b->type) {
return true;
}
else if(this->type == "integer" && b->type == "rational") return true;
else if(this->type == "rational" && b->type == "integer") return true;
else if(this->type == "multiple" && b->type == "multiple"){
MultipleExpressions *t = (MultipleExpressions *)this;
MultipleExpressions *m = (MultipleExpressions *)b;
if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) {
return true;
}
}else if(this->type == "multiple" || b->type == "multiple") return true;
return false;
}
bool Exponential::canDivide(Expression* b){
if (this->type == b->type) {
return true;
}
else if(this->type == "integer"){
if( b->type == "rational") return true;
}
else if(this->type == "rational" && b->type == "integer") return true;
else if(this->type == "multiple" && b->type == "multiple"){
MultipleExpressions *t = (MultipleExpressions *)this;
MultipleExpressions *m = (MultipleExpressions *)b;
if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) {
return true;
}
}else if(this->type == "multiple" || b->type == "multiple") return true;
return false;
}
<commit_msg>Fixed errors<commit_after>//
// Exponent.cpp
// Calculator
//
// Created by Gavin Scheele on 3/27/14.
// Copyright (c) 2014 Gavin Scheele. All rights reserved.
//
#include "Exponential.h"
Exponential::Exponential(Expression* base, Rational* exponent){
this->type = "exponential";
this->base = base;
this->exponent = exponent;
this->exde = new Integer(exponent->getDenominator());
if (exde->getValue() != 1) {
//if the denominator of the exponent is not 1, make the base a root of the denominator, then setting the denominator equal to 1
Integer* baseAsInteger = (Integer *) base;
base = new nthRoot(exde->getValue(), baseAsInteger->getValue(), 1);
Integer* one = new Integer(1);
exponent->setDenominator(one);
}
this->exnu = new Integer(exponent->getNumerator());
if (canExponentiate()) {
exponentiate();
}
}
Exponential::~Exponential(){
}
bool Exponential::canExponentiate() {
if(base->type == "euler"){
return false;
}else if(base->type == "exponential"){
Exponential* ex = (Exponential *) base;
this->exponent->multiply(ex->getExponent());
Integer* numSum = new Integer (1);
ex->getExponent()->setNumerator(numSum);
return false;
// false is returned because the base itself would have already been exponentiated if it were possible
}else if(base->type == "integer"){
return true;
}else if(base->type == "logarithm"){
return false;
}else if(base->type == "nthRoot"){
nthRoot* nr = (nthRoot *) base;
Rational* r = new Rational(this->exponent->getNumerator(), nr->getRoot()*this->exponent->getDenominator());
//makes a new exponent, multiplying the denominator by the root, allowing the root to be simplified to one
this->exponent = r;
nr->setRoot(1);
return false;
}else if(base->type == "pi"){
return false;
}else if(base->type == "rational"){
Rational* r = (Rational *) base;
if (r->geteNumerator()->type == "integer" && r->geteDenominator()->type == "integer") {
Exponential* nu = new Exponential(r->geteNumerator(), this->exponent);
r->setNumerator(nu);
Exponential* de = new Exponential(r->geteDenominator(), this->exponent);
r->setDenominator(de);
}
}else{
cout << "type not recognized" << endl;
}
return false;
}
void Exponential::exponentiate(){
Integer* one = new Integer(1);
Rational* oneRat = new Rational(1, 1);
if (this->base->type = "rational") {
Rational* ratBase = (Rational *) this->base;
Exponential* numAsExponential = new Exponential (ratBase->getNumerator(), this->exponent);
Exponential* denAsExponential = new Exponential (ratBase->getDenominator(), this->exponent);
this->exponent = oneRat;
}
else {
if (this->exponent->getNumerator()==0) {
this->exponent=oneRat;
this->base=one;
}
bool toFlip = false;
if (exnu->getValue()<0) {
exnu->setValue(exnu->getValue()*-1);
toFlip = true;
//handles negative exponents
}
Expression* constantBase = 0;
if (base->type == "integer") { //fixed the problem for integers but nothing else
Integer *a = (Integer *)base;
constantBase = new Integer(a->getValue());
}
while (exponent->getNumerator()>1)
{
base->multiply(constantBase);
exponent->setNumerator(exponent->geteNumerator()->subtract(one));
}
if (toFlip) {
Integer* one = new Integer(1);
Rational* mouse = new Rational(one, base);
base = mouse;
}
}
}
Expression* Exponential::add(Expression* a){
if(a->type == "euler"){
}else if(a->type == "exponential"){
Exponential* ex = (Exponential *) a;
if (ex->getBase()==this->base) {
if (ex->getExponent()==this->exponent) {
Integer* two = new Integer(2);
this->multiply(two);
}
}
}else if(a->type == "integer"){
}else if(a->type == "logarithm"){
}else if(a->type == "nthRoot"){
}else if(a->type == "pi"){
}else if(a->type == "rational"){
}else{
cout << "type not recognized" << endl;
}
return this;
}
Expression* Exponential::subtract(Expression* a){
if(a->type == "euler"){
}else if(a->type == "exponential"){
Exponential* ex = (Exponential *) a;
if (ex->getBase()==this->base) {
if (ex->getExponent()==this->exponent) {
Integer* zero = new Integer(0);
this->multiply(zero);
}
}
}else if(a->type == "integer"){
}else if(a->type == "logarithm"){
}else if(a->type == "nthRoot"){
}else if(a->type == "pi"){
}else if(a->type == "rational"){
}else{
cout << "type not recognized" << endl;
}
return this;
}
Expression* Exponential::multiply(Expression* a){
if(a->type == "euler"){
if (this->base->type == "euler") {
Rational* oneRat = new Rational(1, 1);
this->exponent->add(oneRat);
}
}else if(a->type == "exponential"){
Exponential* ex = (Exponential *) a;
if (this->base == ex->getBase()) {
this->exponent->add(ex->getExponent());
}
}else if(a->type == "integer"){
}else if(a->type == "logarithm"){
}else if(a->type == "nthRoot"){
}else if(a->type == "pi"){
if (this->base->type == "pi") {
Rational* oneRat = new Rational(1, 1);
this->exponent->add(oneRat);
}
}else if(a->type == "rational"){
Rational* r = (Rational *) a;
r->setNumerator(r->geteNumerator()->multiply(this)); //Error: expected expression
return r;
}else{
cout << "type not recognized" << endl;
}
return this;
}
Expression* Exponential::divide(Expression* a){
if(a->type == "euler"){
if (this->base->type == "euler") {
Rational* oneRat = new Rational(1, 1);
this->exponent->subtract(oneRat);
}
}else if(a->type == "exponential"){
Exponential* ex = (Exponential *) a;
if (this->base == ex->getBase()) {
this->exponent->subtract(ex->getExponent());
}
}else if(a->type == "integer"){
}else if(a->type == "logarithm"){
}else if(a->type == "nthRoot"){
}else if(a->type == "pi"){
if (this->base->type == "pi") {
Rational* oneRat = new Rational(1, 1);
this->exponent->subtract(oneRat);
}
}else if(a->type == "rational"){
Rational* r = (Rational *) a;
r->setDenominator(r->geteDenominator()->multiply(this)); //Error: member reference type 'int' is not a pointer
return r;
}else{
cout << "type not recognized" << endl;
}
return this;
}
Rational* Exponential::getExponent() {
return exponent;
}
Expression* Exponential::getBase() {
return base;
}
Integer* Exponential::getExnu() {
return exnu;
}
Integer* Exponential::getExde() {
return exde;
}
void Exponential::setExnu(Integer* n) {
exnu = n;
}
void Exponential::setExde(Integer* n) {
exde = n;
}
void Exponential::setExponent(Rational* e) {
exponent = e;
}
void Exponential::setBase(Expression* e) {
base = e;
}
string Exponential::toString() {
stringstream str;
if(exponent->getNumerator() == 1 && exponent->getDenominator() == 1){
str << *base;
}
else if(exponent->getDenominator() == 1){
str << *base << "^" << *exponent->geteNumerator();
}else{
str << *base << "^" << *exponent;
}
return str.str();
}
ostream& Exponential::print(std::ostream& output) const{
Exponential *a = (Exponential *)this;
output << a->toString();
return output;
}
bool Exponential::canAdd(Expression* b){ //use "this" as comparison. Solver will call someExpression.canAdd(&someOtherExpression)
if (this->type == b->type && this->type != "logarithm") {
if (this->type == "nthRoot") {
}
return true;
}else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){
return true;
}else if(this->type == "multiple" && b->type == "multiple"){
MultipleExpressions *t = (MultipleExpressions *)this;
MultipleExpressions *m = (MultipleExpressions *)b;
if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) {
return true;
}
}else if(this->type == "multiple" || b->type == "multiple") return true;
return false;
}
bool Exponential::canSubtract(Expression* b){
if (this->type == b->type) {
return true;
}else if((this->type == "integer" && b->type == "rational") || (this->type == "rational" && b->type == "integer")){
return true;
}else if(this->type == "multiple" && b->type == "multiple"){
MultipleExpressions *t = (MultipleExpressions *)this;
MultipleExpressions *m = (MultipleExpressions *)b;
if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) {
return true;
}
}else if(this->type == "multiple" || b->type == "multiple") return true;
return false;
}
bool Exponential::canMultiply(Expression* b){
if (this->type == b->type) {
return true;
}
else if(this->type == "integer" && b->type == "rational") return true;
else if(this->type == "rational" && b->type == "integer") return true;
else if(this->type == "multiple" && b->type == "multiple"){
MultipleExpressions *t = (MultipleExpressions *)this;
MultipleExpressions *m = (MultipleExpressions *)b;
if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) {
return true;
}
}else if(this->type == "multiple" || b->type == "multiple") return true;
return false;
}
bool Exponential::canDivide(Expression* b){
if (this->type == b->type) {
return true;
}
else if(this->type == "integer"){
if( b->type == "rational") return true;
}
else if(this->type == "rational" && b->type == "integer") return true;
else if(this->type == "multiple" && b->type == "multiple"){
MultipleExpressions *t = (MultipleExpressions *)this;
MultipleExpressions *m = (MultipleExpressions *)b;
if ((t->meType == "as" && m->meType == "as") || (t->meType == "md" && m->meType == "md")) {
return true;
}
}else if(this->type == "multiple" || b->type == "multiple") return true;
return false;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: frmpage.hxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: os $ $Date: 2002-09-25 11:36:19 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _FRMPAGE_HXX
#define _FRMPAGE_HXX
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif
#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif
#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#ifndef _BMPWIN_HXX
#include <bmpwin.hxx>
#endif
#ifndef _FRMEX_HXX
#include <frmex.hxx>
#endif
#ifndef _PRCNTFLD_HXX
#include <prcntfld.hxx>
#endif
namespace sfx2{class FileDialogHelper;}
class SwWrtShell;
struct FrmMap;
/*--------------------------------------------------------------------
Beschreibung: Rahmendialog
--------------------------------------------------------------------*/
class SwFrmPage: public SfxTabPage
{
// Size
FixedText aWidthFT;
PercentField aWidthED;
CheckBox aRelWidthCB;
FixedText aHeightFT;
PercentField aHeightED;
CheckBox aRelHeightCB;
CheckBox aFixedRatioCB;
CheckBox aAutoHeightCB;
PushButton aRealSizeBT;
FixedLine aSizeFL;
BOOL bWidthLastChanged;
// Anker
FixedLine aTypeFL;
FixedLine aTypeSepFL;
RadioButton aAnchorAtPageRB;
RadioButton aAnchorAtParaRB;
RadioButton aAnchorAtCharRB;
RadioButton aAnchorAsCharRB;
RadioButton aAnchorAtFrameRB;
// Position
FixedText aHorizontalFT;
ListBox aHorizontalDLB;
FixedText aAtHorzPosFT;
MetricField aAtHorzPosED;
FixedText aHoriRelationFT;
ListBox aHoriRelationLB;
CheckBox aMirrorPagesCB;
FixedText aVerticalFT;
ListBox aVerticalDLB;
FixedText aAtVertPosFT;
MetricField aAtVertPosED;
FixedText aVertRelationFT;
ListBox aVertRelationLB;
FixedLine aPositionFL;
BOOL bAtHorzPosModified;
BOOL bAtVertPosModified;
// Example
SwFrmPagePreview aExampleWN;
BOOL bFormat;
BOOL bNew;
BOOL bHtmlMode;
BOOL bNoModifyHdl;
BOOL bVerticalChanged; //check done whether frame is in vertical environment
BOOL bIsVerticalFrame; //current frame is in vertical environment - strings are exchanged
BOOL bIsInRightToLeft; // current frame is in right-to-left environment - strings are exchanged
USHORT nHtmlMode;
USHORT nDlgType;
Size aGrfSize;
Size aWrap;
SwTwips nUpperBorder;
SwTwips nLowerBorder;
double fWidthHeightRatio; //width-to-height ratio to support the KeepRatio button
// Die alten Ausrichtungen
USHORT nOldH;
USHORT nOldHRel;
USHORT nOldV;
USHORT nOldVRel;
virtual void ActivatePage(const SfxItemSet& rSet);
virtual int DeactivatePage(SfxItemSet *pSet);
DECL_LINK( RangeModifyHdl, Edit * );
DECL_LINK( AnchorTypeHdl, RadioButton * );
DECL_LINK( PosHdl, ListBox * );
DECL_LINK( RelHdl, ListBox * );
void InitPos(USHORT nId, USHORT nH, USHORT nHRel,
USHORT nV, USHORT nVRel,
long nX, long nY);
DECL_LINK( EditModifyHdl, Edit * );
DECL_LINK( RealSizeHdl, Button * );
DECL_LINK( RelSizeClickHdl, CheckBox * );
DECL_LINK( MirrorHdl, CheckBox * );
DECL_LINK( ManualHdl, Button * );
// Beispiel aktualisieren
void UpdateExample();
DECL_LINK( ModifyHdl, Edit * );
void Init(const SfxItemSet& rSet, BOOL bReset = FALSE);
USHORT FillPosLB(FrmMap *pMap, USHORT nAlign, ListBox &rLB);
ULONG FillRelLB(FrmMap *pMap, USHORT nLBSelPos, USHORT nAlign, USHORT nRel, ListBox &rLB, FixedText &rFT);
USHORT GetMapPos(FrmMap *pMap, ListBox &rAlignLB);
USHORT GetAlignment(FrmMap *pMap, USHORT nMapPos, ListBox &rAlignLB, ListBox &rRelationLB);
USHORT GetRelation(FrmMap *pMap, ListBox &rRelationLB);
USHORT GetAnchor();
SwFrmPage(Window *pParent, const SfxItemSet &rSet);
~SwFrmPage();
public:
static SfxTabPage *Create(Window *pParent, const SfxItemSet &rSet);
static USHORT* GetRanges();
virtual BOOL FillItemSet(SfxItemSet &rSet);
virtual void Reset(const SfxItemSet &rSet);
void SetNewFrame(BOOL bNewFrame) { bNew = bNewFrame; }
void SetFormatUsed(BOOL bFmt);
void SetFrmType(USHORT nType) { nDlgType = nType; }
};
class SwGrfExtPage: public SfxTabPage
{
// Spiegeln
FixedLine aMirrorFL;
CheckBox aMirrorVertBox;
CheckBox aMirrorHorzBox;
RadioButton aAllPagesRB;
RadioButton aLeftPagesRB;
RadioButton aRightPagesRB;
BmpWindow aBmpWin;
FixedLine aConnectFL;
FixedText aConnectFT;
Edit aConnectED;
PushButton aBrowseBT;
String aFilterName;
String aGrfName, aNewGrfName;
::sfx2::FileDialogHelper* pGrfDlg;
BOOL bHtmlMode;
// Handler fuer Spiegeln
DECL_LINK( MirrorHdl, CheckBox * );
DECL_LINK( BrowseHdl, Button * );
virtual void ActivatePage(const SfxItemSet& rSet);
SwGrfExtPage(Window *pParent, const SfxItemSet &rSet);
~SwGrfExtPage();
public:
static SfxTabPage *Create(Window *pParent, const SfxItemSet &rSet);
virtual BOOL FillItemSet(SfxItemSet &rSet);
virtual void Reset(const SfxItemSet &rSet);
virtual int DeactivatePage(SfxItemSet *pSet);
};
class SwFrmURLPage : public SfxTabPage
{
//Hyperlink
FixedLine aHyperLinkFL;
FixedText aURLFT;
Edit aURLED;
PushButton aSearchPB;
FixedText aNameFT;
Edit aNameED;
FixedText aFrameFT;
ComboBox aFrameCB;
//Image map
FixedLine aImageFL;
CheckBox aServerCB;
CheckBox aClientCB;
DECL_LINK( InsertFileHdl, PushButton * );
SwFrmURLPage(Window *pParent, const SfxItemSet &rSet);
~SwFrmURLPage();
public:
static SfxTabPage *Create(Window *pParent, const SfxItemSet &rSet);
virtual BOOL FillItemSet(SfxItemSet &rSet);
virtual void Reset(const SfxItemSet &rSet);
};
/*-----------------13.11.96 12.59-------------------
--------------------------------------------------*/
class SwFrmAddPage : public SfxTabPage
{
FixedText aNameFT;
Edit aNameED;
FixedText aAltNameFT;
Edit aAltNameED;
FixedText aPrevFT;
ListBox aPrevLB;
FixedText aNextFT;
ListBox aNextLB;
FixedLine aNamesFL;
CheckBox aProtectContentCB;
CheckBox aProtectFrameCB;
CheckBox aProtectSizeCB;
FixedLine aProtectFL;
CheckBox aEditInReadonlyCB;
CheckBox aPrintFrameCB;
FixedText aTextFlowFT;
ListBox aTextFlowLB;
FixedLine aExtFL;
SwWrtShell* pWrtSh;
USHORT nDlgType;
BOOL bHtmlMode;
BOOL bFormat;
BOOL bNew;
DECL_LINK(EditModifyHdl, Edit*);
DECL_LINK(ChainModifyHdl, ListBox*);
SwFrmAddPage(Window *pParent, const SfxItemSet &rSet);
~SwFrmAddPage();
public:
static SfxTabPage* Create(Window *pParent, const SfxItemSet &rSet);
static USHORT* GetRanges();
virtual BOOL FillItemSet(SfxItemSet &rSet);
virtual void Reset(const SfxItemSet &rSet);
void SetFormatUsed(BOOL bFmt);
void SetFrmType(USHORT nType) { nDlgType = nType; }
void SetNewFrame(BOOL bNewFrame) { bNew = bNewFrame; }
void SetShell(SwWrtShell* pSh) { pWrtSh = pSh; }
};
#endif // _FRMPAGE_HXX
<commit_msg>INTEGRATION: CWS swobjpos02 (1.12.312); FILE MERGED 2003/10/02 11:12:41 od 1.12.312.1: #i18732# class <SwFrmPage> - new checkbox for option 'FollowTextFlow'<commit_after>/*************************************************************************
*
* $RCSfile: frmpage.hxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: hr $ $Date: 2004-02-02 18:42:05 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _FRMPAGE_HXX
#define _FRMPAGE_HXX
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif
#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif
#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#ifndef _BMPWIN_HXX
#include <bmpwin.hxx>
#endif
#ifndef _FRMEX_HXX
#include <frmex.hxx>
#endif
#ifndef _PRCNTFLD_HXX
#include <prcntfld.hxx>
#endif
namespace sfx2{class FileDialogHelper;}
class SwWrtShell;
struct FrmMap;
/*--------------------------------------------------------------------
Beschreibung: Rahmendialog
--------------------------------------------------------------------*/
class SwFrmPage: public SfxTabPage
{
// Size
FixedText aWidthFT;
PercentField aWidthED;
CheckBox aRelWidthCB;
FixedText aHeightFT;
PercentField aHeightED;
CheckBox aRelHeightCB;
CheckBox aFixedRatioCB;
CheckBox aAutoHeightCB;
PushButton aRealSizeBT;
FixedLine aSizeFL;
BOOL bWidthLastChanged;
// Anker
FixedLine aTypeFL;
FixedLine aTypeSepFL;
RadioButton aAnchorAtPageRB;
RadioButton aAnchorAtParaRB;
RadioButton aAnchorAtCharRB;
RadioButton aAnchorAsCharRB;
RadioButton aAnchorAtFrameRB;
// Position
FixedText aHorizontalFT;
ListBox aHorizontalDLB;
FixedText aAtHorzPosFT;
MetricField aAtHorzPosED;
FixedText aHoriRelationFT;
ListBox aHoriRelationLB;
CheckBox aMirrorPagesCB;
FixedText aVerticalFT;
ListBox aVerticalDLB;
FixedText aAtVertPosFT;
MetricField aAtVertPosED;
FixedText aVertRelationFT;
ListBox aVertRelationLB;
// OD 02.10.2003 #i18732# - check box for new option 'FollowTextFlow'
CheckBox aFollowTextFlowCB;
FixedLine aPositionFL;
BOOL bAtHorzPosModified;
BOOL bAtVertPosModified;
// Example
SwFrmPagePreview aExampleWN;
BOOL bFormat;
BOOL bNew;
BOOL bHtmlMode;
BOOL bNoModifyHdl;
BOOL bVerticalChanged; //check done whether frame is in vertical environment
BOOL bIsVerticalFrame; //current frame is in vertical environment - strings are exchanged
BOOL bIsInRightToLeft; // current frame is in right-to-left environment - strings are exchanged
USHORT nHtmlMode;
USHORT nDlgType;
Size aGrfSize;
Size aWrap;
SwTwips nUpperBorder;
SwTwips nLowerBorder;
double fWidthHeightRatio; //width-to-height ratio to support the KeepRatio button
// Die alten Ausrichtungen
USHORT nOldH;
USHORT nOldHRel;
USHORT nOldV;
USHORT nOldVRel;
virtual void ActivatePage(const SfxItemSet& rSet);
virtual int DeactivatePage(SfxItemSet *pSet);
DECL_LINK( RangeModifyHdl, Edit * );
DECL_LINK( AnchorTypeHdl, RadioButton * );
DECL_LINK( PosHdl, ListBox * );
DECL_LINK( RelHdl, ListBox * );
void InitPos(USHORT nId, USHORT nH, USHORT nHRel,
USHORT nV, USHORT nVRel,
long nX, long nY);
DECL_LINK( EditModifyHdl, Edit * );
DECL_LINK( RealSizeHdl, Button * );
DECL_LINK( RelSizeClickHdl, CheckBox * );
DECL_LINK( MirrorHdl, CheckBox * );
DECL_LINK( ManualHdl, Button * );
// Beispiel aktualisieren
void UpdateExample();
DECL_LINK( ModifyHdl, Edit * );
void Init(const SfxItemSet& rSet, BOOL bReset = FALSE);
USHORT FillPosLB(FrmMap *pMap, USHORT nAlign, ListBox &rLB);
ULONG FillRelLB(FrmMap *pMap, USHORT nLBSelPos, USHORT nAlign, USHORT nRel, ListBox &rLB, FixedText &rFT);
USHORT GetMapPos(FrmMap *pMap, ListBox &rAlignLB);
USHORT GetAlignment(FrmMap *pMap, USHORT nMapPos, ListBox &rAlignLB, ListBox &rRelationLB);
USHORT GetRelation(FrmMap *pMap, ListBox &rRelationLB);
USHORT GetAnchor();
SwFrmPage(Window *pParent, const SfxItemSet &rSet);
~SwFrmPage();
public:
static SfxTabPage *Create(Window *pParent, const SfxItemSet &rSet);
static USHORT* GetRanges();
virtual BOOL FillItemSet(SfxItemSet &rSet);
virtual void Reset(const SfxItemSet &rSet);
void SetNewFrame(BOOL bNewFrame) { bNew = bNewFrame; }
void SetFormatUsed(BOOL bFmt);
void SetFrmType(USHORT nType) { nDlgType = nType; }
};
class SwGrfExtPage: public SfxTabPage
{
// Spiegeln
FixedLine aMirrorFL;
CheckBox aMirrorVertBox;
CheckBox aMirrorHorzBox;
RadioButton aAllPagesRB;
RadioButton aLeftPagesRB;
RadioButton aRightPagesRB;
BmpWindow aBmpWin;
FixedLine aConnectFL;
FixedText aConnectFT;
Edit aConnectED;
PushButton aBrowseBT;
String aFilterName;
String aGrfName, aNewGrfName;
::sfx2::FileDialogHelper* pGrfDlg;
BOOL bHtmlMode;
// Handler fuer Spiegeln
DECL_LINK( MirrorHdl, CheckBox * );
DECL_LINK( BrowseHdl, Button * );
virtual void ActivatePage(const SfxItemSet& rSet);
SwGrfExtPage(Window *pParent, const SfxItemSet &rSet);
~SwGrfExtPage();
public:
static SfxTabPage *Create(Window *pParent, const SfxItemSet &rSet);
virtual BOOL FillItemSet(SfxItemSet &rSet);
virtual void Reset(const SfxItemSet &rSet);
virtual int DeactivatePage(SfxItemSet *pSet);
};
class SwFrmURLPage : public SfxTabPage
{
//Hyperlink
FixedLine aHyperLinkFL;
FixedText aURLFT;
Edit aURLED;
PushButton aSearchPB;
FixedText aNameFT;
Edit aNameED;
FixedText aFrameFT;
ComboBox aFrameCB;
//Image map
FixedLine aImageFL;
CheckBox aServerCB;
CheckBox aClientCB;
DECL_LINK( InsertFileHdl, PushButton * );
SwFrmURLPage(Window *pParent, const SfxItemSet &rSet);
~SwFrmURLPage();
public:
static SfxTabPage *Create(Window *pParent, const SfxItemSet &rSet);
virtual BOOL FillItemSet(SfxItemSet &rSet);
virtual void Reset(const SfxItemSet &rSet);
};
/*-----------------13.11.96 12.59-------------------
--------------------------------------------------*/
class SwFrmAddPage : public SfxTabPage
{
FixedText aNameFT;
Edit aNameED;
FixedText aAltNameFT;
Edit aAltNameED;
FixedText aPrevFT;
ListBox aPrevLB;
FixedText aNextFT;
ListBox aNextLB;
FixedLine aNamesFL;
CheckBox aProtectContentCB;
CheckBox aProtectFrameCB;
CheckBox aProtectSizeCB;
FixedLine aProtectFL;
CheckBox aEditInReadonlyCB;
CheckBox aPrintFrameCB;
FixedText aTextFlowFT;
ListBox aTextFlowLB;
FixedLine aExtFL;
SwWrtShell* pWrtSh;
USHORT nDlgType;
BOOL bHtmlMode;
BOOL bFormat;
BOOL bNew;
DECL_LINK(EditModifyHdl, Edit*);
DECL_LINK(ChainModifyHdl, ListBox*);
SwFrmAddPage(Window *pParent, const SfxItemSet &rSet);
~SwFrmAddPage();
public:
static SfxTabPage* Create(Window *pParent, const SfxItemSet &rSet);
static USHORT* GetRanges();
virtual BOOL FillItemSet(SfxItemSet &rSet);
virtual void Reset(const SfxItemSet &rSet);
void SetFormatUsed(BOOL bFmt);
void SetFrmType(USHORT nType) { nDlgType = nType; }
void SetNewFrame(BOOL bNewFrame) { bNew = bNewFrame; }
void SetShell(SwWrtShell* pSh) { pWrtSh = pSh; }
};
#endif // _FRMPAGE_HXX
<|endoftext|>
|
<commit_before>#ifndef GENERIC_STRING_HPP
# define GENERIC_STRING_HPP
# pragma once
#include <cstring>
#include <algorithm>
#include <sstream>
#include <string>
#include <vector>
namespace generic
{
// cstrlen
//////////////////////////////////////////////////////////////////////////////
template <::std::size_t N>
inline constexpr ::std::size_t cstrlen(char const (&)[N]) noexcept
{
return N - 1;
}
//////////////////////////////////////////////////////////////////////////////
inline constexpr ::std::size_t cstrlen(char const* const p) noexcept
{
return *p ? 1 + cstrlen(p + 1) : 0;
}
// join
//////////////////////////////////////////////////////////////////////////////
template <typename C>
inline typename C::value_type join(C const& container,
typename C::value_type const sep) noexcept
{
if (container.size())
{
typename C::value_type r(container.front());
auto const end(container.end());
for (typename C::const_iterator i(container.begin() + 1); i != end; ++i)
{
r += sep + *i;
}
return r;
}
else
{
return typename C::value_type();
}
}
//////////////////////////////////////////////////////////////////////////////
template <typename C>
inline typename C::value_type join(C const& container,
typename C::value_type::value_type const sep) noexcept
{
if (container.size())
{
typename C::value_type r(container.front());
auto const end(container.end());
for (typename C::const_iterator i(container.begin() + 1); i != end; ++i)
{
r += sep + *i;
}
return r;
}
else
{
return typename C::value_type();
}
}
// split
//////////////////////////////////////////////////////////////////////////////
template<class CharT, class Traits, class Allocator>
inline ::std::vector<::std::basic_string<CharT, Traits, Allocator> >
split(::std::basic_string<CharT, Traits, Allocator> const& s,
CharT const delim) noexcept
{
::std::stringstream ss(s);
::std::string item;
::std::vector<typename ::std::decay<decltype(s)>::type> r;
while (::std::getline(ss, item, delim))
{
r.push_back(item);
}
return r;
}
//////////////////////////////////////////////////////////////////////////////
inline ::std::vector<::std::string>
split(::std::string const& s,
char const* const delims = "\f\n\r\t\v") noexcept
{
::std::vector<typename ::std::decay<decltype(s)>::type> r;
auto const S(s.size());
decltype(s.size()) i{};
while (i < S)
{
while ((i < S) && ::std::strchr(delims, s[i]))
{
++i;
}
if (i == S)
{
break;
}
// else do nothing
auto j(i + 1);
while ((j < S) && !::std::strchr(delims, s[j]))
{
++j;
}
r.push_back(s.substr(i, j - i));
i = j + 1;
}
return r;
}
// trim
//////////////////////////////////////////////////////////////////////////////
template<class CharT, class Traits, class Allocator>
inline ::std::basic_string<CharT, Traits, Allocator>&
ltrim(::std::basic_string<CharT, Traits, Allocator>& s,
CharT const* cs = " ") noexcept
{
s.erase(s.begin(),
::std::find_if(s.begin(), s.end(),
[cs](char const c) noexcept {
return !::std::strrchr(cs, c);
}
)
);
return s;
}
template<class CharT, class Traits, class Allocator>
inline ::std::basic_string<CharT, Traits, Allocator>&
rtrim(::std::basic_string<CharT, Traits, Allocator>& s,
CharT const* cs = " ") noexcept
{
s.erase(::std::find_if(s.rbegin(), s.rend(),
[cs](char const c) noexcept {
return !::std::strrchr(cs, c);
}
).base(),
s.end()
);
return s;
}
template<class CharT, class Traits, class Allocator>
inline ::std::basic_string<CharT, Traits, Allocator>&
trim(::std::basic_string<CharT, Traits, Allocator>& s,
CharT const* cs = " ") noexcept
{
return ltrim(rtrim(s, cs), cs);
}
}
#endif // GENERIC_STRING_HPP
<commit_msg>some fixes<commit_after>#ifndef GENERIC_STRING_HPP
# define GENERIC_STRING_HPP
# pragma once
#include <cstring>
#include <algorithm>
#include <sstream>
#include <string>
#include <vector>
namespace generic
{
// cstrlen
//////////////////////////////////////////////////////////////////////////////
template <::std::size_t N>
inline constexpr ::std::size_t cstrlen(char const (&)[N]) noexcept
{
return N - 1;
}
//////////////////////////////////////////////////////////////////////////////
inline constexpr ::std::size_t cstrlen(char const* const p) noexcept
{
return *p ? 1 + cstrlen(p + 1) : 0;
}
// join
//////////////////////////////////////////////////////////////////////////////
template <typename C>
inline typename C::value_type join(C const& container,
typename C::value_type const sep) noexcept
{
if (container.size())
{
typename C::value_type r(*container.begin());
auto const end(container.end());
for (auto i(::std::next(container.begin())); i != end; ++i)
{
r += sep + *i;
}
return r;
}
else
{
return typename C::value_type();
}
}
//////////////////////////////////////////////////////////////////////////////
template <typename C>
inline typename C::value_type join(C const& container,
typename C::value_type::value_type const sep) noexcept
{
if (container.size())
{
typename C::value_type r(container.front());
auto const end(container.end());
for (typename C::const_iterator i(container.begin() + 1); i != end; ++i)
{
r += sep + *i;
}
return r;
}
else
{
return typename C::value_type();
}
}
// split
//////////////////////////////////////////////////////////////////////////////
template<class CharT, class Traits, class Allocator>
inline ::std::vector<::std::basic_string<CharT, Traits, Allocator> >
split(::std::basic_string<CharT, Traits, Allocator> const& s,
CharT const delim) noexcept
{
::std::stringstream ss(s);
::std::string item;
::std::vector<typename ::std::decay<decltype(s)>::type> r;
while (::std::getline(ss, item, delim))
{
r.push_back(item);
}
return r;
}
//////////////////////////////////////////////////////////////////////////////
inline ::std::vector<::std::string>
split(::std::string const& s,
char const* const delims = "\f\n\r\t\v") noexcept
{
::std::vector<typename ::std::decay<decltype(s)>::type> r;
auto const S(s.size());
decltype(s.size()) i{};
while (i < S)
{
while ((i < S) && ::std::strchr(delims, s[i]))
{
++i;
}
if (i == S)
{
break;
}
// else do nothing
auto j(i + 1);
while ((j < S) && !::std::strchr(delims, s[j]))
{
++j;
}
r.push_back(s.substr(i, j - i));
i = j + 1;
}
return r;
}
// trim
//////////////////////////////////////////////////////////////////////////////
template<class CharT, class Traits, class Allocator>
inline ::std::basic_string<CharT, Traits, Allocator>&
ltrim(::std::basic_string<CharT, Traits, Allocator>& s,
CharT const* cs = " ") noexcept
{
s.erase(s.begin(),
::std::find_if(s.begin(), s.end(),
[cs](char const c) noexcept {
return !::std::strrchr(cs, c);
}
)
);
return s;
}
template<class CharT, class Traits, class Allocator>
inline ::std::basic_string<CharT, Traits, Allocator>&
rtrim(::std::basic_string<CharT, Traits, Allocator>& s,
CharT const* cs = " ") noexcept
{
s.erase(::std::find_if(s.rbegin(), s.rend(),
[cs](char const c) noexcept {
return !::std::strrchr(cs, c);
}
).base(),
s.end()
);
return s;
}
template<class CharT, class Traits, class Allocator>
inline ::std::basic_string<CharT, Traits, Allocator>&
trim(::std::basic_string<CharT, Traits, Allocator>& s,
CharT const* cs = " ") noexcept
{
return ltrim(rtrim(s, cs), cs);
}
}
#endif // GENERIC_STRING_HPP
<|endoftext|>
|
<commit_before>// $Id$
/*
Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior University
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 Stanford University 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.
*/
/*credit.cpp
*
*A class for credits
*/
#include "booksim.hpp"
#include "credit.hpp"
stack<Credit *> Credit::_pool;
Credit::Credit(int max_vcs)
{
Reset();
}
void Credit::Reset(int max_vcs)
{
vc.resize(max_vcs);
vc_cnt = 0;
tail = false;
id = -1;
dest_router = -1;
}
Credit * Credit::New(int max_vcs) {
Credit * c;
if(_pool.empty()) {
c = new Credit(max_vcs);
} else {
c = _pool.top();
c->Reset(max_vcs);
_pool.pop();
}
return c;
}
void Credit::Free() {
_pool.push(this);
}
void Credit::FreePool() {
while(!_pool.empty()) {
delete _pool.top();
_pool.pop();
}
}
<commit_msg>reset head field<commit_after>// $Id$
/*
Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior University
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 Stanford University 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.
*/
/*credit.cpp
*
*A class for credits
*/
#include "booksim.hpp"
#include "credit.hpp"
stack<Credit *> Credit::_pool;
Credit::Credit(int max_vcs)
{
Reset();
}
void Credit::Reset(int max_vcs)
{
vc.resize(max_vcs);
vc_cnt = 0;
head = false;
tail = false;
id = -1;
dest_router = -1;
}
Credit * Credit::New(int max_vcs) {
Credit * c;
if(_pool.empty()) {
c = new Credit(max_vcs);
} else {
c = _pool.top();
c->Reset(max_vcs);
_pool.pop();
}
return c;
}
void Credit::Free() {
_pool.push(this);
}
void Credit::FreePool() {
while(!_pool.empty()) {
delete _pool.top();
_pool.pop();
}
}
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2005 Steven L. Scott
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
/*
* R : A Computer Language for Statistical Data Analysis
* Copyright (C) 1995, 1996 Robert Gentleman and Ross Ihaka
* Copyright (C) 2000 The R Development Core Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/
#include "nmath.hpp"
#include "dpq.hpp"
namespace Rmath{
double dlogis(double x, double location, double scale, int give_log)
{
double e, f;
#ifdef IEEE_754
if (ISNAN(x) || ISNAN(location) || ISNAN(scale))
return x + location + scale;
#endif
if (scale <= 0.0)
ML_ERR_return_NAN;
x = (x - location) / scale;
e = exp(-x);
f = 1.0 + e;
return give_log ? -(x + log(scale * f * f)) : e / (scale * f * f);
}
}
<commit_msg>Add missing 'fabs' to dlogis.<commit_after>/*
Copyright (C) 2005 Steven L. Scott
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
/*
* R : A Computer Language for Statistical Data Analysis
* Copyright (C) 1995, 1996 Robert Gentleman and Ross Ihaka
* Copyright (C) 2000 The R Development Core Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/
#include "nmath.hpp"
#include "dpq.hpp"
namespace Rmath{
double dlogis(double x, double location, double scale, int give_log)
{
double e, f;
#ifdef IEEE_754
if (ISNAN(x) || ISNAN(location) || ISNAN(scale))
return x + location + scale;
#endif
if (scale <= 0.0)
ML_ERR_return_NAN;
x = fabs((x - location) / scale);
e = exp(-x);
f = 1.0 + e;
return give_log ? -(x + log(scale * f * f)) : e / (scale * f * f);
}
}
<|endoftext|>
|
<commit_before>/*
* libjingle
* Copyright 2004 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/media/base/testutils.h"
#if defined(OSX) && defined(FLUTE_IN_CHROME_BUILD)
#include <mach-o/dyld.h> // For NSGetExecutablePath.
#endif
#include <math.h>
#include "talk/media/base/executablehelpers.h"
#include "talk/media/base/rtpdump.h"
#include "talk/media/base/videocapturer.h"
#include "talk/media/base/videoframe.h"
#include "webrtc/base/bytebuffer.h"
#include "webrtc/base/fileutils.h"
#include "webrtc/base/gunit.h"
#include "webrtc/base/pathutils.h"
#include "webrtc/base/stream.h"
#include "webrtc/base/stringutils.h"
#include "webrtc/base/testutils.h"
namespace cricket {
/////////////////////////////////////////////////////////////////////////
// Implementation of RawRtpPacket
/////////////////////////////////////////////////////////////////////////
void RawRtpPacket::WriteToByteBuffer(
uint32 in_ssrc, rtc::ByteBuffer *buf) const {
if (!buf) return;
buf->WriteUInt8(ver_to_cc);
buf->WriteUInt8(m_to_pt);
buf->WriteUInt16(sequence_number);
buf->WriteUInt32(timestamp);
buf->WriteUInt32(in_ssrc);
buf->WriteBytes(payload, sizeof(payload));
}
bool RawRtpPacket::ReadFromByteBuffer(rtc::ByteBuffer* buf) {
if (!buf) return false;
bool ret = true;
ret &= buf->ReadUInt8(&ver_to_cc);
ret &= buf->ReadUInt8(&m_to_pt);
ret &= buf->ReadUInt16(&sequence_number);
ret &= buf->ReadUInt32(×tamp);
ret &= buf->ReadUInt32(&ssrc);
ret &= buf->ReadBytes(payload, sizeof(payload));
return ret;
}
bool RawRtpPacket::SameExceptSeqNumTimestampSsrc(
const RawRtpPacket& packet, uint16 seq, uint32 ts, uint32 ssc) const {
return sequence_number == seq &&
timestamp == ts &&
ver_to_cc == packet.ver_to_cc &&
m_to_pt == packet.m_to_pt &&
ssrc == ssc &&
0 == memcmp(payload, packet.payload, sizeof(payload));
}
/////////////////////////////////////////////////////////////////////////
// Implementation of RawRtcpPacket
/////////////////////////////////////////////////////////////////////////
void RawRtcpPacket::WriteToByteBuffer(rtc::ByteBuffer *buf) const {
if (!buf) return;
buf->WriteUInt8(ver_to_count);
buf->WriteUInt8(type);
buf->WriteUInt16(length);
buf->WriteBytes(payload, sizeof(payload));
}
bool RawRtcpPacket::ReadFromByteBuffer(rtc::ByteBuffer* buf) {
if (!buf) return false;
bool ret = true;
ret &= buf->ReadUInt8(&ver_to_count);
ret &= buf->ReadUInt8(&type);
ret &= buf->ReadUInt16(&length);
ret &= buf->ReadBytes(payload, sizeof(payload));
return ret;
}
bool RawRtcpPacket::EqualsTo(const RawRtcpPacket& packet) const {
return ver_to_count == packet.ver_to_count &&
type == packet.type &&
length == packet.length &&
0 == memcmp(payload, packet.payload, sizeof(payload));
}
/////////////////////////////////////////////////////////////////////////
// Implementation of class RtpTestUtility
/////////////////////////////////////////////////////////////////////////
const RawRtpPacket RtpTestUtility::kTestRawRtpPackets[] = {
{0x80, 0, 0, 0, RtpTestUtility::kDefaultSsrc, "RTP frame 0"},
{0x80, 0, 1, 30, RtpTestUtility::kDefaultSsrc, "RTP frame 1"},
{0x80, 0, 2, 30, RtpTestUtility::kDefaultSsrc, "RTP frame 1"},
{0x80, 0, 3, 60, RtpTestUtility::kDefaultSsrc, "RTP frame 2"}
};
const RawRtcpPacket RtpTestUtility::kTestRawRtcpPackets[] = {
// The Version is 2, the Length is 2, and the payload has 8 bytes.
{0x80, 0, 2, "RTCP0000"},
{0x80, 0, 2, "RTCP0001"},
{0x80, 0, 2, "RTCP0002"},
{0x80, 0, 2, "RTCP0003"},
};
size_t RtpTestUtility::GetTestPacketCount() {
return rtc::_min(
ARRAY_SIZE(kTestRawRtpPackets),
ARRAY_SIZE(kTestRawRtcpPackets));
}
bool RtpTestUtility::WriteTestPackets(
size_t count, bool rtcp, uint32 rtp_ssrc, RtpDumpWriter* writer) {
if (!writer || count > GetTestPacketCount()) return false;
bool result = true;
uint32 elapsed_time_ms = 0;
for (size_t i = 0; i < count && result; ++i) {
rtc::ByteBuffer buf;
if (rtcp) {
kTestRawRtcpPackets[i].WriteToByteBuffer(&buf);
} else {
kTestRawRtpPackets[i].WriteToByteBuffer(rtp_ssrc, &buf);
}
RtpDumpPacket dump_packet(buf.Data(), buf.Length(), elapsed_time_ms, rtcp);
elapsed_time_ms += kElapsedTimeInterval;
result &= (rtc::SR_SUCCESS == writer->WritePacket(dump_packet));
}
return result;
}
bool RtpTestUtility::VerifyTestPacketsFromStream(
size_t count, rtc::StreamInterface* stream, uint32 ssrc) {
if (!stream) return false;
uint32 prev_elapsed_time = 0;
bool result = true;
stream->Rewind();
RtpDumpLoopReader reader(stream);
for (size_t i = 0; i < count && result; ++i) {
// Which loop and which index in the loop are we reading now.
size_t loop = i / GetTestPacketCount();
size_t index = i % GetTestPacketCount();
RtpDumpPacket packet;
result &= (rtc::SR_SUCCESS == reader.ReadPacket(&packet));
// Check the elapsed time of the dump packet.
result &= (packet.elapsed_time >= prev_elapsed_time);
prev_elapsed_time = packet.elapsed_time;
// Check the RTP or RTCP packet.
rtc::ByteBuffer buf(reinterpret_cast<const char*>(&packet.data[0]),
packet.data.size());
if (packet.is_rtcp()) {
// RTCP packet.
RawRtcpPacket rtcp_packet;
result &= rtcp_packet.ReadFromByteBuffer(&buf);
result &= rtcp_packet.EqualsTo(kTestRawRtcpPackets[index]);
} else {
// RTP packet.
RawRtpPacket rtp_packet;
result &= rtp_packet.ReadFromByteBuffer(&buf);
result &= rtp_packet.SameExceptSeqNumTimestampSsrc(
kTestRawRtpPackets[index],
static_cast<uint16>(kTestRawRtpPackets[index].sequence_number +
loop * GetTestPacketCount()),
static_cast<uint32>(kTestRawRtpPackets[index].timestamp +
loop * kRtpTimestampIncrease),
ssrc);
}
}
stream->Rewind();
return result;
}
bool RtpTestUtility::VerifyPacket(const RtpDumpPacket* dump,
const RawRtpPacket* raw,
bool header_only) {
if (!dump || !raw) return false;
rtc::ByteBuffer buf;
raw->WriteToByteBuffer(RtpTestUtility::kDefaultSsrc, &buf);
if (header_only) {
size_t header_len = 0;
dump->GetRtpHeaderLen(&header_len);
return header_len == dump->data.size() &&
buf.Length() > dump->data.size() &&
0 == memcmp(buf.Data(), &dump->data[0], dump->data.size());
} else {
return buf.Length() == dump->data.size() &&
0 == memcmp(buf.Data(), &dump->data[0], dump->data.size());
}
}
// Implementation of VideoCaptureListener.
VideoCapturerListener::VideoCapturerListener(VideoCapturer* capturer)
: last_capture_state_(CS_STARTING),
frame_count_(0),
frame_fourcc_(0),
frame_width_(0),
frame_height_(0),
frame_size_(0),
resolution_changed_(false) {
capturer->SignalStateChange.connect(this,
&VideoCapturerListener::OnStateChange);
capturer->SignalFrameCaptured.connect(this,
&VideoCapturerListener::OnFrameCaptured);
}
void VideoCapturerListener::OnStateChange(VideoCapturer* capturer,
CaptureState result) {
last_capture_state_ = result;
}
void VideoCapturerListener::OnFrameCaptured(VideoCapturer* capturer,
const CapturedFrame* frame) {
++frame_count_;
if (1 == frame_count_) {
frame_fourcc_ = frame->fourcc;
frame_width_ = frame->width;
frame_height_ = frame->height;
frame_size_ = frame->data_size;
} else if (frame_width_ != frame->width || frame_height_ != frame->height) {
resolution_changed_ = true;
}
}
// Returns the absolute path to a file in the testdata/ directory.
std::string GetTestFilePath(const std::string& filename) {
// Locate test data directory.
#ifdef ENABLE_WEBRTC
rtc::Pathname path = rtc::GetExecutablePath();
EXPECT_FALSE(path.empty());
path.AppendPathname("../../talk/");
#else
rtc::Pathname path = testing::GetTalkDirectory();
EXPECT_FALSE(path.empty()); // must be run from inside "talk"
#endif
path.AppendFolder("media/testdata/");
path.SetFilename(filename);
return path.pathname();
}
// Loads the image with the specified prefix and size into |out|.
bool LoadPlanarYuvTestImage(const std::string& prefix,
int width, int height, uint8* out) {
std::stringstream ss;
ss << prefix << "." << width << "x" << height << "_P420.yuv";
rtc::scoped_ptr<rtc::FileStream> stream(
rtc::Filesystem::OpenFile(rtc::Pathname(
GetTestFilePath(ss.str())), "rb"));
if (!stream) {
return false;
}
rtc::StreamResult res =
stream->ReadAll(out, I420_SIZE(width, height), NULL, NULL);
return (res == rtc::SR_SUCCESS);
}
// Dumps the YUV image out to a file, for visual inspection.
// PYUV tool can be used to view dump files.
void DumpPlanarYuvTestImage(const std::string& prefix, const uint8* img,
int w, int h) {
rtc::FileStream fs;
char filename[256];
rtc::sprintfn(filename, sizeof(filename), "%s.%dx%d_P420.yuv",
prefix.c_str(), w, h);
fs.Open(filename, "wb", NULL);
fs.Write(img, I420_SIZE(w, h), NULL, NULL);
}
// Dumps the ARGB image out to a file, for visual inspection.
// ffplay tool can be used to view dump files.
void DumpPlanarArgbTestImage(const std::string& prefix, const uint8* img,
int w, int h) {
rtc::FileStream fs;
char filename[256];
rtc::sprintfn(filename, sizeof(filename), "%s.%dx%d_ARGB.raw",
prefix.c_str(), w, h);
fs.Open(filename, "wb", NULL);
fs.Write(img, ARGB_SIZE(w, h), NULL, NULL);
}
bool VideoFrameEqual(const VideoFrame* frame0, const VideoFrame* frame1) {
const uint8* y0 = frame0->GetYPlane();
const uint8* u0 = frame0->GetUPlane();
const uint8* v0 = frame0->GetVPlane();
const uint8* y1 = frame1->GetYPlane();
const uint8* u1 = frame1->GetUPlane();
const uint8* v1 = frame1->GetVPlane();
for (size_t i = 0; i < frame0->GetHeight(); ++i) {
if (0 != memcmp(y0, y1, frame0->GetWidth())) {
return false;
}
y0 += frame0->GetYPitch();
y1 += frame1->GetYPitch();
}
for (size_t i = 0; i < frame0->GetChromaHeight(); ++i) {
if (0 != memcmp(u0, u1, frame0->GetChromaWidth())) {
return false;
}
if (0 != memcmp(v0, v1, frame0->GetChromaWidth())) {
return false;
}
u0 += frame0->GetUPitch();
v0 += frame0->GetVPitch();
u1 += frame1->GetUPitch();
v1 += frame1->GetVPitch();
}
return true;
}
cricket::StreamParams CreateSimStreamParams(
const std::string& cname, const std::vector<uint32>& ssrcs) {
cricket::StreamParams sp;
cricket::SsrcGroup sg(cricket::kSimSsrcGroupSemantics, ssrcs);
sp.ssrcs = ssrcs;
sp.ssrc_groups.push_back(sg);
sp.cname = cname;
return sp;
}
// There should be an rtx_ssrc per ssrc.
cricket::StreamParams CreateSimWithRtxStreamParams(
const std::string& cname, const std::vector<uint32>& ssrcs,
const std::vector<uint32>& rtx_ssrcs) {
cricket::StreamParams sp = CreateSimStreamParams(cname, ssrcs);
for (size_t i = 0; i < ssrcs.size(); ++i) {
sp.ssrcs.push_back(rtx_ssrcs[i]);
std::vector<uint32> fid_ssrcs;
fid_ssrcs.push_back(ssrcs[i]);
fid_ssrcs.push_back(rtx_ssrcs[i]);
cricket::SsrcGroup fid_group(cricket::kFidSsrcGroupSemantics, fid_ssrcs);
sp.ssrc_groups.push_back(fid_group);
}
return sp;
}
} // namespace cricket
<commit_msg>Remove unnecessary include from testutils.cc.<commit_after>/*
* libjingle
* Copyright 2004 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/media/base/testutils.h"
#include <math.h>
#include "talk/media/base/executablehelpers.h"
#include "talk/media/base/rtpdump.h"
#include "talk/media/base/videocapturer.h"
#include "talk/media/base/videoframe.h"
#include "webrtc/base/bytebuffer.h"
#include "webrtc/base/fileutils.h"
#include "webrtc/base/gunit.h"
#include "webrtc/base/pathutils.h"
#include "webrtc/base/stream.h"
#include "webrtc/base/stringutils.h"
#include "webrtc/base/testutils.h"
namespace cricket {
/////////////////////////////////////////////////////////////////////////
// Implementation of RawRtpPacket
/////////////////////////////////////////////////////////////////////////
void RawRtpPacket::WriteToByteBuffer(
uint32 in_ssrc, rtc::ByteBuffer *buf) const {
if (!buf) return;
buf->WriteUInt8(ver_to_cc);
buf->WriteUInt8(m_to_pt);
buf->WriteUInt16(sequence_number);
buf->WriteUInt32(timestamp);
buf->WriteUInt32(in_ssrc);
buf->WriteBytes(payload, sizeof(payload));
}
bool RawRtpPacket::ReadFromByteBuffer(rtc::ByteBuffer* buf) {
if (!buf) return false;
bool ret = true;
ret &= buf->ReadUInt8(&ver_to_cc);
ret &= buf->ReadUInt8(&m_to_pt);
ret &= buf->ReadUInt16(&sequence_number);
ret &= buf->ReadUInt32(×tamp);
ret &= buf->ReadUInt32(&ssrc);
ret &= buf->ReadBytes(payload, sizeof(payload));
return ret;
}
bool RawRtpPacket::SameExceptSeqNumTimestampSsrc(
const RawRtpPacket& packet, uint16 seq, uint32 ts, uint32 ssc) const {
return sequence_number == seq &&
timestamp == ts &&
ver_to_cc == packet.ver_to_cc &&
m_to_pt == packet.m_to_pt &&
ssrc == ssc &&
0 == memcmp(payload, packet.payload, sizeof(payload));
}
/////////////////////////////////////////////////////////////////////////
// Implementation of RawRtcpPacket
/////////////////////////////////////////////////////////////////////////
void RawRtcpPacket::WriteToByteBuffer(rtc::ByteBuffer *buf) const {
if (!buf) return;
buf->WriteUInt8(ver_to_count);
buf->WriteUInt8(type);
buf->WriteUInt16(length);
buf->WriteBytes(payload, sizeof(payload));
}
bool RawRtcpPacket::ReadFromByteBuffer(rtc::ByteBuffer* buf) {
if (!buf) return false;
bool ret = true;
ret &= buf->ReadUInt8(&ver_to_count);
ret &= buf->ReadUInt8(&type);
ret &= buf->ReadUInt16(&length);
ret &= buf->ReadBytes(payload, sizeof(payload));
return ret;
}
bool RawRtcpPacket::EqualsTo(const RawRtcpPacket& packet) const {
return ver_to_count == packet.ver_to_count &&
type == packet.type &&
length == packet.length &&
0 == memcmp(payload, packet.payload, sizeof(payload));
}
/////////////////////////////////////////////////////////////////////////
// Implementation of class RtpTestUtility
/////////////////////////////////////////////////////////////////////////
const RawRtpPacket RtpTestUtility::kTestRawRtpPackets[] = {
{0x80, 0, 0, 0, RtpTestUtility::kDefaultSsrc, "RTP frame 0"},
{0x80, 0, 1, 30, RtpTestUtility::kDefaultSsrc, "RTP frame 1"},
{0x80, 0, 2, 30, RtpTestUtility::kDefaultSsrc, "RTP frame 1"},
{0x80, 0, 3, 60, RtpTestUtility::kDefaultSsrc, "RTP frame 2"}
};
const RawRtcpPacket RtpTestUtility::kTestRawRtcpPackets[] = {
// The Version is 2, the Length is 2, and the payload has 8 bytes.
{0x80, 0, 2, "RTCP0000"},
{0x80, 0, 2, "RTCP0001"},
{0x80, 0, 2, "RTCP0002"},
{0x80, 0, 2, "RTCP0003"},
};
size_t RtpTestUtility::GetTestPacketCount() {
return rtc::_min(
ARRAY_SIZE(kTestRawRtpPackets),
ARRAY_SIZE(kTestRawRtcpPackets));
}
bool RtpTestUtility::WriteTestPackets(
size_t count, bool rtcp, uint32 rtp_ssrc, RtpDumpWriter* writer) {
if (!writer || count > GetTestPacketCount()) return false;
bool result = true;
uint32 elapsed_time_ms = 0;
for (size_t i = 0; i < count && result; ++i) {
rtc::ByteBuffer buf;
if (rtcp) {
kTestRawRtcpPackets[i].WriteToByteBuffer(&buf);
} else {
kTestRawRtpPackets[i].WriteToByteBuffer(rtp_ssrc, &buf);
}
RtpDumpPacket dump_packet(buf.Data(), buf.Length(), elapsed_time_ms, rtcp);
elapsed_time_ms += kElapsedTimeInterval;
result &= (rtc::SR_SUCCESS == writer->WritePacket(dump_packet));
}
return result;
}
bool RtpTestUtility::VerifyTestPacketsFromStream(
size_t count, rtc::StreamInterface* stream, uint32 ssrc) {
if (!stream) return false;
uint32 prev_elapsed_time = 0;
bool result = true;
stream->Rewind();
RtpDumpLoopReader reader(stream);
for (size_t i = 0; i < count && result; ++i) {
// Which loop and which index in the loop are we reading now.
size_t loop = i / GetTestPacketCount();
size_t index = i % GetTestPacketCount();
RtpDumpPacket packet;
result &= (rtc::SR_SUCCESS == reader.ReadPacket(&packet));
// Check the elapsed time of the dump packet.
result &= (packet.elapsed_time >= prev_elapsed_time);
prev_elapsed_time = packet.elapsed_time;
// Check the RTP or RTCP packet.
rtc::ByteBuffer buf(reinterpret_cast<const char*>(&packet.data[0]),
packet.data.size());
if (packet.is_rtcp()) {
// RTCP packet.
RawRtcpPacket rtcp_packet;
result &= rtcp_packet.ReadFromByteBuffer(&buf);
result &= rtcp_packet.EqualsTo(kTestRawRtcpPackets[index]);
} else {
// RTP packet.
RawRtpPacket rtp_packet;
result &= rtp_packet.ReadFromByteBuffer(&buf);
result &= rtp_packet.SameExceptSeqNumTimestampSsrc(
kTestRawRtpPackets[index],
static_cast<uint16>(kTestRawRtpPackets[index].sequence_number +
loop * GetTestPacketCount()),
static_cast<uint32>(kTestRawRtpPackets[index].timestamp +
loop * kRtpTimestampIncrease),
ssrc);
}
}
stream->Rewind();
return result;
}
bool RtpTestUtility::VerifyPacket(const RtpDumpPacket* dump,
const RawRtpPacket* raw,
bool header_only) {
if (!dump || !raw) return false;
rtc::ByteBuffer buf;
raw->WriteToByteBuffer(RtpTestUtility::kDefaultSsrc, &buf);
if (header_only) {
size_t header_len = 0;
dump->GetRtpHeaderLen(&header_len);
return header_len == dump->data.size() &&
buf.Length() > dump->data.size() &&
0 == memcmp(buf.Data(), &dump->data[0], dump->data.size());
} else {
return buf.Length() == dump->data.size() &&
0 == memcmp(buf.Data(), &dump->data[0], dump->data.size());
}
}
// Implementation of VideoCaptureListener.
VideoCapturerListener::VideoCapturerListener(VideoCapturer* capturer)
: last_capture_state_(CS_STARTING),
frame_count_(0),
frame_fourcc_(0),
frame_width_(0),
frame_height_(0),
frame_size_(0),
resolution_changed_(false) {
capturer->SignalStateChange.connect(this,
&VideoCapturerListener::OnStateChange);
capturer->SignalFrameCaptured.connect(this,
&VideoCapturerListener::OnFrameCaptured);
}
void VideoCapturerListener::OnStateChange(VideoCapturer* capturer,
CaptureState result) {
last_capture_state_ = result;
}
void VideoCapturerListener::OnFrameCaptured(VideoCapturer* capturer,
const CapturedFrame* frame) {
++frame_count_;
if (1 == frame_count_) {
frame_fourcc_ = frame->fourcc;
frame_width_ = frame->width;
frame_height_ = frame->height;
frame_size_ = frame->data_size;
} else if (frame_width_ != frame->width || frame_height_ != frame->height) {
resolution_changed_ = true;
}
}
// Returns the absolute path to a file in the testdata/ directory.
std::string GetTestFilePath(const std::string& filename) {
// Locate test data directory.
#ifdef ENABLE_WEBRTC
rtc::Pathname path = rtc::GetExecutablePath();
EXPECT_FALSE(path.empty());
path.AppendPathname("../../talk/");
#else
rtc::Pathname path = testing::GetTalkDirectory();
EXPECT_FALSE(path.empty()); // must be run from inside "talk"
#endif
path.AppendFolder("media/testdata/");
path.SetFilename(filename);
return path.pathname();
}
// Loads the image with the specified prefix and size into |out|.
bool LoadPlanarYuvTestImage(const std::string& prefix,
int width, int height, uint8* out) {
std::stringstream ss;
ss << prefix << "." << width << "x" << height << "_P420.yuv";
rtc::scoped_ptr<rtc::FileStream> stream(
rtc::Filesystem::OpenFile(rtc::Pathname(
GetTestFilePath(ss.str())), "rb"));
if (!stream) {
return false;
}
rtc::StreamResult res =
stream->ReadAll(out, I420_SIZE(width, height), NULL, NULL);
return (res == rtc::SR_SUCCESS);
}
// Dumps the YUV image out to a file, for visual inspection.
// PYUV tool can be used to view dump files.
void DumpPlanarYuvTestImage(const std::string& prefix, const uint8* img,
int w, int h) {
rtc::FileStream fs;
char filename[256];
rtc::sprintfn(filename, sizeof(filename), "%s.%dx%d_P420.yuv",
prefix.c_str(), w, h);
fs.Open(filename, "wb", NULL);
fs.Write(img, I420_SIZE(w, h), NULL, NULL);
}
// Dumps the ARGB image out to a file, for visual inspection.
// ffplay tool can be used to view dump files.
void DumpPlanarArgbTestImage(const std::string& prefix, const uint8* img,
int w, int h) {
rtc::FileStream fs;
char filename[256];
rtc::sprintfn(filename, sizeof(filename), "%s.%dx%d_ARGB.raw",
prefix.c_str(), w, h);
fs.Open(filename, "wb", NULL);
fs.Write(img, ARGB_SIZE(w, h), NULL, NULL);
}
bool VideoFrameEqual(const VideoFrame* frame0, const VideoFrame* frame1) {
const uint8* y0 = frame0->GetYPlane();
const uint8* u0 = frame0->GetUPlane();
const uint8* v0 = frame0->GetVPlane();
const uint8* y1 = frame1->GetYPlane();
const uint8* u1 = frame1->GetUPlane();
const uint8* v1 = frame1->GetVPlane();
for (size_t i = 0; i < frame0->GetHeight(); ++i) {
if (0 != memcmp(y0, y1, frame0->GetWidth())) {
return false;
}
y0 += frame0->GetYPitch();
y1 += frame1->GetYPitch();
}
for (size_t i = 0; i < frame0->GetChromaHeight(); ++i) {
if (0 != memcmp(u0, u1, frame0->GetChromaWidth())) {
return false;
}
if (0 != memcmp(v0, v1, frame0->GetChromaWidth())) {
return false;
}
u0 += frame0->GetUPitch();
v0 += frame0->GetVPitch();
u1 += frame1->GetUPitch();
v1 += frame1->GetVPitch();
}
return true;
}
cricket::StreamParams CreateSimStreamParams(
const std::string& cname, const std::vector<uint32>& ssrcs) {
cricket::StreamParams sp;
cricket::SsrcGroup sg(cricket::kSimSsrcGroupSemantics, ssrcs);
sp.ssrcs = ssrcs;
sp.ssrc_groups.push_back(sg);
sp.cname = cname;
return sp;
}
// There should be an rtx_ssrc per ssrc.
cricket::StreamParams CreateSimWithRtxStreamParams(
const std::string& cname, const std::vector<uint32>& ssrcs,
const std::vector<uint32>& rtx_ssrcs) {
cricket::StreamParams sp = CreateSimStreamParams(cname, ssrcs);
for (size_t i = 0; i < ssrcs.size(); ++i) {
sp.ssrcs.push_back(rtx_ssrcs[i]);
std::vector<uint32> fid_ssrcs;
fid_ssrcs.push_back(ssrcs[i]);
fid_ssrcs.push_back(rtx_ssrcs[i]);
cricket::SsrcGroup fid_group(cricket::kFidSsrcGroupSemantics, fid_ssrcs);
sp.ssrc_groups.push_back(fid_group);
}
return sp;
}
} // namespace cricket
<|endoftext|>
|
<commit_before>#include "output-impl.hpp"
#include "wayfire/view.hpp"
#include "../core/core-impl.hpp"
#include "wayfire/signal-definitions.hpp"
#include "wayfire/render-manager.hpp"
#include "wayfire/output-layout.hpp"
#include "wayfire/workspace-manager.hpp"
#include "wayfire/compositor-view.hpp"
#include "wayfire-shell.hpp"
#include "../core/seat/input-manager.hpp"
#include "../view/xdg-shell.hpp"
#include <wayfire/util/log.hpp>
#include <linux/input.h>
extern "C"
{
#include <wlr/types/wlr_output.h>
}
#include <algorithm>
#include <assert.h>
wf::output_t::output_t() = default;
wf::output_impl_t::output_impl_t(wlr_output *handle, const wf::dimensions_t& effective_size)
{
this->set_effective_size(effective_size);
this->handle = handle;
workspace = std::make_unique<workspace_manager> (this);
render = std::make_unique<render_manager> (this);
view_disappeared_cb = [=] (wf::signal_data_t *data) {
output_t::refocus(get_signaled_view(data));
};
connect_signal("view-disappeared", &view_disappeared_cb);
connect_signal("detach-view", &view_disappeared_cb);
}
void wf::output_impl_t::start_plugins()
{
plugin = std::make_unique<plugin_manager> (this);
}
std::string wf::output_t::to_string() const
{
return handle->name;
}
void wf::output_impl_t::refocus(wayfire_view skip_view, uint32_t layers)
{
wayfire_view next_focus = nullptr;
auto views = workspace->get_views_on_workspace(workspace->get_current_workspace(), layers, true);
for (auto v : views)
{
if (v != skip_view && v->is_mapped() &&
v->get_keyboard_focus_surface())
{
next_focus = v;
break;
}
}
focus_view(next_focus, 0u);
}
void wf::output_t::refocus(wayfire_view skip_view)
{
uint32_t focused_layer = wf::get_core().get_focused_layer();
uint32_t layers = focused_layer <= LAYER_WORKSPACE ? WM_LAYERS : focused_layer;
auto views = workspace->get_views_on_workspace(
workspace->get_current_workspace(), layers, true);
if (views.empty())
{
if (wf::get_core().get_active_output() == this) {
LOGD("warning: no focused views in the focused layer, probably a bug");
}
/* Usually, we focus a layer so that a particular view has focus, i.e
* we expect that there is a view in the focused layer. However we
* should try to find reasonable focus in any focuseable layers if
* that is not the case, for ex. if there is a focused layer by a
* layer surface on another output */
layers = all_layers_not_below(focused_layer);
}
refocus(skip_view, layers);
}
wf::output_t::~output_t()
{
wf::get_core_impl().input->free_output_bindings(this);
}
wf::output_impl_t::~output_impl_t() { }
void wf::output_impl_t::set_effective_size(const wf::dimensions_t& size)
{
this->effective_size = size;
}
wf::dimensions_t wf::output_impl_t::get_screen_size() const
{
return this->effective_size;
}
wf::geometry_t wf::output_t::get_relative_geometry() const
{
auto size = get_screen_size();
return {
0, 0, size.width, size.height
};
}
wf::geometry_t wf::output_t::get_layout_geometry() const
{
auto box = wlr_output_layout_get_box(
wf::get_core().output_layout->get_handle(), handle);
if (box) {
return *box;
} else {
LOGE("Get layout geometry for an invalid output!");
return {0, 0, 1, 1};
}
}
void wf::output_t::ensure_pointer(bool center) const
{
auto ptr = wf::get_core().get_cursor_position();
if (!center &&
(get_layout_geometry() & wf::point_t{(int)ptr.x, (int)ptr.y}))
{
return;
}
auto lg = get_layout_geometry();
wf::point_t target = {
lg.x + lg.width / 2,
lg.y + lg.height / 2,
};
wf::get_core().warp_cursor(target.x, target.y);
wf::get_core().set_cursor("default");
}
wf::pointf_t wf::output_t::get_cursor_position() const
{
auto og = get_layout_geometry();
auto gc = wf::get_core().get_cursor_position();
return {gc.x - og.x, gc.y - og.y};
}
bool wf::output_t::ensure_visible(wayfire_view v)
{
auto bbox = v->get_bounding_box();
auto g = this->get_relative_geometry();
/* Compute the percentage of the view which is visible */
auto intersection = wf::geometry_intersection(bbox, g);
double area = 1.0 * intersection.width * intersection.height;
area /= 1.0 * bbox.width * bbox.height;
if (area >= 0.1) /* View is somewhat visible, no need for anything special */
return false;
/* Otherwise, switch the workspace so the view gets maximum exposure */
int dx = bbox.x + bbox.width / 2;
int dy = bbox.y + bbox.height / 2;
int dvx = std::floor(1.0 * dx / g.width);
int dvy = std::floor(1.0 * dy / g.height);
auto cws = workspace->get_current_workspace();
workspace->request_workspace(cws + wf::point_t{dvx, dvy});
return true;
}
template<class popup_type>
void try_close_popup(wayfire_view to_check, wayfire_view active_view)
{
auto popup = dynamic_cast<wayfire_xdg_popup<popup_type>*> (to_check.get());
if (!popup || popup->popup_parent == active_view.get())
return;
/* Ignore popups which have a popup as their parent. In those cases, we'll
* close the topmost popup and this will recursively destroy the others.
*
* Otherwise we get a race condition with wlroots. */
if (dynamic_cast<wayfire_xdg_popup<popup_type>*> (popup->popup_parent))
return;
popup->close();
}
void wf::output_impl_t::close_popups()
{
for (auto& v : workspace->get_views_in_layer(wf::ALL_LAYERS))
{
try_close_popup<wlr_xdg_popup> (v, active_view);
try_close_popup<wlr_xdg_popup_v6> (v, active_view);
}
}
void wf::output_impl_t::update_active_view(wayfire_view v, uint32_t flags)
{
this->active_view = v;
if (this == wf::get_core().get_active_output())
wf::get_core().set_active_view(v);
if (flags & FOCUS_VIEW_CLOSE_POPUPS)
close_popups();
}
void wf::output_impl_t::focus_view(wayfire_view v, uint32_t flags)
{
if (v && workspace->get_view_layer(v) < wf::get_core().get_focused_layer())
{
auto active_view = get_active_view();
if (active_view && active_view->get_app_id().find("$unfocus") == 0)
return focus_view(nullptr, false);
LOGD("Denying focus request for a view from a lower layer than the"
" focused layer");
return;
}
if (!v || !v->is_mapped())
{
update_active_view(nullptr, flags);
return;
}
while (v->parent && v->parent->is_mapped())
v = v->parent;
/* If no keyboard focus surface is set, then we don't want to focus the view */
if (v->get_keyboard_focus_surface() || interactive_view_from_view(v.get()))
{
/* We must make sure the view which gets focus is visible on the
* current workspace */
if (v->minimized)
v->minimize_request(false);
update_active_view(v, flags);
if (flags & FOCUS_VIEW_RAISE)
workspace->bring_to_front(v);
focus_view_signal data;
data.view = v;
emit_signal("focus-view", &data);
}
}
void wf::output_impl_t::focus_view(wayfire_view v, bool raise)
{
uint32_t flags = FOCUS_VIEW_CLOSE_POPUPS;
if (raise)
flags |= FOCUS_VIEW_RAISE;
focus_view(v, flags);
}
wayfire_view wf::output_t::get_top_view() const
{
auto views = workspace->get_views_on_workspace(workspace->get_current_workspace(),
LAYER_WORKSPACE, false);
return views.empty() ? nullptr : views[0];
}
wayfire_view wf::output_impl_t::get_active_view() const
{
return active_view;
}
bool wf::output_impl_t::can_activate_plugin(const plugin_grab_interface_uptr& owner,
uint32_t flags)
{
if (!owner)
return false;
if (this->inhibited && !(flags & wf::PLUGIN_ACTIVATION_IGNORE_INHIBIT))
return false;
if (active_plugins.find(owner.get()) != active_plugins.end())
return flags & wf::PLUGIN_ACTIVATE_ALLOW_MULTIPLE;
for(auto act_owner : active_plugins)
{
bool compatible =
((act_owner->capabilities & owner->capabilities) == 0);
if (!compatible)
return false;
}
return true;
}
bool wf::output_impl_t::activate_plugin(const plugin_grab_interface_uptr& owner,
uint32_t flags)
{
if (!can_activate_plugin(owner, flags))
return false;
if (active_plugins.find(owner.get()) != active_plugins.end()) {
LOGD("output ", handle->name,
": activate plugin ", owner->name, " again");
} else {
LOGD("output ", handle->name, ": activate plugin ", owner->name);
}
active_plugins.insert(owner.get());
return true;
}
bool wf::output_impl_t::deactivate_plugin(
const plugin_grab_interface_uptr& owner)
{
auto it = active_plugins.find(owner.get());
if (it == active_plugins.end())
return true;
active_plugins.erase(it);
LOGD("output ", handle->name, ": deactivate plugin ", owner->name);
if (active_plugins.count(owner.get()) == 0)
{
owner->ungrab();
active_plugins.erase(owner.get());
return true;
}
return false;
}
bool wf::output_impl_t::is_plugin_active(std::string name) const
{
for (auto act : active_plugins)
if (act && act->name == name)
return true;
return false;
}
wf::plugin_grab_interface_t* wf::output_impl_t::get_input_grab_interface()
{
for (auto p : active_plugins)
if (p && p->is_grabbed())
return p;
return nullptr;
}
void wf::output_impl_t::inhibit_plugins()
{
this->inhibited = true;
std::vector<wf::plugin_grab_interface_t*> ifaces;
for (auto p : active_plugins)
{
if (p->callbacks.cancel)
ifaces.push_back(p);
}
for (auto p : ifaces)
p->callbacks.cancel();
}
void wf::output_impl_t::uninhibit_plugins()
{
this->inhibited = false;
}
bool wf::output_impl_t::is_inhibited() const
{
return this->inhibited;
}
/* simple wrappers for wf::get_core_impl().input, as it isn't exposed to plugins */
wf::binding_t *wf::output_t::add_key(option_sptr_t<keybinding_t> key, wf::key_callback *callback)
{
return wf::get_core_impl().input->new_binding(WF_BINDING_KEY, key, this, callback);
}
wf::binding_t *wf::output_t::add_axis(option_sptr_t<keybinding_t> axis, wf::axis_callback *callback)
{
return wf::get_core_impl().input->new_binding(WF_BINDING_AXIS, axis, this, callback);
}
wf::binding_t *wf::output_t::add_touch(option_sptr_t<keybinding_t> mod, wf::touch_callback *callback)
{
return wf::get_core_impl().input->new_binding(WF_BINDING_TOUCH, mod, this, callback);
}
wf::binding_t *wf::output_t::add_button(option_sptr_t<buttonbinding_t> button,
wf::button_callback *callback)
{
return wf::get_core_impl().input->new_binding(WF_BINDING_BUTTON, button,
this, callback);
}
wf::binding_t *wf::output_t::add_gesture(option_sptr_t<touchgesture_t> gesture,
wf::gesture_callback *callback)
{
return wf::get_core_impl().input->new_binding(WF_BINDING_GESTURE, gesture,
this, callback);
}
wf::binding_t *wf::output_t::add_activator(
option_sptr_t<activatorbinding_t> activator, wf::activator_callback *callback)
{
return wf::get_core_impl().input->new_binding(WF_BINDING_ACTIVATOR, activator,
this, callback);
}
void wf::output_t::rem_binding(wf::binding_t *binding)
{
wf::get_core_impl().input->rem_binding(binding);
}
void wf::output_t::rem_binding(void *callback)
{
wf::get_core_impl().input->rem_binding(callback);
}
namespace wf
{
uint32_t all_layers_not_below(uint32_t layer)
{
uint32_t mask = 0;
for (int i = 0; i < wf::TOTAL_LAYERS; i++)
{
if ((1u << i) >= layer)
mask |= (1 << i);
}
return mask;
}
}
<commit_msg>output: improve handling of $unfocus clients<commit_after>#include "output-impl.hpp"
#include "wayfire/view.hpp"
#include "../core/core-impl.hpp"
#include "wayfire/signal-definitions.hpp"
#include "wayfire/render-manager.hpp"
#include "wayfire/output-layout.hpp"
#include "wayfire/workspace-manager.hpp"
#include "wayfire/compositor-view.hpp"
#include "wayfire-shell.hpp"
#include "../core/seat/input-manager.hpp"
#include "../view/xdg-shell.hpp"
#include <wayfire/util/log.hpp>
#include <linux/input.h>
extern "C"
{
#include <wlr/types/wlr_output.h>
}
#include <algorithm>
#include <assert.h>
wf::output_t::output_t() = default;
wf::output_impl_t::output_impl_t(wlr_output *handle, const wf::dimensions_t& effective_size)
{
this->set_effective_size(effective_size);
this->handle = handle;
workspace = std::make_unique<workspace_manager> (this);
render = std::make_unique<render_manager> (this);
view_disappeared_cb = [=] (wf::signal_data_t *data) {
output_t::refocus(get_signaled_view(data));
};
connect_signal("view-disappeared", &view_disappeared_cb);
connect_signal("detach-view", &view_disappeared_cb);
}
void wf::output_impl_t::start_plugins()
{
plugin = std::make_unique<plugin_manager> (this);
}
std::string wf::output_t::to_string() const
{
return handle->name;
}
void wf::output_impl_t::refocus(wayfire_view skip_view, uint32_t layers)
{
wayfire_view next_focus = nullptr;
auto views = workspace->get_views_on_workspace(workspace->get_current_workspace(), layers, true);
for (auto v : views)
{
if (v != skip_view && v->is_mapped() &&
v->get_keyboard_focus_surface())
{
next_focus = v;
break;
}
}
focus_view(next_focus, 0u);
}
void wf::output_t::refocus(wayfire_view skip_view)
{
uint32_t focused_layer = wf::get_core().get_focused_layer();
uint32_t layers = focused_layer <= LAYER_WORKSPACE ? WM_LAYERS : focused_layer;
auto views = workspace->get_views_on_workspace(
workspace->get_current_workspace(), layers, true);
if (views.empty())
{
if (wf::get_core().get_active_output() == this) {
LOGD("warning: no focused views in the focused layer, probably a bug");
}
/* Usually, we focus a layer so that a particular view has focus, i.e
* we expect that there is a view in the focused layer. However we
* should try to find reasonable focus in any focuseable layers if
* that is not the case, for ex. if there is a focused layer by a
* layer surface on another output */
layers = all_layers_not_below(focused_layer);
}
refocus(skip_view, layers);
}
wf::output_t::~output_t()
{
wf::get_core_impl().input->free_output_bindings(this);
}
wf::output_impl_t::~output_impl_t() { }
void wf::output_impl_t::set_effective_size(const wf::dimensions_t& size)
{
this->effective_size = size;
}
wf::dimensions_t wf::output_impl_t::get_screen_size() const
{
return this->effective_size;
}
wf::geometry_t wf::output_t::get_relative_geometry() const
{
auto size = get_screen_size();
return {
0, 0, size.width, size.height
};
}
wf::geometry_t wf::output_t::get_layout_geometry() const
{
auto box = wlr_output_layout_get_box(
wf::get_core().output_layout->get_handle(), handle);
if (box) {
return *box;
} else {
LOGE("Get layout geometry for an invalid output!");
return {0, 0, 1, 1};
}
}
void wf::output_t::ensure_pointer(bool center) const
{
auto ptr = wf::get_core().get_cursor_position();
if (!center &&
(get_layout_geometry() & wf::point_t{(int)ptr.x, (int)ptr.y}))
{
return;
}
auto lg = get_layout_geometry();
wf::point_t target = {
lg.x + lg.width / 2,
lg.y + lg.height / 2,
};
wf::get_core().warp_cursor(target.x, target.y);
wf::get_core().set_cursor("default");
}
wf::pointf_t wf::output_t::get_cursor_position() const
{
auto og = get_layout_geometry();
auto gc = wf::get_core().get_cursor_position();
return {gc.x - og.x, gc.y - og.y};
}
bool wf::output_t::ensure_visible(wayfire_view v)
{
auto bbox = v->get_bounding_box();
auto g = this->get_relative_geometry();
/* Compute the percentage of the view which is visible */
auto intersection = wf::geometry_intersection(bbox, g);
double area = 1.0 * intersection.width * intersection.height;
area /= 1.0 * bbox.width * bbox.height;
if (area >= 0.1) /* View is somewhat visible, no need for anything special */
return false;
/* Otherwise, switch the workspace so the view gets maximum exposure */
int dx = bbox.x + bbox.width / 2;
int dy = bbox.y + bbox.height / 2;
int dvx = std::floor(1.0 * dx / g.width);
int dvy = std::floor(1.0 * dy / g.height);
auto cws = workspace->get_current_workspace();
workspace->request_workspace(cws + wf::point_t{dvx, dvy});
return true;
}
template<class popup_type>
void try_close_popup(wayfire_view to_check, wayfire_view active_view)
{
auto popup = dynamic_cast<wayfire_xdg_popup<popup_type>*> (to_check.get());
if (!popup || popup->popup_parent == active_view.get())
return;
/* Ignore popups which have a popup as their parent. In those cases, we'll
* close the topmost popup and this will recursively destroy the others.
*
* Otherwise we get a race condition with wlroots. */
if (dynamic_cast<wayfire_xdg_popup<popup_type>*> (popup->popup_parent))
return;
popup->close();
}
void wf::output_impl_t::close_popups()
{
for (auto& v : workspace->get_views_in_layer(wf::ALL_LAYERS))
{
try_close_popup<wlr_xdg_popup> (v, active_view);
try_close_popup<wlr_xdg_popup_v6> (v, active_view);
}
}
void wf::output_impl_t::update_active_view(wayfire_view v, uint32_t flags)
{
this->active_view = v;
if (this == wf::get_core().get_active_output())
wf::get_core().set_active_view(v);
if (flags & FOCUS_VIEW_CLOSE_POPUPS)
close_popups();
}
void wf::output_impl_t::focus_view(wayfire_view v, uint32_t flags)
{
const auto& make_view_visible = [this, flags] (wayfire_view view)
{
if (view->minimized)
view->minimize_request(false);
if (flags & FOCUS_VIEW_RAISE)
workspace->bring_to_front(view);
};
if (v && workspace->get_view_layer(v) < wf::get_core().get_focused_layer())
{
auto active_view = get_active_view();
if (active_view && active_view->get_app_id().find("$unfocus") == 0)
{
/* This is the case where for ex. a panel has grabbed input focus,
* but user has clicked on another view so we want to dismiss the
* grab. We can't do that straight away because the client still
* holds the focus layer request.
*
* Instead, we want to deactive the $unfocus view, so that it can
* release the grab. At the same time, we bring the to-be-focused
* view on top, so that it gets the focus next. */
update_active_view(nullptr, flags);
make_view_visible(v);
} else
{
LOGD("Denying focus request for a view from a lower layer than the"
" focused layer");
}
return;
}
if (!v || !v->is_mapped())
{
update_active_view(nullptr, flags);
return;
}
while (v->parent && v->parent->is_mapped())
v = v->parent;
/* If no keyboard focus surface is set, then we don't want to focus the view */
if (v->get_keyboard_focus_surface() || interactive_view_from_view(v.get()))
{
make_view_visible(v);
update_active_view(v, flags);
focus_view_signal data;
data.view = v;
emit_signal("focus-view", &data);
}
}
void wf::output_impl_t::focus_view(wayfire_view v, bool raise)
{
uint32_t flags = FOCUS_VIEW_CLOSE_POPUPS;
if (raise)
flags |= FOCUS_VIEW_RAISE;
focus_view(v, flags);
}
wayfire_view wf::output_t::get_top_view() const
{
auto views = workspace->get_views_on_workspace(workspace->get_current_workspace(),
LAYER_WORKSPACE, false);
return views.empty() ? nullptr : views[0];
}
wayfire_view wf::output_impl_t::get_active_view() const
{
return active_view;
}
bool wf::output_impl_t::can_activate_plugin(const plugin_grab_interface_uptr& owner,
uint32_t flags)
{
if (!owner)
return false;
if (this->inhibited && !(flags & wf::PLUGIN_ACTIVATION_IGNORE_INHIBIT))
return false;
if (active_plugins.find(owner.get()) != active_plugins.end())
return flags & wf::PLUGIN_ACTIVATE_ALLOW_MULTIPLE;
for(auto act_owner : active_plugins)
{
bool compatible =
((act_owner->capabilities & owner->capabilities) == 0);
if (!compatible)
return false;
}
return true;
}
bool wf::output_impl_t::activate_plugin(const plugin_grab_interface_uptr& owner,
uint32_t flags)
{
if (!can_activate_plugin(owner, flags))
return false;
if (active_plugins.find(owner.get()) != active_plugins.end()) {
LOGD("output ", handle->name,
": activate plugin ", owner->name, " again");
} else {
LOGD("output ", handle->name, ": activate plugin ", owner->name);
}
active_plugins.insert(owner.get());
return true;
}
bool wf::output_impl_t::deactivate_plugin(
const plugin_grab_interface_uptr& owner)
{
auto it = active_plugins.find(owner.get());
if (it == active_plugins.end())
return true;
active_plugins.erase(it);
LOGD("output ", handle->name, ": deactivate plugin ", owner->name);
if (active_plugins.count(owner.get()) == 0)
{
owner->ungrab();
active_plugins.erase(owner.get());
return true;
}
return false;
}
bool wf::output_impl_t::is_plugin_active(std::string name) const
{
for (auto act : active_plugins)
if (act && act->name == name)
return true;
return false;
}
wf::plugin_grab_interface_t* wf::output_impl_t::get_input_grab_interface()
{
for (auto p : active_plugins)
if (p && p->is_grabbed())
return p;
return nullptr;
}
void wf::output_impl_t::inhibit_plugins()
{
this->inhibited = true;
std::vector<wf::plugin_grab_interface_t*> ifaces;
for (auto p : active_plugins)
{
if (p->callbacks.cancel)
ifaces.push_back(p);
}
for (auto p : ifaces)
p->callbacks.cancel();
}
void wf::output_impl_t::uninhibit_plugins()
{
this->inhibited = false;
}
bool wf::output_impl_t::is_inhibited() const
{
return this->inhibited;
}
/* simple wrappers for wf::get_core_impl().input, as it isn't exposed to plugins */
wf::binding_t *wf::output_t::add_key(option_sptr_t<keybinding_t> key, wf::key_callback *callback)
{
return wf::get_core_impl().input->new_binding(WF_BINDING_KEY, key, this, callback);
}
wf::binding_t *wf::output_t::add_axis(option_sptr_t<keybinding_t> axis, wf::axis_callback *callback)
{
return wf::get_core_impl().input->new_binding(WF_BINDING_AXIS, axis, this, callback);
}
wf::binding_t *wf::output_t::add_touch(option_sptr_t<keybinding_t> mod, wf::touch_callback *callback)
{
return wf::get_core_impl().input->new_binding(WF_BINDING_TOUCH, mod, this, callback);
}
wf::binding_t *wf::output_t::add_button(option_sptr_t<buttonbinding_t> button,
wf::button_callback *callback)
{
return wf::get_core_impl().input->new_binding(WF_BINDING_BUTTON, button,
this, callback);
}
wf::binding_t *wf::output_t::add_gesture(option_sptr_t<touchgesture_t> gesture,
wf::gesture_callback *callback)
{
return wf::get_core_impl().input->new_binding(WF_BINDING_GESTURE, gesture,
this, callback);
}
wf::binding_t *wf::output_t::add_activator(
option_sptr_t<activatorbinding_t> activator, wf::activator_callback *callback)
{
return wf::get_core_impl().input->new_binding(WF_BINDING_ACTIVATOR, activator,
this, callback);
}
void wf::output_t::rem_binding(wf::binding_t *binding)
{
wf::get_core_impl().input->rem_binding(binding);
}
void wf::output_t::rem_binding(void *callback)
{
wf::get_core_impl().input->rem_binding(callback);
}
namespace wf
{
uint32_t all_layers_not_below(uint32_t layer)
{
uint32_t mask = 0;
for (int i = 0; i < wf::TOTAL_LAYERS; i++)
{
if ((1u << i) >= layer)
mask |= (1 << i);
}
return mask;
}
}
<|endoftext|>
|
<commit_before>#include "nano.h"
#include "class.h"
#include "measure.h"
#include "text/table.h"
#include "accumulator.h"
#include "text/cmdline.h"
#include "math/random.h"
#include "tensor/numeric.h"
#include "measure_and_log.h"
#include "layers/make_layers.h"
#include "tasks/task_charset.h"
#include "text/table_row_mark.h"
#include <iostream>
int main(int argc, const char *argv[])
{
using namespace nano;
// parse the command line
nano::cmdline_t cmdline("benchmark models");
cmdline.add("s", "samples", "number of samples to use [100, 10000]", "1000");
cmdline.add("c", "conn", "plane connectivity for convolution networks [1, 16]", "8");
cmdline.add("", "mlps", "benchmark MLP models");
cmdline.add("", "convnets", "benchmark convolution networks");
cmdline.add("", "forward", "evaluate the \'forward\' pass (output)");
cmdline.add("", "backward", "evaluate the \'backward' pass (gradient)");
cmdline.add("", "activation", "activation layer", "act-snorm");
cmdline.add("", "detailed", "print detailed measurements (e.g. per-layer)");
cmdline.process(argc, argv);
// check arguments and options
const auto cmd_samples = nano::clamp(cmdline.get<size_t>("samples"), 100, 100 * 1000);
const auto conn = nano::clamp(cmdline.get<int>("conn"), 1, 16);
const auto cmd_forward = cmdline.has("forward");
const auto cmd_backward = cmdline.has("backward");
const auto cmd_mlps = cmdline.has("mlps");
const auto cmd_convnets = cmdline.has("convnets");
const auto activation = cmdline.get("activation");
const auto cmd_detailed = cmdline.has("detailed");
if (!cmd_forward && !cmd_backward)
{
cmdline.usage();
}
if (!cmd_mlps && !cmd_convnets)
{
cmdline.usage();
}
const auto cmd_rows = 28;
const auto cmd_cols = 28;
const auto cmd_color = color_mode::luma;
const size_t cmd_min_nthreads = 1;
const size_t cmd_max_nthreads = nano::logical_cpus();
// generate synthetic task
charset_task_t task(to_params(
"type", charset_mode::digit, "color", cmd_color, "irows", cmd_rows, "icols", cmd_cols, "count", cmd_samples));
task.load();
// construct models
const string_t mlp0;
const string_t mlp1 = mlp0 + make_affine_layer(128, activation);
const string_t mlp2 = mlp1 + make_affine_layer(512, activation);
const string_t mlp3 = mlp2 + make_affine_layer(128, activation);
const string_t mlp4 = mlp3 + make_affine_layer(512, activation);
const string_t mlp5 = mlp4 + make_affine_layer(128, activation);
const string_t convnet0;
const string_t convnet1 = convnet0 + make_conv_layer(64, 7, 7, 1, activation);
const string_t convnet2 = convnet1 + make_conv_layer(64, 7, 7, conn, activation);
const string_t convnet3 = convnet2 + make_conv_layer(64, 5, 5, conn, activation);
const string_t convnet4 = convnet3 + make_conv_layer(64, 5, 5, conn, activation);
const string_t convnet5 = convnet4 + make_conv_layer(64, 3, 3, conn, activation);
const string_t outlayer = make_output_layer(task.odims());
std::vector<std::pair<string_t, string_t>> networks;
#define DEFINE(config) networks.emplace_back(config + outlayer, NANO_STRINGIFY(config))
if (cmd_mlps)
{
DEFINE(mlp0);
DEFINE(mlp1);
DEFINE(mlp2);
DEFINE(mlp3);
DEFINE(mlp4);
DEFINE(mlp5);
}
if (cmd_convnets)
{
DEFINE(convnet1);
DEFINE(convnet2);
DEFINE(convnet3);
DEFINE(convnet4);
DEFINE(convnet5);
}
#undef DEFINE
const auto loss = nano::get_losses().get("logistic");
const auto criterion = nano::get_criteria().get("avg");
// construct tables to compare models
nano::table_t ftable; ftable.header() << "model-forward [us] / sample";
nano::table_t btable; btable.header() << "model-backward [us] / sample";
for (size_t nthreads = cmd_min_nthreads; nthreads <= cmd_max_nthreads; ++ nthreads)
{
ftable.header() << (nano::to_string(nthreads) + "xCPU");
btable.header() << (nano::to_string(nthreads) + "xCPU");
}
// evaluate models
for (const auto& config : networks)
{
const string_t cmd_network = config.first;
const string_t cmd_name = config.second;
log_info() << "<<< running network [" << cmd_network << "] ...";
// create feed-forward network
const auto model = nano::get_models().get("forward-network", cmd_network);
model->resize(task);
model->random();
model->describe();
auto& frow = ftable.append() << (cmd_name + " (" + nano::to_string(model->psize()) + ")");
auto& brow = btable.append() << (cmd_name + " (" + nano::to_string(model->psize()) + ")");
const auto fold = fold_t{0, protocol::train};
std::vector<model_t::timings_t> ftimings(cmd_max_nthreads + 1);
std::vector<model_t::timings_t> btimings(cmd_max_nthreads + 1);
// process the samples
for (size_t nthreads = cmd_min_nthreads; nthreads <= cmd_max_nthreads; ++ nthreads)
{
accumulator_t acc(*model, *loss, *criterion);
acc.lambda(scalar_t(0.1));
acc.threads(nthreads);
if (cmd_forward)
{
const auto duration = nano::measure_robustly_usec([&] ()
{
acc.mode(criterion_t::type::value);
acc.update(task, fold);
}, 1);
log_info() << "<<< processed [" << acc.count()
<< "] forward samples in " << duration.count() << " us.";
frow << idiv(static_cast<size_t>(duration.count()), acc.count());
ftimings[nthreads] = acc.timings();
}
if (cmd_backward)
{
const auto duration = nano::measure_robustly_usec([&] ()
{
acc.mode(criterion_t::type::vgrad);
acc.update(task, fold);
}, 1);
log_info() << "<<< processed [" << acc.count()
<< "] backward samples in " << duration.count() << " us.";
brow << idiv(static_cast<size_t>(duration.count()), acc.count());
btimings[nthreads] = acc.timings();
}
}
// detailed per-component (e.g. per-layer) timing information
const auto print_timings = [&] (table_t& table, const string_t& basename,
const std::vector<model_t::timings_t>& timings)
{
for (const auto& timing0 : timings[cmd_min_nthreads])
{
auto& row = table.append();
row << (basename + timing0.first);
for (size_t nthreads = cmd_min_nthreads; nthreads <= cmd_max_nthreads; ++ nthreads)
{
const auto& timingT = timings[nthreads];
assert(timingT.find(timing0.first) != timingT.end());
row << timingT.find(timing0.first)->second.avg();
}
}
};
if (cmd_forward && cmd_detailed)
{
print_timings(ftable, ">", ftimings);
}
if (cmd_backward && cmd_detailed)
{
print_timings(btable, ">", btimings);
}
}
// print results
if (cmd_forward)
{
ftable.mark(nano::make_table_mark_minimum_percentage_cols<size_t>(5));
std::cout << ftable;
}
if (cmd_backward)
{
btable.mark(nano::make_table_mark_minimum_percentage_cols<size_t>(5));
std::cout << btable;
}
// OK
log_info() << done;
return EXIT_SUCCESS;
}
<commit_msg>remove duplicated logging message<commit_after>#include "nano.h"
#include "class.h"
#include "measure.h"
#include "text/table.h"
#include "accumulator.h"
#include "text/cmdline.h"
#include "math/random.h"
#include "tensor/numeric.h"
#include "measure_and_log.h"
#include "layers/make_layers.h"
#include "tasks/task_charset.h"
#include "text/table_row_mark.h"
#include <iostream>
int main(int argc, const char *argv[])
{
using namespace nano;
// parse the command line
nano::cmdline_t cmdline("benchmark models");
cmdline.add("s", "samples", "number of samples to use [100, 10000]", "1000");
cmdline.add("c", "conn", "plane connectivity for convolution networks [1, 16]", "8");
cmdline.add("", "mlps", "benchmark MLP models");
cmdline.add("", "convnets", "benchmark convolution networks");
cmdline.add("", "forward", "evaluate the \'forward\' pass (output)");
cmdline.add("", "backward", "evaluate the \'backward' pass (gradient)");
cmdline.add("", "activation", "activation layer", "act-snorm");
cmdline.add("", "detailed", "print detailed measurements (e.g. per-layer)");
cmdline.process(argc, argv);
// check arguments and options
const auto cmd_samples = nano::clamp(cmdline.get<size_t>("samples"), 100, 100 * 1000);
const auto conn = nano::clamp(cmdline.get<int>("conn"), 1, 16);
const auto cmd_forward = cmdline.has("forward");
const auto cmd_backward = cmdline.has("backward");
const auto cmd_mlps = cmdline.has("mlps");
const auto cmd_convnets = cmdline.has("convnets");
const auto activation = cmdline.get("activation");
const auto cmd_detailed = cmdline.has("detailed");
if (!cmd_forward && !cmd_backward)
{
cmdline.usage();
}
if (!cmd_mlps && !cmd_convnets)
{
cmdline.usage();
}
const auto cmd_rows = 28;
const auto cmd_cols = 28;
const auto cmd_color = color_mode::luma;
const size_t cmd_min_nthreads = 1;
const size_t cmd_max_nthreads = nano::logical_cpus();
// generate synthetic task
charset_task_t task(to_params(
"type", charset_mode::digit, "color", cmd_color, "irows", cmd_rows, "icols", cmd_cols, "count", cmd_samples));
task.load();
// construct models
const string_t mlp0;
const string_t mlp1 = mlp0 + make_affine_layer(128, activation);
const string_t mlp2 = mlp1 + make_affine_layer(512, activation);
const string_t mlp3 = mlp2 + make_affine_layer(128, activation);
const string_t mlp4 = mlp3 + make_affine_layer(512, activation);
const string_t mlp5 = mlp4 + make_affine_layer(128, activation);
const string_t convnet0;
const string_t convnet1 = convnet0 + make_conv_layer(64, 7, 7, 1, activation);
const string_t convnet2 = convnet1 + make_conv_layer(64, 7, 7, conn, activation);
const string_t convnet3 = convnet2 + make_conv_layer(64, 5, 5, conn, activation);
const string_t convnet4 = convnet3 + make_conv_layer(64, 5, 5, conn, activation);
const string_t convnet5 = convnet4 + make_conv_layer(64, 3, 3, conn, activation);
const string_t outlayer = make_output_layer(task.odims());
std::vector<std::pair<string_t, string_t>> networks;
#define DEFINE(config) networks.emplace_back(config + outlayer, NANO_STRINGIFY(config))
if (cmd_mlps)
{
DEFINE(mlp0);
DEFINE(mlp1);
DEFINE(mlp2);
DEFINE(mlp3);
DEFINE(mlp4);
DEFINE(mlp5);
}
if (cmd_convnets)
{
DEFINE(convnet1);
DEFINE(convnet2);
DEFINE(convnet3);
DEFINE(convnet4);
DEFINE(convnet5);
}
#undef DEFINE
const auto loss = nano::get_losses().get("logistic");
const auto criterion = nano::get_criteria().get("avg");
// construct tables to compare models
nano::table_t ftable; ftable.header() << "model-forward [us] / sample";
nano::table_t btable; btable.header() << "model-backward [us] / sample";
for (size_t nthreads = cmd_min_nthreads; nthreads <= cmd_max_nthreads; ++ nthreads)
{
ftable.header() << (nano::to_string(nthreads) + "xCPU");
btable.header() << (nano::to_string(nthreads) + "xCPU");
}
// evaluate models
for (const auto& config : networks)
{
const string_t cmd_network = config.first;
const string_t cmd_name = config.second;
// create feed-forward network
const auto model = nano::get_models().get("forward-network", cmd_network);
model->resize(task);
model->random();
model->describe();
auto& frow = ftable.append() << (cmd_name + " (" + nano::to_string(model->psize()) + ")");
auto& brow = btable.append() << (cmd_name + " (" + nano::to_string(model->psize()) + ")");
const auto fold = fold_t{0, protocol::train};
std::vector<model_t::timings_t> ftimings(cmd_max_nthreads + 1);
std::vector<model_t::timings_t> btimings(cmd_max_nthreads + 1);
// process the samples
for (size_t nthreads = cmd_min_nthreads; nthreads <= cmd_max_nthreads; ++ nthreads)
{
accumulator_t acc(*model, *loss, *criterion);
acc.lambda(scalar_t(0.1));
acc.threads(nthreads);
if (cmd_forward)
{
const auto duration = nano::measure_robustly_usec([&] ()
{
acc.mode(criterion_t::type::value);
acc.update(task, fold);
}, 1);
log_info() << "<<< processed [" << acc.count()
<< "] forward samples in " << duration.count() << " us.";
frow << idiv(static_cast<size_t>(duration.count()), acc.count());
ftimings[nthreads] = acc.timings();
}
if (cmd_backward)
{
const auto duration = nano::measure_robustly_usec([&] ()
{
acc.mode(criterion_t::type::vgrad);
acc.update(task, fold);
}, 1);
log_info() << "<<< processed [" << acc.count()
<< "] backward samples in " << duration.count() << " us.";
brow << idiv(static_cast<size_t>(duration.count()), acc.count());
btimings[nthreads] = acc.timings();
}
}
// detailed per-component (e.g. per-layer) timing information
const auto print_timings = [&] (table_t& table, const string_t& basename,
const std::vector<model_t::timings_t>& timings)
{
for (const auto& timing0 : timings[cmd_min_nthreads])
{
auto& row = table.append();
row << (basename + timing0.first);
for (size_t nthreads = cmd_min_nthreads; nthreads <= cmd_max_nthreads; ++ nthreads)
{
const auto& timingT = timings[nthreads];
assert(timingT.find(timing0.first) != timingT.end());
row << timingT.find(timing0.first)->second.avg();
}
}
};
if (cmd_forward && cmd_detailed)
{
print_timings(ftable, ">", ftimings);
}
if (cmd_backward && cmd_detailed)
{
print_timings(btable, ">", btimings);
}
}
// print results
if (cmd_forward)
{
ftable.mark(nano::make_table_mark_minimum_percentage_cols<size_t>(5));
std::cout << ftable;
}
if (cmd_backward)
{
btable.mark(nano::make_table_mark_minimum_percentage_cols<size_t>(5));
std::cout << btable;
}
// OK
log_info() << done;
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include "db_url.h"
#include <boost/regex.hpp>
using namespace boost;
using namespace boost::program_options;
inline int DbUrl::from_hex(char ch) {
if (ch >= '0' && ch <= '9') {
return (ch - '0');
} else if (ch >= 'a' && ch <= 'f') {
return (ch - 'a' + 10);
} else if (ch >= 'A' && ch <= 'F') {
return (ch - 'A' + 10);
} else {
return -1;
}
}
string DbUrl::urldecode(const string &str) {
string result;
result.reserve(str.length()); // optimization
string::const_iterator it = str.begin();
string::const_iterator end = str.end();
while (it != end) {
if (*it == '%') {
// escape sequence
int digit1 = from_hex(*(++it));
if (digit1 >= 0) {
int digit2 = from_hex(*(++it));
if (digit2 >= 0) {
// valid hex escape, store the decoded character
result += digit1 * 16 + digit2;
// loop around and carry on with the next digit
++it;
continue;
} else {
// invalid escape sequence, copy the % through as a literal, and go back a place to copy the first hex digit
result += '%';
--it;
// fall through to copy the first hex digit as a literal
}
} else {
// invalid escape sequence, copy the % through as a literal
result += '%';
// fall through to copy the first hex digit as a literal
}
}
// normal character
result += *(it++);
}
return result;
}
void validate(
boost::any& v,
const vector<string>& values,
DbUrl* target_type,
int _dummy) {
// vendor://[user[:pass]@]hostname[:port]/database
static regex r("^(\\w+)://(?:([^:]+)(?::([^@]+))?@)?([^:/]+)(?::(.+))?/([^/]+)$");
validators::check_first_occurrence(v);
smatch match;
if (regex_match(validators::get_single_string(values), match, r)) {
// FUTURE: implement percent-decoding
v = any(DbUrl(
DbUrl::urldecode(match[1]),
DbUrl::urldecode(match[2]),
DbUrl::urldecode(match[3]),
DbUrl::urldecode(match[4]),
DbUrl::urldecode(match[5]),
DbUrl::urldecode(match[6])));
} else {
throw validation_error(validation_error::invalid_option_value);
}
}
<commit_msg>remove a FUTURE that actually got done ages ago<commit_after>#include "db_url.h"
#include <boost/regex.hpp>
using namespace boost;
using namespace boost::program_options;
inline int DbUrl::from_hex(char ch) {
if (ch >= '0' && ch <= '9') {
return (ch - '0');
} else if (ch >= 'a' && ch <= 'f') {
return (ch - 'a' + 10);
} else if (ch >= 'A' && ch <= 'F') {
return (ch - 'A' + 10);
} else {
return -1;
}
}
string DbUrl::urldecode(const string &str) {
string result;
result.reserve(str.length()); // optimization
string::const_iterator it = str.begin();
string::const_iterator end = str.end();
while (it != end) {
if (*it == '%') {
// escape sequence
int digit1 = from_hex(*(++it));
if (digit1 >= 0) {
int digit2 = from_hex(*(++it));
if (digit2 >= 0) {
// valid hex escape, store the decoded character
result += digit1 * 16 + digit2;
// loop around and carry on with the next digit
++it;
continue;
} else {
// invalid escape sequence, copy the % through as a literal, and go back a place to copy the first hex digit
result += '%';
--it;
// fall through to copy the first hex digit as a literal
}
} else {
// invalid escape sequence, copy the % through as a literal
result += '%';
// fall through to copy the first hex digit as a literal
}
}
// normal character
result += *(it++);
}
return result;
}
void validate(
boost::any& v,
const vector<string>& values,
DbUrl* target_type,
int _dummy) {
// vendor://[user[:pass]@]hostname[:port]/database
static regex r("^(\\w+)://(?:([^:]+)(?::([^@]+))?@)?([^:/]+)(?::(.+))?/([^/]+)$");
validators::check_first_occurrence(v);
smatch match;
if (regex_match(validators::get_single_string(values), match, r)) {
v = any(DbUrl(
DbUrl::urldecode(match[1]),
DbUrl::urldecode(match[2]),
DbUrl::urldecode(match[3]),
DbUrl::urldecode(match[4]),
DbUrl::urldecode(match[5]),
DbUrl::urldecode(match[6])));
} else {
throw validation_error(validation_error::invalid_option_value);
}
}
<|endoftext|>
|
<commit_before>#ifndef __STAN__MATH__ERROR_HANDLING__MATRIX__CHECK_POS_DEFINITE_HPP__
#define __STAN__MATH__ERROR_HANDLING__MATRIX__CHECK_POS_DEFINITE_HPP__
#include <sstream>
#include <stan/math/matrix/Eigen.hpp>
#include <stan/math/error_handling/default_policy.hpp>
#include <stan/math/error_handling/raise_domain_error.hpp>
#include <stan/math/error_handling/matrix/constraint_tolerance.hpp>
namespace stan {
namespace math {
/**
* Return <code>true</code> if the specified matrix is positive definite
*
* NOTE: symmetry is NOT checked by this function
*
* @param function
* @param y Matrix to test.
* @param name
* @param result
* @return <code>true</code> if the matrix is positive definite.
* @tparam T Type of scalar.
*/
// FIXME: update warnings (message has (0,0) item)
template <typename T_y, typename T_result, class Policy>
inline bool check_pos_definite(const char* function,
const Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic>& y,
const char* name,
T_result* result,
const Policy&) {
typedef
typename Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic>::size_type
size_type;
if (y.rows() == 1 && y(0,0) <= CONSTRAINT_TOLERANCE) {
std::ostringstream message;
message << name << " is not positive definite. "
<< name << "(0,0) is %1%.";
T_result tmp = policies::raise_domain_error<T_y>(function,
message.str().c_str(),
y(0,0), Policy());
if (result != 0)
*result = tmp;
return false;
}
Eigen::LDLT< Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic> > cholesky
= y.ldlt();
if((cholesky.vectorD().array() <= CONSTRAINT_TOLERANCE).any()) {
std::ostringstream message;
message << name << " is not positive definite. "
<< name << "(0,0) is %1%.";
T_result tmp = policies::raise_domain_error<T_y>(function,
message.str().c_str(),
y(0,0), Policy());
if (result != 0)
*result = tmp;
return false;
}
return true;
}
template <typename T_y, typename T_result>
inline bool check_pos_definite(const char* function,
const Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic>& y,
const char* name,
T_result* result) {
return check_pos_definite(function,y,name,result,default_policy());
}
template <typename T>
inline bool check_pos_definite(const char* function,
const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>& y,
const char* name,
T* result = 0) {
return check_pos_definite(function,y,name,result,default_policy());
}
}
}
#endif
<commit_msg>Small tweak/improvement to check_pos_definite.<commit_after>#ifndef __STAN__MATH__ERROR_HANDLING__MATRIX__CHECK_POS_DEFINITE_HPP__
#define __STAN__MATH__ERROR_HANDLING__MATRIX__CHECK_POS_DEFINITE_HPP__
#include <sstream>
#include <stan/math/matrix/Eigen.hpp>
#include <stan/math/error_handling/default_policy.hpp>
#include <stan/math/error_handling/raise_domain_error.hpp>
#include <stan/math/error_handling/matrix/constraint_tolerance.hpp>
namespace stan {
namespace math {
/**
* Return <code>true</code> if the specified matrix is positive definite
*
* NOTE: symmetry is NOT checked by this function
*
* @param function
* @param y Matrix to test.
* @param name
* @param result
* @return <code>true</code> if the matrix is positive definite.
* @tparam T Type of scalar.
*/
// FIXME: update warnings (message has (0,0) item)
template <typename T_y, typename T_result, class Policy>
inline bool check_pos_definite(const char* function,
const Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic>& y,
const char* name,
T_result* result,
const Policy&) {
typedef
typename Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic>::size_type
size_type;
if (y.rows() == 1 && y(0,0) <= CONSTRAINT_TOLERANCE) {
std::ostringstream message;
message << name << " is not positive definite. "
<< name << "(0,0) is %1%.";
T_result tmp = policies::raise_domain_error<T_y>(function,
message.str().c_str(),
y(0,0), Policy());
if (result != 0)
*result = tmp;
return false;
}
Eigen::LDLT< Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic> > cholesky
= y.ldlt();
if(cholesky.info() != Eigen::Success ||
cholesky.isNegative() ||
(cholesky.vectorD().array() <= CONSTRAINT_TOLERANCE).any()) {
std::ostringstream message;
message << name << " is not positive definite. "
<< name << "(0,0) is %1%.";
T_result tmp = policies::raise_domain_error<T_y>(function,
message.str().c_str(),
y(0,0), Policy());
if (result != 0)
*result = tmp;
return false;
}
return true;
}
template <typename T_y, typename T_result>
inline bool check_pos_definite(const char* function,
const Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic>& y,
const char* name,
T_result* result) {
return check_pos_definite(function,y,name,result,default_policy());
}
template <typename T>
inline bool check_pos_definite(const char* function,
const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>& y,
const char* name,
T* result = 0) {
return check_pos_definite(function,y,name,result,default_policy());
}
}
}
#endif
<|endoftext|>
|
<commit_before>#include "profileshow.hpp"
#include "screenrect.hpp"
#include "dwrapper.hpp"
#include "../gameloophelper.hpp"
#include <iomanip>
namespace rs {
namespace util {
// ---------------------- ProfileShow::St_Default ----------------------
struct ProfileShow::St_Default : StateT<St_Default> {
WindowRect* pRect;
void onConnected(ProfileShow& self, HGroup /*hGroup*/) override {
auto* dg = self._hDg->get();
{
auto fn = [](const auto& t, IEffect& e) { t.draw(e); };
auto hlp = rs_mgr_obj.makeDrawable<DWrapper<WindowRect>>(fn, self._idRect, HDGroup());
hlp.second->setColor({0,0,1});
hlp.second->setAlpha(0.5f);
dg->addObj(hlp.first);
pRect = hlp.second;
}
dg->addObj(self.handleFromThis());
}
void onDisconnected(ProfileShow& self, HGroup /*hGroup*/) override {
auto* dg = self._hDg->get();
dg->remObj(self.handleFromThis());
}
void onDraw(const ProfileShow& self, IEffect& e) const override {
if(self._spProfile) {
std::stringstream ss;
ss.precision(2);
ss << std::setfill('0') << std::setw(5);
auto& hist = spn::profiler.getIntervalHistory();
self._spProfile->iterateDepthFirst<false>([&ss, &hist](const spn::Profiler::Block& nd, int depth){
auto us = nd.hist.tAccum - nd.getLowerTime();
for(int i=0 ; i<depth ; i++)
ss << "---";
int tavg = 0;
if(hist.count(nd.layerHistId) > 0) {
tavg = hist.at(nd.layerHistId).getAverageTime().count();
}
std::string s = (boost::format("%1%: %2$2.2fms,%|30t|N=%3%,%|40t|Avg=%4%") % nd.name % ((us.count()/10)/100.f) % nd.hist.nCalled % tavg).str();
ss << s << std::endl;
return spn::Iterate::StepIn;
});
e.setTechPassId(self._idText);
const_cast<ProfileShow&>(self)._textHud.setText(ss.str());
self._textHud.draw(e);
}
}
void onUpdate(ProfileShow& self, const SPLua& /*ls*/) override {
// プロファイラの(1フレーム前の)情報を取得
self._spProfile = spn::profiler.getRoot();
auto sz = self._textHud.getText()->getSize();
pRect->setScale({sz.width, -sz.height});
pRect->setOffset(self._offset);
}
};
// ---------------------- ProfileShow ----------------------
ProfileShow::ProfileShow(IdValue idText, IdValue idRect, CCoreID cid, HDGroup hDg, Priority uprio, Priority dprio):
_idText(idText),
_idRect(idRect),
_hDg(hDg),
_uprio(uprio),
_offset(0)
{
_dtag.priority = dprio;
_textHud.setCCoreId(cid);
_textHud.setScreenOffset({-1,0});
_textHud.setDepth(0.f);
setStateNew<St_Default>();
}
void ProfileShow::setOffset(const spn::Vec2& ofs) {
_offset = ofs;
_textHud.setWindowOffset(ofs);
}
Priority ProfileShow::getPriority() const {
return _uprio;
}
}
}
<commit_msg>ProfileShow: 背景の矩形の優先順序を調整<commit_after>#include "profileshow.hpp"
#include "screenrect.hpp"
#include "dwrapper.hpp"
#include "../gameloophelper.hpp"
#include <iomanip>
namespace rs {
namespace util {
// ---------------------- ProfileShow::St_Default ----------------------
struct ProfileShow::St_Default : StateT<St_Default> {
WindowRect* pRect;
void onConnected(ProfileShow& self, HGroup /*hGroup*/) override {
auto* dg = self._hDg->get();
{
auto fn = [](const auto& t, IEffect& e) { t.draw(e); };
auto hlp = rs_mgr_obj.makeDrawable<DWrapper<WindowRect>>(fn, self._idRect, HDGroup());
hlp.second->setColor({0,0,1});
hlp.second->setAlpha(0.5f);
hlp.second->setDepth(1.f);
hlp.second->setPriority(self._dtag.priority-1);
dg->addObj(hlp.first);
pRect = hlp.second;
}
dg->addObj(self.handleFromThis());
}
void onDisconnected(ProfileShow& self, HGroup /*hGroup*/) override {
auto* dg = self._hDg->get();
dg->remObj(self.handleFromThis());
}
void onDraw(const ProfileShow& self, IEffect& e) const override {
if(self._spProfile) {
std::stringstream ss;
ss.precision(2);
ss << std::setfill('0') << std::setw(5);
auto& hist = spn::profiler.getIntervalHistory();
self._spProfile->iterateDepthFirst<false>([&ss, &hist](const spn::Profiler::Block& nd, int depth){
auto us = nd.hist.tAccum - nd.getLowerTime();
for(int i=0 ; i<depth ; i++)
ss << "---";
int tavg = 0;
if(hist.count(nd.layerHistId) > 0) {
tavg = hist.at(nd.layerHistId).getAverageTime().count();
}
std::string s = (boost::format("%1%: %2$2.2fms,%|30t|N=%3%,%|40t|Avg=%4%") % nd.name % ((us.count()/10)/100.f) % nd.hist.nCalled % tavg).str();
ss << s << std::endl;
return spn::Iterate::StepIn;
});
e.setTechPassId(self._idText);
const_cast<ProfileShow&>(self)._textHud.setText(ss.str());
self._textHud.draw(e);
}
}
void onUpdate(ProfileShow& self, const SPLua& /*ls*/) override {
// プロファイラの(1フレーム前の)情報を取得
self._spProfile = spn::profiler.getRoot();
auto sz = self._textHud.getText()->getSize();
pRect->setScale({sz.width, -sz.height});
pRect->setOffset(self._offset);
}
};
// ---------------------- ProfileShow ----------------------
ProfileShow::ProfileShow(IdValue idText, IdValue idRect, CCoreID cid, HDGroup hDg, Priority uprio, Priority dprio):
_idText(idText),
_idRect(idRect),
_hDg(hDg),
_uprio(uprio),
_offset(0)
{
_dtag.priority = dprio;
_textHud.setCCoreId(cid);
_textHud.setScreenOffset({-1,0});
_textHud.setDepth(0.f);
setStateNew<St_Default>();
}
void ProfileShow::setOffset(const spn::Vec2& ofs) {
_offset = ofs;
_textHud.setWindowOffset(ofs);
}
Priority ProfileShow::getPriority() const {
return _uprio;
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2014 Cloudius Systems
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef UTILS_DATA_OUTPUT_HH_
#define UTILS_DATA_OUTPUT_HH_
#include "bytes.hh"
#include "net/byteorder.hh"
/**
* Data output interface for Java-esqe wire serialization of
* basic type, including strings and bytes. The latter I've opted
* to keep for a few reasons:
* 1.) It matches better with data_input.read<sstring>, which in turn
* is somewhat meaningful because it can create a string more efficiently
* without adding another slightly contrived abstraction (iterators?)
* 2.) At some point this interface should maybe be extended to support stream-like
* underlying mediums (such as a back_insert iterator etc), at which point
* having to know the exact size of what it being serialized becomes less of an
* issue.
*/
class data_output {
public:
data_output(char* p, char* e)
: _ptr(p), _end(e) {
}
data_output(char* p, size_t n)
: data_output(p, p + n) {
}
data_output(bytes& b)
: data_output(reinterpret_cast<char*>(b.begin()), b.size()) {
}
data_output(bytes& b, size_t off, size_t n = bytes::npos)
: data_output(reinterpret_cast<char*>(b.begin()) + off,
reinterpret_cast<char*>(b.begin()) + off + std::min(b.size() - off, n)) {
if (off > b.size()) {
throw std::out_of_range("Offset out of range");
}
}
template<typename T>
static inline std::enable_if_t<std::is_fundamental<T>::value, size_t> serialized_size(const T&) {
return sizeof(T);
}
template<typename T>
static inline std::enable_if_t<std::is_fundamental<T>::value, size_t> serialized_size() {
return sizeof(T);
}
template<typename SizeType = uint16_t>
static inline size_t serialized_size(const sstring& s) {
if (s.size() > std::numeric_limits<SizeType>::max()) {
throw std::out_of_range("String too large");
}
return sizeof(SizeType) + s.size();
}
template<typename SizeType = uint32_t>
static inline size_t serialized_size(const bytes_view& s) {
if (s.size() > std::numeric_limits<SizeType>::max()) {
throw std::out_of_range("Buffer too large");
}
return sizeof(SizeType) + s.size();
}
template<typename SizeType = uint32_t>
static inline size_t serialized_size(const bytes& s) {
return serialized_size<SizeType>(bytes_view(s));
}
size_t avail() const {
return _end - _ptr;
}
void ensure(size_t s) const {
if (avail() < s) {
throw std::out_of_range("Buffer overflow");
}
}
data_output& skip(size_t s) {
ensure(s);
_ptr += s;
return *this;
}
template<typename T>
inline std::enable_if_t<std::is_fundamental<T>::value, data_output&> write(T t);
template<typename SizeType = uint16_t>
data_output& write(const sstring& s) {
ensure(serialized_size<SizeType>(s));
write(SizeType(s.size()));
_ptr = std::copy(s.begin(), s.end(), _ptr);
return *this;
}
template<typename SizeType = uint32_t>
data_output& write(const bytes_view& s) {
ensure(serialized_size<SizeType>(s));
write(SizeType(s.size()));
_ptr = std::copy(s.begin(), s.end(), _ptr);
return *this;
}
template<typename SizeType = uint32_t>
data_output& write(const bytes & s) {
return write<SizeType>(bytes_view(s));
}
template<typename Iter>
data_output& write(Iter s, Iter e) {
while (s != e) {
write(*s++);
}
return *this;
}
data_output& write(const char* s, const char* e) {
ensure(e - s);
_ptr = std::copy(s, e, _ptr);
return *this;
}
template<typename T>
data_output& write(T t, size_t n) {
while (n-- > 0) {
write(t);
}
return *this;
}
data_output& write_view(bytes_view v) {
return write(v.begin(), v.end());
}
private:
char * _ptr;
char * _end;
};
template<>
inline data_output& data_output::write(bool b) {
return write<uint8_t>(b);
}
template<>
inline data_output& data_output::write(char c) {
ensure(1);
*_ptr++ = c;
return *this;
}
template<typename T>
inline std::enable_if_t<std::is_fundamental<T>::value, data_output&> data_output::write(
T t) {
ensure(sizeof(T));
*reinterpret_cast<net::packed<T> *>(_ptr) = net::hton(t);
_ptr += sizeof(T);
return *this;
}
#endif /* UTILS_DATA_OUTPUT_HH_ */
<commit_msg>data_output: specialize serialized_size for bool to ensure sync with write<commit_after>/*
* Copyright 2014 Cloudius Systems
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef UTILS_DATA_OUTPUT_HH_
#define UTILS_DATA_OUTPUT_HH_
#include "bytes.hh"
#include "net/byteorder.hh"
/**
* Data output interface for Java-esqe wire serialization of
* basic type, including strings and bytes. The latter I've opted
* to keep for a few reasons:
* 1.) It matches better with data_input.read<sstring>, which in turn
* is somewhat meaningful because it can create a string more efficiently
* without adding another slightly contrived abstraction (iterators?)
* 2.) At some point this interface should maybe be extended to support stream-like
* underlying mediums (such as a back_insert iterator etc), at which point
* having to know the exact size of what it being serialized becomes less of an
* issue.
*/
class data_output {
public:
data_output(char* p, char* e)
: _ptr(p), _end(e) {
}
data_output(char* p, size_t n)
: data_output(p, p + n) {
}
data_output(bytes& b)
: data_output(reinterpret_cast<char*>(b.begin()), b.size()) {
}
data_output(bytes& b, size_t off, size_t n = bytes::npos)
: data_output(reinterpret_cast<char*>(b.begin()) + off,
reinterpret_cast<char*>(b.begin()) + off + std::min(b.size() - off, n)) {
if (off > b.size()) {
throw std::out_of_range("Offset out of range");
}
}
template<typename T>
static inline std::enable_if_t<std::is_fundamental<T>::value, size_t> serialized_size(const T&);
template<typename T>
static inline std::enable_if_t<std::is_fundamental<T>::value, size_t> serialized_size();
template<typename SizeType = uint16_t>
static inline size_t serialized_size(const sstring& s) {
if (s.size() > std::numeric_limits<SizeType>::max()) {
throw std::out_of_range("String too large");
}
return sizeof(SizeType) + s.size();
}
template<typename SizeType = uint32_t>
static inline size_t serialized_size(const bytes_view& s) {
if (s.size() > std::numeric_limits<SizeType>::max()) {
throw std::out_of_range("Buffer too large");
}
return sizeof(SizeType) + s.size();
}
template<typename SizeType = uint32_t>
static inline size_t serialized_size(const bytes& s) {
return serialized_size<SizeType>(bytes_view(s));
}
size_t avail() const {
return _end - _ptr;
}
void ensure(size_t s) const {
if (avail() < s) {
throw std::out_of_range("Buffer overflow");
}
}
data_output& skip(size_t s) {
ensure(s);
_ptr += s;
return *this;
}
template<typename T>
inline std::enable_if_t<std::is_fundamental<T>::value, data_output&> write(T t);
template<typename SizeType = uint16_t>
data_output& write(const sstring& s) {
ensure(serialized_size<SizeType>(s));
write(SizeType(s.size()));
_ptr = std::copy(s.begin(), s.end(), _ptr);
return *this;
}
template<typename SizeType = uint32_t>
data_output& write(const bytes_view& s) {
ensure(serialized_size<SizeType>(s));
write(SizeType(s.size()));
_ptr = std::copy(s.begin(), s.end(), _ptr);
return *this;
}
template<typename SizeType = uint32_t>
data_output& write(const bytes & s) {
return write<SizeType>(bytes_view(s));
}
template<typename Iter>
data_output& write(Iter s, Iter e) {
while (s != e) {
write(*s++);
}
return *this;
}
data_output& write(const char* s, const char* e) {
ensure(e - s);
_ptr = std::copy(s, e, _ptr);
return *this;
}
template<typename T>
data_output& write(T t, size_t n) {
while (n-- > 0) {
write(t);
}
return *this;
}
data_output& write_view(bytes_view v) {
return write(v.begin(), v.end());
}
private:
char * _ptr;
char * _end;
};
template<>
inline size_t data_output::serialized_size<bool>() {
return sizeof(uint8_t);
}
template<typename T>
inline std::enable_if_t<std::is_fundamental<T>::value, size_t> data_output::serialized_size() {
return sizeof(T);
}
template<typename T>
inline std::enable_if_t<std::is_fundamental<T>::value, size_t> data_output::serialized_size(const T&) {
return serialized_size<T>();
}
template<>
inline data_output& data_output::write(bool b) {
return write<uint8_t>(b);
}
template<>
inline data_output& data_output::write(char c) {
ensure(1);
*_ptr++ = c;
return *this;
}
template<typename T>
inline std::enable_if_t<std::is_fundamental<T>::value, data_output&> data_output::write(
T t) {
ensure(sizeof(T));
*reinterpret_cast<net::packed<T> *>(_ptr) = net::hton(t);
_ptr += sizeof(T);
return *this;
}
#endif /* UTILS_DATA_OUTPUT_HH_ */
<|endoftext|>
|
<commit_before>// Copyright (C) 2015 The Regents of the University of California (Regents).
// 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 Regents or University of California 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 HOLDERS 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.
//
// Please contact the author of this library if you have any questions.
// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)
#include "theia/sfm/extract_maximally_parallel_rigid_subgraph.h"
#include <ceres/rotation.h>
#include <Eigen/Core>
#include <Eigen/LU>
#include <algorithm>
#include <unordered_map>
#include <vector>
#include "theia/sfm/pose/util.h"
#include "theia/sfm/types.h"
#include "theia/sfm/view_graph/view_graph.h"
#include "theia/util/map_util.h"
namespace theia {
namespace {
void FormAngleMeasurementMatrix(
const std::unordered_map<ViewId, Eigen::Vector3d>& orientations,
const ViewGraph& view_graph,
const std::unordered_map<ViewId, int>& view_ids_to_index,
Eigen::MatrixXd* angle_measurements) {
const auto& view_pairs = view_graph.GetAllEdges();
angle_measurements->setZero();
// Set up the matrix such that t_{i,j} x (c_j - c_i) = 0.
int i = 0;
for (const auto& view_pair : view_pairs) {
// Get t_{i,j} and rotate it such that it is oriented in the global
// reference frame.
Eigen::Matrix3d world_to_view1_rotation;
ceres::AngleAxisToRotationMatrix(
FindOrDie(orientations, view_pair.first.first).data(),
ceres::ColumnMajorAdapter3x3(world_to_view1_rotation.data()));
const Eigen::Vector3d rotated_translation =
world_to_view1_rotation.transpose() * view_pair.second.position_2;
const Eigen::Matrix3d cross_product_mat =
CrossProductMatrix(rotated_translation);
// Find the column locations of the two views.
const int view1_col =
3 * FindOrDie(view_ids_to_index, view_pair.first.first);
const int view2_col =
3 * FindOrDie(view_ids_to_index, view_pair.first.second);
angle_measurements->block<3, 3>(3 * i, view1_col) = -cross_product_mat;
angle_measurements->block<3, 3>(3 * i, view2_col) = cross_product_mat;
++i;
}
}
// Computes the cosine distance in each dimension x, y, and z and returns the
// maximum cosine distance.
//
// cos distance = 1.0 - a.dot(b) / (norm(a) * norm(b))
double ComputeCosineDistance(const Eigen::MatrixXd& mat1,
const Eigen::MatrixXd& mat2) {
Eigen::Vector3d cos_distance;
for (int i =0; i < 3; i++) {
cos_distance(i) = 1.0 - std::abs(mat1.row(i).dot(mat2.row(i)));
}
return cos_distance.maxCoeff();
}
// Find the maximal rigid component containing fixed_node. This is done by
// examining which nodes are parallel when removing node fixed_node from the
// null space. The nodes are only parallel if they are part of the maximal rigid
// component with fixed_node.
void FindMaximalParallelRigidComponent(const Eigen::MatrixXd& null_space,
const int fixed_node,
std::unordered_set<int>* largest_cc) {
static const double kMaxCosDistance = 1e-5;
static const double kMaxNorm = 1e-10;
const int num_nodes = null_space.rows() / 3;
largest_cc->insert(fixed_node);
const Eigen::MatrixXd fixed_null_space_component =
null_space.block(3 * fixed_node, 0, 3, null_space.cols());
// Remove the fixed node from the rest of the null space.
Eigen::MatrixXd modified_null_space =
null_space - fixed_null_space_component.replicate(num_nodes, 1);
// Normalize all rows to be unit-norm. If the rows have a very small norm then
// they are parallel to the fixed_node. and should be set to zero.
const Eigen::VectorXd norms = modified_null_space.rowwise().norm();
modified_null_space.rowwise().normalize();
// Find the pairs to match. Add all indices that are close to 0-vectors, as
// they are clearly part of the rigid component.
std::vector<int> indices_to_match;
for (int i = 0; i < num_nodes; i++) {
// Skip this index if it is fixed.
if (i == fixed_node) {
continue;
}
// Skip this index if it is nearly a 0-vector because this means it is
// clearly part of the rigid component.
if (norms(3 * i) < kMaxNorm &&
norms(3 * i + 1) < kMaxNorm &&
norms(3 * i + 2) < kMaxNorm) {
largest_cc->insert(i);
continue;
}
indices_to_match.emplace_back(i);
}
// Each node has three dimensions (x, y, z). We only compare parallel-ness
// between similar dimensions. If all x, y, z dimensions are parallel then
// the two nodes will be parallel.
for (int i = 0; i < indices_to_match.size(); i++) {
// Test all other nodes (that have not been tested) to determine if they are
// parallel to this node.
const Eigen::MatrixXd& block1 = modified_null_space.block(
3 * indices_to_match[i], 0, 3, null_space.cols());
for (int j = i + 1; j < indices_to_match.size(); j++) {
const Eigen::MatrixXd& block2 = modified_null_space.block(
3 * indices_to_match[j], 0, 3, null_space.cols());
const double cos_distance = ComputeCosineDistance(block1, block2);
if (cos_distance < kMaxCosDistance) {
largest_cc->insert(indices_to_match[i]);
largest_cc->insert(indices_to_match[j]);
}
}
}
}
} // namespace
void ExtractMaximallyParallelRigidSubgraph(
const std::unordered_map<ViewId, Eigen::Vector3d>& orientations,
ViewGraph* view_graph) {
// Create a mapping of indexes to ViewIds for our linear system.
std::unordered_map<ViewId, int> view_ids_to_index;
view_ids_to_index.reserve(orientations.size());
for (const auto& orientation : orientations) {
const int current_index = view_ids_to_index.size();
InsertIfNotPresent(&view_ids_to_index, orientation.first, current_index);
}
// Form the global angle measurements matrix from:
// t_{i,j} x (c_j - c_i) = 0.
Eigen::MatrixXd angle_measurements(3 * view_graph->NumEdges(),
3 * orientations.size());
FormAngleMeasurementMatrix(orientations,
*view_graph,
view_ids_to_index,
&angle_measurements);
// Extract the null space of the angle measurements matrix.
Eigen::FullPivLU<Eigen::MatrixXd> lu(angle_measurements.transpose() *
angle_measurements);
const Eigen::MatrixXd null_space = lu.kernel();
// For each node in the graph (i.e. each camera), set the null space component
// to be zero such that the camera position would be fixed at the origin. If
// two nodes i and j are in the same rigid component, then their null spaces
// will be parallel because the camera positions may only change by a
// scale. We find all components that are parallel to find the rigid
// components. The largest of such component is the maximally parallel rigid
// component of the graph.
std::unordered_set<int> maximal_rigid_component;
for (int i = 0; i < orientations.size(); i++) {
std::unordered_set<int> temp_cc;
FindMaximalParallelRigidComponent(null_space, i, &temp_cc);
if (temp_cc.size() > maximal_rigid_component.size()) {
std::swap(temp_cc, maximal_rigid_component);
}
}
// Only keep the nodes in the largest maximally parallel rigid component.
for (const auto& orientation : orientations) {
const int index = FindOrDie(view_ids_to_index, orientation.first);
// If the view is not in the maximal rigid component then remove it from the
// view graph.
if (!ContainsKey(maximal_rigid_component, index)) {
CHECK(view_graph->RemoveView(orientation.first))
<< "Could not remove view id " << orientation.first
<< " from the view graph because it does not exist.";
}
}
}
} // namespace theia
<commit_msg>Bug fix: do not consider views that are not in the view graph<commit_after>// Copyright (C) 2015 The Regents of the University of California (Regents).
// 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 Regents or University of California 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 HOLDERS 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.
//
// Please contact the author of this library if you have any questions.
// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)
#include "theia/sfm/extract_maximally_parallel_rigid_subgraph.h"
#include <ceres/rotation.h>
#include <Eigen/Core>
#include <Eigen/LU>
#include <algorithm>
#include <unordered_map>
#include <vector>
#include "theia/sfm/pose/util.h"
#include "theia/sfm/types.h"
#include "theia/sfm/view_graph/view_graph.h"
#include "theia/util/map_util.h"
namespace theia {
namespace {
void FormAngleMeasurementMatrix(
const std::unordered_map<ViewId, Eigen::Vector3d>& orientations,
const ViewGraph& view_graph,
const std::unordered_map<ViewId, int>& view_ids_to_index,
Eigen::MatrixXd* angle_measurements) {
const auto& view_pairs = view_graph.GetAllEdges();
angle_measurements->setZero();
// Set up the matrix such that t_{i,j} x (c_j - c_i) = 0.
int i = 0;
for (const auto& view_pair : view_pairs) {
// Get t_{i,j} and rotate it such that it is oriented in the global
// reference frame.
Eigen::Matrix3d world_to_view1_rotation;
ceres::AngleAxisToRotationMatrix(
FindOrDie(orientations, view_pair.first.first).data(),
ceres::ColumnMajorAdapter3x3(world_to_view1_rotation.data()));
const Eigen::Vector3d rotated_translation =
world_to_view1_rotation.transpose() * view_pair.second.position_2;
const Eigen::Matrix3d cross_product_mat =
CrossProductMatrix(rotated_translation);
// Find the column locations of the two views.
const int view1_col =
3 * FindOrDie(view_ids_to_index, view_pair.first.first);
const int view2_col =
3 * FindOrDie(view_ids_to_index, view_pair.first.second);
angle_measurements->block<3, 3>(3 * i, view1_col) = -cross_product_mat;
angle_measurements->block<3, 3>(3 * i, view2_col) = cross_product_mat;
++i;
}
}
// Computes the cosine distance in each dimension x, y, and z and returns the
// maximum cosine distance.
//
// cos distance = 1.0 - a.dot(b) / (norm(a) * norm(b))
double ComputeCosineDistance(const Eigen::MatrixXd& mat1,
const Eigen::MatrixXd& mat2) {
Eigen::Vector3d cos_distance;
for (int i =0; i < 3; i++) {
cos_distance(i) = 1.0 - std::abs(mat1.row(i).dot(mat2.row(i)));
}
return cos_distance.maxCoeff();
}
// Find the maximal rigid component containing fixed_node. This is done by
// examining which nodes are parallel when removing node fixed_node from the
// null space. The nodes are only parallel if they are part of the maximal rigid
// component with fixed_node.
void FindMaximalParallelRigidComponent(const Eigen::MatrixXd& null_space,
const int fixed_node,
std::unordered_set<int>* largest_cc) {
static const double kMaxCosDistance = 1e-5;
static const double kMaxNorm = 1e-10;
const int num_nodes = null_space.rows() / 3;
largest_cc->insert(fixed_node);
const Eigen::MatrixXd fixed_null_space_component =
null_space.block(3 * fixed_node, 0, 3, null_space.cols());
// Remove the fixed node from the rest of the null space.
Eigen::MatrixXd modified_null_space =
null_space - fixed_null_space_component.replicate(num_nodes, 1);
// Normalize all rows to be unit-norm. If the rows have a very small norm then
// they are parallel to the fixed_node. and should be set to zero.
const Eigen::VectorXd norms = modified_null_space.rowwise().norm();
modified_null_space.rowwise().normalize();
// Find the pairs to match. Add all indices that are close to 0-vectors, as
// they are clearly part of the rigid component.
std::vector<int> indices_to_match;
for (int i = 0; i < num_nodes; i++) {
// Skip this index if it is fixed.
if (i == fixed_node) {
continue;
}
// Skip this index if it is nearly a 0-vector because this means it is
// clearly part of the rigid component.
if (norms(3 * i) < kMaxNorm &&
norms(3 * i + 1) < kMaxNorm &&
norms(3 * i + 2) < kMaxNorm) {
largest_cc->insert(i);
continue;
}
indices_to_match.emplace_back(i);
}
// Each node has three dimensions (x, y, z). We only compare parallel-ness
// between similar dimensions. If all x, y, z dimensions are parallel then
// the two nodes will be parallel.
for (int i = 0; i < indices_to_match.size(); i++) {
// Test all other nodes (that have not been tested) to determine if they are
// parallel to this node.
const Eigen::MatrixXd& block1 = modified_null_space.block(
3 * indices_to_match[i], 0, 3, null_space.cols());
for (int j = i + 1; j < indices_to_match.size(); j++) {
const Eigen::MatrixXd& block2 = modified_null_space.block(
3 * indices_to_match[j], 0, 3, null_space.cols());
const double cos_distance = ComputeCosineDistance(block1, block2);
if (cos_distance < kMaxCosDistance) {
largest_cc->insert(indices_to_match[i]);
largest_cc->insert(indices_to_match[j]);
}
}
}
}
} // namespace
void ExtractMaximallyParallelRigidSubgraph(
const std::unordered_map<ViewId, Eigen::Vector3d>& orientations,
ViewGraph* view_graph) {
// Create a mapping of indexes to ViewIds for our linear system.
std::unordered_map<ViewId, int> view_ids_to_index;
view_ids_to_index.reserve(orientations.size());
for (const auto& orientation : orientations) {
if (!view_graph->HasView(orientation.first)) {
continue;
}
const int current_index = view_ids_to_index.size();
InsertIfNotPresent(&view_ids_to_index, orientation.first, current_index);
}
// Form the global angle measurements matrix from:
// t_{i,j} x (c_j - c_i) = 0.
Eigen::MatrixXd angle_measurements(3 * view_graph->NumEdges(),
3 * orientations.size());
FormAngleMeasurementMatrix(orientations,
*view_graph,
view_ids_to_index,
&angle_measurements);
// Extract the null space of the angle measurements matrix.
Eigen::FullPivLU<Eigen::MatrixXd> lu(angle_measurements.transpose() *
angle_measurements);
const Eigen::MatrixXd null_space = lu.kernel();
// For each node in the graph (i.e. each camera), set the null space component
// to be zero such that the camera position would be fixed at the origin. If
// two nodes i and j are in the same rigid component, then their null spaces
// will be parallel because the camera positions may only change by a
// scale. We find all components that are parallel to find the rigid
// components. The largest of such component is the maximally parallel rigid
// component of the graph.
std::unordered_set<int> maximal_rigid_component;
for (int i = 0; i < orientations.size(); i++) {
std::unordered_set<int> temp_cc;
FindMaximalParallelRigidComponent(null_space, i, &temp_cc);
if (temp_cc.size() > maximal_rigid_component.size()) {
std::swap(temp_cc, maximal_rigid_component);
}
}
// Only keep the nodes in the largest maximally parallel rigid component.
for (const auto& orientation : orientations) {
const int index = FindOrDie(view_ids_to_index, orientation.first);
// If the view is not in the maximal rigid component then remove it from the
// view graph.
if (!ContainsKey(maximal_rigid_component, index) &&
view_graph->HasView(orientation.first)) {
CHECK(view_graph->RemoveView(orientation.first))
<< "Could not remove view id " << orientation.first
<< " from the view graph because it does not exist.";
}
}
}
} // namespace theia
<|endoftext|>
|
<commit_before>/*
* ascutil.cpp
*
* Arduino Solar Controller
*
* by karldm, March 2016
*/
#include "ascutil.h"
#define FUN_NAME_SIZE 20
#define MES_BUF_SIZE 40
static char activefname[] = "ASC"; // id on console messages
static char mesbuf[MES_BUF_SIZE];
/*
* #####
* Timer
* #####
*
* declare Timer timer( delay)
* timer.delay()
* timer.start()
* timer.check()
*
*/
Timer::Timer( unsigned long delayMillis )
{
_delay = delayMillis;
_starTimeMillis = millis(); // start the timer
}
void Timer::start()
{
// reset the timer
_starTimeMillis = millis();
}
bool Timer::check()
{
// check and restart if timeout
bool istimeout;
istimeout = (millis() - _starTimeMillis) > _delay;
if ( istimeout )
{
_starTimeMillis = millis();
}
return( istimeout );
}
bool Timer::check( unsigned long delayMillis )
{
// check if timeout (only)
// require the delay
bool istimeout;
istimeout = (millis() - _starTimeMillis) > delayMillis;
return( istimeout );
}
unsigned long Timer::elapsed()
{
// return elapsed time
return( millis() - _starTimeMillis );
}
/*
* ########
* Counterh
* ########
*
* Cumulative counter in x.hour
* Counter index( unsigned long valueh )
* index.tic() // start or stop
* index.add(x) // x=1 for hours, W for Wh
* index.get()
*/
Counterh::Counterh( unsigned long index )
{
_index = index;
_addedMillis = 0;
_lastSamplingMillis = 0; // last sampling time
_running = false; // use .run to start
}
bool Counterh::run()
{
// activate counting
_running = true;
_lastSamplingMillis = millis(); // so you don't need to call it if not running
return(_running);
}
bool Counterh::stop()
{
// stop counting
_running = false;
_lastSamplingMillis = millis();
return(_running);
}
bool Counterh::tic()
{
// run <-> stop counting
_running = !_running;
_lastSamplingMillis = millis();
return(_running);
}
unsigned long Counterh::set( unsigned long index )
{
// set the counter value
_index = index;
return(_index);
}
unsigned long Counterh::add( unsigned long curvalue )
{
// add and check if index to be increased
// beware! only positive values can be added!
unsigned long intpart;
unsigned long curMillis;
curMillis = millis(); // current time
if ( _running ) {
_addedMillis += curvalue*( curMillis - _lastSamplingMillis);
// check if index is to be incremented
intpart = _addedMillis / ONEHOURMS; // 1 hour in millis
if ( intpart > 0 )
{
_index += intpart;
_addedMillis = _addedMillis % ONEHOURMS;; // keep the millis part
}
}
_lastSamplingMillis = curMillis; // set the last sampling time
return(_index);
}
unsigned long Counterh::get()
{
// get the counter value
return(_index);
}
/*
* Declare the message origin
*/
void SetFname( const char * fname )
{
snprintf( activefname, FUN_NAME_SIZE, "%s", fname );
}
void SetFname( const __FlashStringHelper * fname )
{
// ??? TO CHECK
strcpy_P( activefname, (char *)fname ); // achtung!
}
/*
* ####################
* Various LED controls
* ####################
*/
/*
* Blink a LED once
*/
void LedBlinking(int pin, int delayonms, Timer * timerLED )
{
//
if ( timerLED->check() ) {
digitalWrite( pin, HIGH );
delay( delayonms );
digitalWrite( pin, LOW );
}
}
/*
* Blink a LED N times
*/
void LedBlinkingN(int pin, int delayms, int n )
{
// blink the LED N times with delay()
digitalWrite( pin, LOW ); // begin with LOW
delay( delayms );
for (int i=0; i < n; i++) {
digitalWrite( pin, HIGH );
delay( delayms );
digitalWrite( pin, LOW );
delay( 2*delayms );
}
}
/*
* Glow a LED -- only with PWD~ outputs
*/
void LedGlowing(int pin, int periodms, int minl, int maxl )
{
//
unsigned long i = millis();
unsigned long frac;
int level;
unsigned long j = i % periodms;
if (j > periodms / 2) {
j = periodms - j;
}
frac = minl + 2 * j * (maxl - minl) / periodms;
level = (int) frac;
analogWrite(pin, level );
}
/*
* ###########################################
* Messages and logs on serial port or console
* ###########################################
*
* Console management on Yun
* Call BeginInfo() to open the Console => wait for connection
* do it after Bridge.begin()
* Need to define CONSOLE
*/
/*
* Open the console on Yun
* if CONSOLE is not defined, just do nothing...
*/
void BeginInfo() {
//
#ifdef CONSOLE
Console.begin();
/*
while (!Console) {
; // wait for Console port to connect -- for debug only
}
*/
#endif
}
void PrintInfoDataUsage( int npar, int nparmax ) {
//
#ifdef CONSOLE
Console.print(activefname);
Console.print(",i,Data usage: parameters ");
Console.print( npar );
Console.print("/");
Console.print( nparmax );
Console.print("(");
Console.print( npar*100/nparmax );
Console.println("%)");
#endif
}
void PrintInfo( const char type, const char * message ) {
//
#ifdef CONSOLE
if (type == 'i' || type == 'w' || type == 'd')
{
Console.print(activefname);
Console.print(',');
Console.print(type);
Console.print(',');
Console.println(message);
}
#endif
}
void PrintInfo( const char type, const __FlashStringHelper * message ) {
//
#ifdef CONSOLE
if (type == 'i' || type == 'w' || type == 'd')
{
Console.print(activefname);
Console.print(',');
Console.print(type);
Console.print(',');
Console.println(message);
}
#endif
}
void PrintInfo( const char type, const char * format, const char * val ) {
// print a formatted value
#ifdef CONSOLE
if (type == 'i' || type == 'w' || type == 'd')
{
snprintf( mesbuf, MES_BUF_SIZE, format, val );
Console.print( activefname);
Console.print( ',');
Console.print( type);
Console.print( ',');
Console.println( mesbuf);
}
#endif
}
<commit_msg>Delete ascutil.cpp<commit_after><|endoftext|>
|
<commit_before>// //////////////////////////////////////////////////////////////////////////////////////////
template <const unsigned int d, typename Valid>
typename SHA3 <d, Valid>::StateArray SHA3 <d, Valid>::s2sa(const std::string & S) const {
SHA3 <d, Valid>::StateArray A = {{0}};
for(uint8_t y = 0; y < 5; y++) {
for(uint8_t x = 0; x < 5; x++) {
A[x][y] = toint(little_end(S.substr(w * (5 * y + x), w), 2), 2);
}
}
return A;
}
template <const unsigned int d, typename Valid>
std::string SHA3 <d, Valid>::sa2s(const typename SHA3 <d, Valid>::StateArray & A) const {
std::string S = "";
for(uint8_t j = 0; j < 5; j++) {
for(uint8_t i = 0; i < 5; i++) {
S += little_end(makebin(A[i][j], 64), 2);
}
}
return S;
}
template <const unsigned int d, typename Valid>
typename SHA3 <d, Valid>::StateArray SHA3 <d, Valid>::theta(const typename SHA3 <d, Valid>::StateArray & A) const {
SHA3 <d, Valid>::StateArray Aprime = A;
// step 1
std::array <uint64_t, 5> C;
for(uint8_t x = 0; x < 5; x++) {
C[x] = A[x][0] ^ A[x][1] ^ A[x][2] ^ A[x][3] ^ A[x][4];
}
// step 2
std::array <uint64_t, 5> D;
for(uint8_t x = 0; x < 5; x++) {
D[x] = C[(x + 4) % 5] ^ ROL(C[(x + 1) % 5], 1, 64);
// step 3
for(uint8_t y = 0; y < 5; y++) {
Aprime[x][y] = A[x][y] ^ D[x];
}
}
return Aprime;
}
template <const unsigned int d, typename Valid>
typename SHA3 <d, Valid>::StateArray SHA3 <d, Valid>::pirho(const typename SHA3 <d, Valid>::StateArray & A) const {
SHA3 <d, Valid>::StateArray Aprime;
for(uint8_t x = 0; x < 5; x++) {
for(uint8_t y = 0; y < 5; y++) {
Aprime[y][(2 * x + 3 * y) % 5] = ROL(A[x][y], Keccak_rot[x][y], 64);
}
}
return Aprime;
}
template <const unsigned int d, typename Valid>
typename SHA3 <d, Valid>::StateArray SHA3 <d, Valid>::chi(const typename SHA3 <d, Valid>::StateArray & A) const {
SHA3 <d, Valid>::StateArray Aprime = A;
for(uint8_t x = 0; x < 5; x++) {
for(uint8_t y = 0; y < 5; y++) {
Aprime[x][y] = A[x][y] ^ ((~A[(x + 1) % 5][y]) & A[(x + 2) % 5][y]);
}
}
return Aprime;
}
template <const unsigned int d, typename Valid>
typename SHA3 <d, Valid>::StateArray SHA3 <d, Valid>::iota(const typename SHA3 <d, Valid>::StateArray & A, const uint64_t rc) const {
SHA3 <d, Valid>::StateArray Aprime = A;
Aprime[0][0] ^= rc;
return Aprime;
}
// assumes S is already in binary
template <const unsigned int d, typename Valid>
typename std::string SHA3 <d, Valid>::f(const std::string & S) const {
SHA3 <d, Valid>::StateArray A = s2sa(S);
for(unsigned int i = 0; i < nr; i++) {
A = iota(chi(pirho(theta(A))), Keccak_RC[i]);
}
return sa2s(A);
}
// //////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
// absorb data into given state
template <const unsigned int d, typename Valid>
void SHA3 <d, Valid>::absorb(std::string & S, const std::string & P) const {
for(unsigned int i = 0; i < P.size(); i += r) {
for(int j = 0; j < r; j++) {
S[j] = (P[i + j] ^ S[j]) | '0';
}
S = f(S);
}
}
// squeeze output data (concatenate results of f)
template <const unsigned int d, typename Valid>
std::string SHA3 <d, Valid>::squeeze(std::string & S) const {
std::string Z = "";
while (d > Z.size()) {
Z += S.substr(0, r);
S = f(S);
}
return Z.substr(0, d);
}
template <const unsigned int d, typename Valid>
SHA3 <d, Valid>::SHA3()
: HashAlg(),
b(1600), w(64), l(6), nr(24),
state((size_t) 1600, (char) '0'), stack(""),
r(1600 - (d << 1))
{}
template <const unsigned int d, typename Valid>
SHA3 <d, Valid>::SHA3(const std::string & M)
: SHA3()
{
update(M);
}
template <const unsigned int d, typename Valid>
void SHA3 <d, Valid>::update(const std::string & M) {
// process old leftover data + new data up to last full block
std::string data = stack + binify(M);
absorb(state, data.substr(0, (data.size() / r) * r));
// clear old stack (in case new data does not have partial blocks)
stack = "";
// extract last block of M
if (unsigned int rem = data.size() % r) {
stack = data.substr(data.size() - rem, rem);
}
}
template <const unsigned int d, typename Valid>
std::string SHA3 <d, Valid>::digest() {
// pad10*1 embedded here ////////////////////////////
std::string m = stack + "00000110";
int pad_size = (-static_cast <int> (m.size()) - 1) % r;
pad_size = (pad_size + r) % r;
m += std::string(pad_size - 7, '0') + "10000000";
// //////////////////////////////////////////////////
// copy state and process on that instead of actual state
std::string S = state;
absorb(S, m);
return unbinify(squeeze(S));
}
template <const unsigned int d, typename Valid>
std::string SHA3 <d, Valid>::hexdigest() {
return hexlify(digest());
}
template <const unsigned int d, typename Valid>
std::size_t SHA3 <d, Valid>::blocksize() const {
return r;
}
template <const unsigned int d, typename Valid>
std::size_t SHA3 <d, Valid>::digestsize() const {
return d;
}
// //////////////////////////////////////////////////////////////////////////////////////////
<commit_msg>typename StateArray<commit_after>// //////////////////////////////////////////////////////////////////////////////////////////
template <const unsigned int d, typename Valid>
typename SHA3 <d, Valid>::StateArray SHA3 <d, Valid>::s2sa(const std::string & S) const {
typename SHA3 <d, Valid>::StateArray A = {{0}};
for(uint8_t y = 0; y < 5; y++) {
for(uint8_t x = 0; x < 5; x++) {
A[x][y] = toint(little_end(S.substr(w * (5 * y + x), w), 2), 2);
}
}
return A;
}
template <const unsigned int d, typename Valid>
std::string SHA3 <d, Valid>::sa2s(const typename SHA3 <d, Valid>::StateArray & A) const {
std::string S = "";
for(uint8_t j = 0; j < 5; j++) {
for(uint8_t i = 0; i < 5; i++) {
S += little_end(makebin(A[i][j], 64), 2);
}
}
return S;
}
template <const unsigned int d, typename Valid>
typename SHA3 <d, Valid>::StateArray SHA3 <d, Valid>::theta(const typename SHA3 <d, Valid>::StateArray & A) const {
typename SHA3 <d, Valid>::StateArray Aprime = A;
// step 1
std::array <uint64_t, 5> C;
for(uint8_t x = 0; x < 5; x++) {
C[x] = A[x][0] ^ A[x][1] ^ A[x][2] ^ A[x][3] ^ A[x][4];
}
// step 2
std::array <uint64_t, 5> D;
for(uint8_t x = 0; x < 5; x++) {
D[x] = C[(x + 4) % 5] ^ ROL(C[(x + 1) % 5], 1, 64);
// step 3
for(uint8_t y = 0; y < 5; y++) {
Aprime[x][y] = A[x][y] ^ D[x];
}
}
return Aprime;
}
template <const unsigned int d, typename Valid>
typename SHA3 <d, Valid>::StateArray SHA3 <d, Valid>::pirho(const typename SHA3 <d, Valid>::StateArray & A) const {
typename SHA3 <d, Valid>::StateArray Aprime;
for(uint8_t x = 0; x < 5; x++) {
for(uint8_t y = 0; y < 5; y++) {
Aprime[y][(2 * x + 3 * y) % 5] = ROL(A[x][y], Keccak_rot[x][y], 64);
}
}
return Aprime;
}
template <const unsigned int d, typename Valid>
typename SHA3 <d, Valid>::StateArray SHA3 <d, Valid>::chi(const typename SHA3 <d, Valid>::StateArray & A) const {
typename SHA3 <d, Valid>::StateArray Aprime = A;
for(uint8_t x = 0; x < 5; x++) {
for(uint8_t y = 0; y < 5; y++) {
Aprime[x][y] = A[x][y] ^ ((~A[(x + 1) % 5][y]) & A[(x + 2) % 5][y]);
}
}
return Aprime;
}
template <const unsigned int d, typename Valid>
typename SHA3 <d, Valid>::StateArray SHA3 <d, Valid>::iota(const typename SHA3 <d, Valid>::StateArray & A, const uint64_t rc) const {
typename SHA3 <d, Valid>::StateArray Aprime = A;
Aprime[0][0] ^= rc;
return Aprime;
}
// assumes S is already in binary
template <const unsigned int d, typename Valid>
typename std::string SHA3 <d, Valid>::f(const std::string & S) const {
typename SHA3 <d, Valid>::StateArray A = s2sa(S);
for(unsigned int i = 0; i < nr; i++) {
A = iota(chi(pirho(theta(A))), Keccak_RC[i]);
}
return sa2s(A);
}
// //////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
// absorb data into given state
template <const unsigned int d, typename Valid>
void SHA3 <d, Valid>::absorb(std::string & S, const std::string & P) const {
for(unsigned int i = 0; i < P.size(); i += r) {
for(int j = 0; j < r; j++) {
S[j] = (P[i + j] ^ S[j]) | '0';
}
S = f(S);
}
}
// squeeze output data (concatenate results of f)
template <const unsigned int d, typename Valid>
std::string SHA3 <d, Valid>::squeeze(std::string & S) const {
std::string Z = "";
while (d > Z.size()) {
Z += S.substr(0, r);
S = f(S);
}
return Z.substr(0, d);
}
template <const unsigned int d, typename Valid>
SHA3 <d, Valid>::SHA3()
: HashAlg(),
b(1600), w(64), l(6), nr(24),
state((size_t) 1600, (char) '0'), stack(""),
r(1600 - (d << 1))
{}
template <const unsigned int d, typename Valid>
SHA3 <d, Valid>::SHA3(const std::string & M)
: SHA3()
{
update(M);
}
template <const unsigned int d, typename Valid>
void SHA3 <d, Valid>::update(const std::string & M) {
// process old leftover data + new data up to last full block
std::string data = stack + binify(M);
absorb(state, data.substr(0, (data.size() / r) * r));
// clear old stack (in case new data does not have partial blocks)
stack = "";
// extract last block of M
if (unsigned int rem = data.size() % r) {
stack = data.substr(data.size() - rem, rem);
}
}
template <const unsigned int d, typename Valid>
std::string SHA3 <d, Valid>::digest() {
// pad10*1 embedded here ////////////////////////////
std::string m = stack + "00000110";
int pad_size = (-static_cast <int> (m.size()) - 1) % r;
pad_size = (pad_size + r) % r;
m += std::string(pad_size - 7, '0') + "10000000";
// //////////////////////////////////////////////////
// copy state and process on that instead of actual state
std::string S = state;
absorb(S, m);
return unbinify(squeeze(S));
}
template <const unsigned int d, typename Valid>
std::string SHA3 <d, Valid>::hexdigest() {
return hexlify(digest());
}
template <const unsigned int d, typename Valid>
std::size_t SHA3 <d, Valid>::blocksize() const {
return r;
}
template <const unsigned int d, typename Valid>
std::size_t SHA3 <d, Valid>::digestsize() const {
return d;
}
// //////////////////////////////////////////////////////////////////////////////////////////
<|endoftext|>
|
<commit_before>#include "stdafx.h"
/*
* Copyright (c) 2007-2010 SlimDX Group
*
* 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 "IDWriteFontCollectionMock.h"
#include "IDWriteTextLayoutMock.h"
using namespace testing;
using namespace System;
using namespace SlimDX;
using namespace SlimDX::DirectWrite;
ref class MockedTextLayout
{
public:
MockedTextLayout()
: mockLayout(new IDWriteTextLayoutMock),
layout(TextLayout::FromPointer(System::IntPtr(mockLayout)))
{
}
~MockedTextLayout()
{
delete layout;
layout = nullptr;
delete mockLayout;
mockLayout = 0;
}
property IDWriteTextLayoutMock &Mock
{
IDWriteTextLayoutMock &get() { return *mockLayout; }
}
property TextLayout ^Layout
{
TextLayout ^get() { return layout; }
}
private:
IDWriteTextLayoutMock *mockLayout;
TextLayout ^layout;
};
class TextLayoutTest : public testing::Test
{
protected:
virtual void TearDown()
{
ASSERT_EQ(0, ObjectTable::Objects->Count);
}
};
static DWRITE_CLUSTER_METRICS ExpectedClusterMetrics()
{
DWRITE_CLUSTER_METRICS expectedMetrics;
expectedMetrics.width = 15.0f;
expectedMetrics.length = 1;
expectedMetrics.canWrapLineAfter = 0;
expectedMetrics.isWhitespace = 0;
expectedMetrics.isNewline = 0;
expectedMetrics.isSoftHyphen = 0;
expectedMetrics.isRightToLeft = 0;
return expectedMetrics;
}
static void AssertClusterMetricsMatchExpected(ClusterMetrics metrics)
{
DWRITE_CLUSTER_METRICS expected = ExpectedClusterMetrics();
ASSERT_EQ( expected.width, metrics.Width );
ASSERT_EQ( expected.length, metrics.Length );
ASSERT_EQ( expected.canWrapLineAfter != 0, metrics.CanWrapLineAfter );
ASSERT_EQ( expected.isWhitespace != 0, metrics.IsWhitespace );
ASSERT_EQ( expected.isNewline != 0, metrics.IsNewline );
ASSERT_EQ( expected.isSoftHyphen != 0, metrics.IsSoftHyphen );
ASSERT_EQ( expected.isRightToLeft != 0, metrics.IsRightToLeft );
}
TEST_F(TextLayoutTest, GetClusterMetrics)
{
MockedTextLayout layout;
EXPECT_CALL(layout.Mock, GetClusterMetrics(_, _, _))
.WillRepeatedly(Return(E_UNEXPECTED));
EXPECT_CALL(layout.Mock, GetClusterMetrics(0, 0, NotNull()))
.WillOnce(DoAll(SetArgumentPointee<2>(1),
Return(HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER))));
EXPECT_CALL(layout.Mock, GetClusterMetrics(NotNull(), Gt(0U), NotNull()))
.WillOnce(DoAll(SetArgumentPointee<0>(ExpectedClusterMetrics()),
SetArgumentPointee<2>(1),
Return(S_OK)));
array<SlimDX::DirectWrite::ClusterMetrics>^ metrics = layout.Layout->GetClusterMetrics();
ASSERT_TRUE( Result::Last.IsSuccess );
ASSERT_TRUE( metrics != nullptr );
ASSERT_EQ( 1, metrics->Length );
AssertClusterMetricsMatchExpected(metrics[0]);
}
TEST_F(TextLayoutTest, DetermineMinWidth)
{
MockedTextLayout layout;
EXPECT_CALL(layout.Mock, DetermineMinWidth(NotNull()))
.Times(1)
.WillOnce(DoAll(SetArgumentPointee<0>(14.5f), Return(S_OK)));
float minWidth = -1.0f;
ASSERT_EQ( 14.5f, layout.Layout->DetermineMinWidth() );
}
static DWRITE_HIT_TEST_METRICS ExpectedHitTestMetrics()
{
DWRITE_HIT_TEST_METRICS expectedMetrics;
expectedMetrics.textPosition = 0;
expectedMetrics.length = 1;
expectedMetrics.left = 0.15f;
expectedMetrics.top = 0.245f;
expectedMetrics.width = 45.8f;
expectedMetrics.height = 998.5f;
expectedMetrics.bidiLevel = 23;
expectedMetrics.isText = TRUE;
expectedMetrics.isTrimmed = TRUE;
return expectedMetrics;
}
static void AssertHitTestMetricsMatchExpected(HitTestMetrics% actual)
{
DWRITE_HIT_TEST_METRICS expected = ExpectedHitTestMetrics();
ASSERT_EQ( expected.textPosition, actual.TextPosition );
ASSERT_EQ( expected.length, actual.Length );
ASSERT_EQ( expected.left, actual.Left );
ASSERT_EQ( expected.top, actual.Top );
ASSERT_EQ( expected.width, actual.Width );
ASSERT_EQ( expected.height, actual.Height );
ASSERT_EQ( expected.bidiLevel, actual.BidiLevel );
ASSERT_EQ( expected.isText == TRUE, actual.IsText );
ASSERT_EQ( expected.isTrimmed == TRUE, actual.IsTrimmed );
}
TEST_F(TextLayoutTest, HitTestPoint)
{
MockedTextLayout layout;
EXPECT_CALL(layout.Mock, HitTestPoint(10.0f, 12.0f, NotNull(), NotNull(), NotNull()))
.Times(1)
.WillOnce(DoAll(SetArgumentPointee<2>(false),
SetArgumentPointee<3>(false),
SetArgumentPointee<4>(ExpectedHitTestMetrics()),
Return(S_OK)));
bool isTrailingHit = true;
bool isInside = true;
HitTestMetrics metrics = layout.Layout->HitTestPoint(10.0f, 12.0f, isTrailingHit, isInside);
ASSERT_TRUE( Result::Last.IsSuccess );
ASSERT_FALSE( isTrailingHit );
ASSERT_FALSE( isInside );
AssertHitTestMetricsMatchExpected(metrics);
}
TEST_F(TextLayoutTest, HitTestTextPosition)
{
MockedTextLayout layout;
EXPECT_CALL(layout.Mock, HitTestTextPosition(12U, FALSE, NotNull(), NotNull(), NotNull()))
.Times(1)
.WillOnce(DoAll(SetArgumentPointee<2>(12.5f),
SetArgumentPointee<3>(13.5f),
SetArgumentPointee<4>(ExpectedHitTestMetrics()),
Return(S_OK)));
float x, y;
HitTestMetrics metrics = layout.Layout->HitTestTextPosition(12U, false, x, y);
ASSERT_TRUE( Result::Last.IsSuccess );
ASSERT_EQ( 12.5f, x );
ASSERT_EQ( 13.5f, y );
AssertHitTestMetricsMatchExpected(metrics);
}
TEST_F(TextLayoutTest, HitTestTextRange)
{
MockedTextLayout layout;
EXPECT_CALL(layout.Mock, HitTestTextRange(12U, 4U, 10.0f, 12.0f, 0, 0, NotNull()))
.Times(1)
.WillOnce(DoAll(SetArgumentPointee<6>(1U), Return(HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER))));
EXPECT_CALL(layout.Mock, HitTestTextRange(12U, 4U, 10.0f, 12.0f, NotNull(), 1U, NotNull()))
.Times(1)
.WillOnce(DoAll(SetArgumentPointee<6>(1U),
SetArgumentPointee<4>(ExpectedHitTestMetrics()),
Return(S_OK)));
array<HitTestMetrics> ^metrics = layout.Layout->HitTestTextRange(12U, 4U, 10.0f, 12.0f);
ASSERT_TRUE( Result::Last.IsSuccess );
ASSERT_EQ( 1, metrics->Length );
AssertHitTestMetricsMatchExpected(metrics[0]);
}
TEST_F(TextLayoutTest, GetFontCollectionNoTextRange)
{
MockedTextLayout layout;
IDWriteFontCollectionMock mockCollection;
EXPECT_CALL(layout.Mock, GetFontCollection(0, NotNull(), 0))
.Times(1)
.WillOnce(DoAll(SetArgumentPointee<1>(&mockCollection), Return(S_OK)));
FontCollection ^collection = layout.Layout->GetFontCollection(0);
ASSERT_TRUE( collection != nullptr );
ASSERT_EQ( collection->InternalPointer, &mockCollection );
delete collection;
}
<commit_msg>DirectWrite : Implemented : TextLayout.GetFontCollection returning optional TextRange<commit_after>#include "stdafx.h"
/*
* Copyright (c) 2007-2010 SlimDX Group
*
* 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 "IDWriteFontCollectionMock.h"
#include "IDWriteTextLayoutMock.h"
using namespace testing;
using namespace System;
using namespace SlimDX;
using namespace SlimDX::DirectWrite;
ref class MockedTextLayout
{
public:
MockedTextLayout()
: mockLayout(new IDWriteTextLayoutMock),
layout(TextLayout::FromPointer(System::IntPtr(mockLayout)))
{
}
~MockedTextLayout()
{
delete layout;
layout = nullptr;
delete mockLayout;
mockLayout = 0;
}
property IDWriteTextLayoutMock &Mock
{
IDWriteTextLayoutMock &get() { return *mockLayout; }
}
property TextLayout ^Layout
{
TextLayout ^get() { return layout; }
}
private:
IDWriteTextLayoutMock *mockLayout;
TextLayout ^layout;
};
class TextLayoutTest : public testing::Test
{
protected:
virtual void TearDown()
{
ASSERT_EQ(0, ObjectTable::Objects->Count);
}
};
static DWRITE_CLUSTER_METRICS ExpectedClusterMetrics()
{
DWRITE_CLUSTER_METRICS expectedMetrics;
expectedMetrics.width = 15.0f;
expectedMetrics.length = 1;
expectedMetrics.canWrapLineAfter = 0;
expectedMetrics.isWhitespace = 0;
expectedMetrics.isNewline = 0;
expectedMetrics.isSoftHyphen = 0;
expectedMetrics.isRightToLeft = 0;
return expectedMetrics;
}
static void AssertClusterMetricsMatchExpected(ClusterMetrics metrics)
{
DWRITE_CLUSTER_METRICS expected = ExpectedClusterMetrics();
ASSERT_EQ( expected.width, metrics.Width );
ASSERT_EQ( expected.length, metrics.Length );
ASSERT_EQ( expected.canWrapLineAfter != 0, metrics.CanWrapLineAfter );
ASSERT_EQ( expected.isWhitespace != 0, metrics.IsWhitespace );
ASSERT_EQ( expected.isNewline != 0, metrics.IsNewline );
ASSERT_EQ( expected.isSoftHyphen != 0, metrics.IsSoftHyphen );
ASSERT_EQ( expected.isRightToLeft != 0, metrics.IsRightToLeft );
}
TEST_F(TextLayoutTest, GetClusterMetrics)
{
MockedTextLayout layout;
EXPECT_CALL(layout.Mock, GetClusterMetrics(_, _, _))
.WillRepeatedly(Return(E_UNEXPECTED));
EXPECT_CALL(layout.Mock, GetClusterMetrics(0, 0, NotNull()))
.WillOnce(DoAll(SetArgumentPointee<2>(1),
Return(HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER))));
EXPECT_CALL(layout.Mock, GetClusterMetrics(NotNull(), Gt(0U), NotNull()))
.WillOnce(DoAll(SetArgumentPointee<0>(ExpectedClusterMetrics()),
SetArgumentPointee<2>(1),
Return(S_OK)));
array<SlimDX::DirectWrite::ClusterMetrics>^ metrics = layout.Layout->GetClusterMetrics();
ASSERT_TRUE( Result::Last.IsSuccess );
ASSERT_TRUE( metrics != nullptr );
ASSERT_EQ( 1, metrics->Length );
AssertClusterMetricsMatchExpected(metrics[0]);
}
TEST_F(TextLayoutTest, DetermineMinWidth)
{
MockedTextLayout layout;
EXPECT_CALL(layout.Mock, DetermineMinWidth(NotNull()))
.Times(1)
.WillOnce(DoAll(SetArgumentPointee<0>(14.5f), Return(S_OK)));
float minWidth = -1.0f;
ASSERT_EQ( 14.5f, layout.Layout->DetermineMinWidth() );
}
static DWRITE_HIT_TEST_METRICS ExpectedHitTestMetrics()
{
DWRITE_HIT_TEST_METRICS expectedMetrics;
expectedMetrics.textPosition = 0;
expectedMetrics.length = 1;
expectedMetrics.left = 0.15f;
expectedMetrics.top = 0.245f;
expectedMetrics.width = 45.8f;
expectedMetrics.height = 998.5f;
expectedMetrics.bidiLevel = 23;
expectedMetrics.isText = TRUE;
expectedMetrics.isTrimmed = TRUE;
return expectedMetrics;
}
static void AssertHitTestMetricsMatchExpected(HitTestMetrics% actual)
{
DWRITE_HIT_TEST_METRICS expected = ExpectedHitTestMetrics();
ASSERT_EQ( expected.textPosition, actual.TextPosition );
ASSERT_EQ( expected.length, actual.Length );
ASSERT_EQ( expected.left, actual.Left );
ASSERT_EQ( expected.top, actual.Top );
ASSERT_EQ( expected.width, actual.Width );
ASSERT_EQ( expected.height, actual.Height );
ASSERT_EQ( expected.bidiLevel, actual.BidiLevel );
ASSERT_EQ( expected.isText == TRUE, actual.IsText );
ASSERT_EQ( expected.isTrimmed == TRUE, actual.IsTrimmed );
}
TEST_F(TextLayoutTest, HitTestPoint)
{
MockedTextLayout layout;
EXPECT_CALL(layout.Mock, HitTestPoint(10.0f, 12.0f, NotNull(), NotNull(), NotNull()))
.Times(1)
.WillOnce(DoAll(SetArgumentPointee<2>(false),
SetArgumentPointee<3>(false),
SetArgumentPointee<4>(ExpectedHitTestMetrics()),
Return(S_OK)));
bool isTrailingHit = true;
bool isInside = true;
HitTestMetrics metrics = layout.Layout->HitTestPoint(10.0f, 12.0f, isTrailingHit, isInside);
ASSERT_TRUE( Result::Last.IsSuccess );
ASSERT_FALSE( isTrailingHit );
ASSERT_FALSE( isInside );
AssertHitTestMetricsMatchExpected(metrics);
}
TEST_F(TextLayoutTest, HitTestTextPosition)
{
MockedTextLayout layout;
EXPECT_CALL(layout.Mock, HitTestTextPosition(12U, FALSE, NotNull(), NotNull(), NotNull()))
.Times(1)
.WillOnce(DoAll(SetArgumentPointee<2>(12.5f),
SetArgumentPointee<3>(13.5f),
SetArgumentPointee<4>(ExpectedHitTestMetrics()),
Return(S_OK)));
float x, y;
HitTestMetrics metrics = layout.Layout->HitTestTextPosition(12U, false, x, y);
ASSERT_TRUE( Result::Last.IsSuccess );
ASSERT_EQ( 12.5f, x );
ASSERT_EQ( 13.5f, y );
AssertHitTestMetricsMatchExpected(metrics);
}
TEST_F(TextLayoutTest, HitTestTextRange)
{
MockedTextLayout layout;
EXPECT_CALL(layout.Mock, HitTestTextRange(12U, 4U, 10.0f, 12.0f, 0, 0, NotNull()))
.Times(1)
.WillOnce(DoAll(SetArgumentPointee<6>(1U), Return(HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER))));
EXPECT_CALL(layout.Mock, HitTestTextRange(12U, 4U, 10.0f, 12.0f, NotNull(), 1U, NotNull()))
.Times(1)
.WillOnce(DoAll(SetArgumentPointee<6>(1U),
SetArgumentPointee<4>(ExpectedHitTestMetrics()),
Return(S_OK)));
array<HitTestMetrics> ^metrics = layout.Layout->HitTestTextRange(12U, 4U, 10.0f, 12.0f);
ASSERT_TRUE( Result::Last.IsSuccess );
ASSERT_EQ( 1, metrics->Length );
AssertHitTestMetricsMatchExpected(metrics[0]);
}
TEST_F(TextLayoutTest, GetFontCollectionNoTextRange)
{
MockedTextLayout layout;
IDWriteFontCollectionMock mockCollection;
EXPECT_CALL(layout.Mock, GetFontCollection(0, NotNull(), 0))
.Times(1)
.WillOnce(DoAll(SetArgumentPointee<1>(&mockCollection), Return(S_OK)));
FontCollection ^collection = layout.Layout->GetFontCollection(0);
ASSERT_TRUE( collection != nullptr );
ASSERT_EQ( collection->InternalPointer, &mockCollection );
delete collection;
}
TEST_F(TextLayoutTest, GetFontCollectionWithTextRange)
{
MockedTextLayout layout;
IDWriteFontCollectionMock mockCollection;
DWRITE_TEXT_RANGE fakeTextRange;
fakeTextRange.length = 1;
fakeTextRange.startPosition = 0;
EXPECT_CALL(layout.Mock, GetFontCollection(0, NotNull(), NotNull()))
.Times(1)
.WillOnce(DoAll(SetArgumentPointee<1>(&mockCollection),
SetArgumentPointee<2>(fakeTextRange),
Return(S_OK)));
TextRange textRange;
FontCollection ^collection = layout.Layout->GetFontCollection(0, textRange);
ASSERT_TRUE( collection != nullptr );
ASSERT_EQ( collection->InternalPointer, &mockCollection );
ASSERT_EQ( 1, textRange.Length );
ASSERT_EQ( 0, textRange.StartPosition );
delete collection;
}
<|endoftext|>
|
<commit_before>#include "stdafx.h"
/*
* Copyright (c) 2007-2010 SlimDX Group
*
* 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 "IDWriteTextLayoutMock.h"
using namespace testing;
using namespace System;
using namespace SlimDX;
using namespace SlimDX::DirectWrite;
TEST(TextLayoutTests, GetClusterMetrics)
{
IDWriteTextLayoutMock mockLayout;
TextLayout ^layout = TextLayout::FromPointer(System::IntPtr(&mockLayout));
EXPECT_CALL(mockLayout, GetClusterMetrics(_, _, _))
.WillRepeatedly(Return(E_UNEXPECTED));
EXPECT_CALL(mockLayout, GetClusterMetrics(0, 0, NotNull()))
.WillOnce(DoAll(
SetArgumentPointee<2>(1),
Return(HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER))
));
DWRITE_CLUSTER_METRICS expectedMetrics;
expectedMetrics.width = 15.0f;
expectedMetrics.length = 1;
expectedMetrics.canWrapLineAfter = 0;
expectedMetrics.isWhitespace = 0;
expectedMetrics.isNewline = 0;
expectedMetrics.isSoftHyphen = 0;
expectedMetrics.isRightToLeft = 0;
EXPECT_CALL(mockLayout, GetClusterMetrics(NotNull(), Gt(0U), NotNull()))
.WillOnce(DoAll(
SetArgumentPointee<0>(expectedMetrics),
SetArgumentPointee<2>(1),
Return(S_OK)
));
array<SlimDX::DirectWrite::ClusterMetrics>^ metrics = layout->GetClusterMetrics();
ASSERT_TRUE( Result::Last.IsSuccess );
ASSERT_TRUE( metrics != nullptr );
ASSERT_EQ( 1, metrics->Length );
ASSERT_EQ( 15.0f, metrics[0].Width );
ASSERT_EQ( 1, metrics[0].Length );
ASSERT_FALSE( metrics[0].CanWrapLineAfter );
ASSERT_FALSE( metrics[0].IsWhitespace );
ASSERT_FALSE( metrics[0].IsNewline );
ASSERT_FALSE( metrics[0].IsSoftHyphen );
ASSERT_FALSE( metrics[0].IsRightToLeft );
}
TEST(TextLayoutTests, DetermineMinWidth)
{
IDWriteTextLayoutMock mockLayout;
TextLayout ^layout = TextLayout::FromPointer(System::IntPtr(&mockLayout));
EXPECT_CALL(mockLayout, DetermineMinWidth(NotNull()))
.Times(1)
.WillOnce(DoAll(SetArgumentPointee<0>(14.5f), Return(S_OK)));
float minWidth = -1.0f;
ASSERT_EQ( 14.5f, layout->DetermineMinWidth() );
}
TEST(TextLayoutTests, HitTestPoint)
{
IDWriteTextLayoutMock mockLayout;
TextLayout ^layout = TextLayout::FromPointer(System::IntPtr(&mockLayout));
DWRITE_HIT_TEST_METRICS expectedMetrics;
expectedMetrics.textPosition = 0;
expectedMetrics.length = 1;
expectedMetrics.left = 0.15f;
expectedMetrics.top = 0.245f;
expectedMetrics.width = 45.8f;
expectedMetrics.height = 998.5f;
expectedMetrics.bidiLevel = 23;
expectedMetrics.isText = TRUE;
expectedMetrics.isTrimmed = TRUE;
EXPECT_CALL(mockLayout, HitTestPoint(10.0f, 12.0f, NotNull(), NotNull(), NotNull()))
.Times(1)
.WillOnce(DoAll(SetArgumentPointee<2>(false),
SetArgumentPointee<3>(false),
SetArgumentPointee<4>(expectedMetrics),
Return(S_OK)));
bool isTrailingHit = true;
bool isInside = true;
HitTestMetrics metrics = layout->HitTestPoint(10.0f, 12.0f, isTrailingHit, isInside);
ASSERT_TRUE( Result::Last.IsSuccess );
ASSERT_FALSE( isTrailingHit );
ASSERT_FALSE( isInside );
ASSERT_EQ( 0, metrics.TextPosition );
ASSERT_EQ( 1, metrics.Length );
ASSERT_EQ( 0.15f, metrics.Left );
ASSERT_EQ( 0.245f, metrics.Top );
ASSERT_EQ( 45.8f, metrics.Width );
ASSERT_EQ( 998.5f, metrics.Height );
ASSERT_EQ( 23, metrics.BidiLevel );
ASSERT_TRUE( metrics.IsText );
ASSERT_TRUE( metrics.IsTrimmed );
}
TEST(TextLayoutTests, HitTestTextPosition)
{
IDWriteTextLayoutMock mockLayout;
TextLayout ^layout = TextLayout::FromPointer(System::IntPtr(&mockLayout));
DWRITE_HIT_TEST_METRICS expectedMetrics;
expectedMetrics.textPosition = 0;
expectedMetrics.length = 1;
expectedMetrics.left = 0.15f;
expectedMetrics.top = 0.245f;
expectedMetrics.width = 45.8f;
expectedMetrics.height = 998.5f;
expectedMetrics.bidiLevel = 23;
expectedMetrics.isText = TRUE;
expectedMetrics.isTrimmed = TRUE;
EXPECT_CALL(mockLayout, HitTestTextPosition(12U, FALSE, NotNull(), NotNull(), NotNull()))
.Times(1)
.WillOnce(DoAll(SetArgumentPointee<2>(12.5f),
SetArgumentPointee<3>(13.5f),
SetArgumentPointee<4>(expectedMetrics),
Return(S_OK)));
float x, y;
HitTestMetrics metrics = layout->HitTestTextPosition(12U, false, x, y);
ASSERT_EQ( 12.5f, x );
ASSERT_EQ( 13.5f, y );
ASSERT_TRUE( Result::Last.IsSuccess );
ASSERT_EQ( 0, metrics.TextPosition );
ASSERT_EQ( 1, metrics.Length );
ASSERT_EQ( 0.15f, metrics.Left );
ASSERT_EQ( 0.245f, metrics.Top );
ASSERT_EQ( 45.8f, metrics.Width );
ASSERT_EQ( 998.5f, metrics.Height );
ASSERT_EQ( 23, metrics.BidiLevel );
ASSERT_TRUE( metrics.IsText );
ASSERT_TRUE( metrics.IsTrimmed );
}
<commit_msg>DirectWrite : Refactored : Extract Function<commit_after>#include "stdafx.h"
/*
* Copyright (c) 2007-2010 SlimDX Group
*
* 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 "IDWriteTextLayoutMock.h"
using namespace testing;
using namespace System;
using namespace SlimDX;
using namespace SlimDX::DirectWrite;
TEST(TextLayoutTests, GetClusterMetrics)
{
IDWriteTextLayoutMock mockLayout;
TextLayout ^layout = TextLayout::FromPointer(System::IntPtr(&mockLayout));
EXPECT_CALL(mockLayout, GetClusterMetrics(_, _, _))
.WillRepeatedly(Return(E_UNEXPECTED));
EXPECT_CALL(mockLayout, GetClusterMetrics(0, 0, NotNull()))
.WillOnce(DoAll(
SetArgumentPointee<2>(1),
Return(HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER))
));
DWRITE_CLUSTER_METRICS expectedMetrics;
expectedMetrics.width = 15.0f;
expectedMetrics.length = 1;
expectedMetrics.canWrapLineAfter = 0;
expectedMetrics.isWhitespace = 0;
expectedMetrics.isNewline = 0;
expectedMetrics.isSoftHyphen = 0;
expectedMetrics.isRightToLeft = 0;
EXPECT_CALL(mockLayout, GetClusterMetrics(NotNull(), Gt(0U), NotNull()))
.WillOnce(DoAll(
SetArgumentPointee<0>(expectedMetrics),
SetArgumentPointee<2>(1),
Return(S_OK)
));
array<SlimDX::DirectWrite::ClusterMetrics>^ metrics = layout->GetClusterMetrics();
ASSERT_TRUE( Result::Last.IsSuccess );
ASSERT_TRUE( metrics != nullptr );
ASSERT_EQ( 1, metrics->Length );
ASSERT_EQ( 15.0f, metrics[0].Width );
ASSERT_EQ( 1, metrics[0].Length );
ASSERT_FALSE( metrics[0].CanWrapLineAfter );
ASSERT_FALSE( metrics[0].IsWhitespace );
ASSERT_FALSE( metrics[0].IsNewline );
ASSERT_FALSE( metrics[0].IsSoftHyphen );
ASSERT_FALSE( metrics[0].IsRightToLeft );
}
TEST(TextLayoutTests, DetermineMinWidth)
{
IDWriteTextLayoutMock mockLayout;
TextLayout ^layout = TextLayout::FromPointer(System::IntPtr(&mockLayout));
EXPECT_CALL(mockLayout, DetermineMinWidth(NotNull()))
.Times(1)
.WillOnce(DoAll(SetArgumentPointee<0>(14.5f), Return(S_OK)));
float minWidth = -1.0f;
ASSERT_EQ( 14.5f, layout->DetermineMinWidth() );
}
static DWRITE_HIT_TEST_METRICS ExpectedHitTestMetrics()
{
DWRITE_HIT_TEST_METRICS expectedMetrics;
expectedMetrics.textPosition = 0;
expectedMetrics.length = 1;
expectedMetrics.left = 0.15f;
expectedMetrics.top = 0.245f;
expectedMetrics.width = 45.8f;
expectedMetrics.height = 998.5f;
expectedMetrics.bidiLevel = 23;
expectedMetrics.isText = TRUE;
expectedMetrics.isTrimmed = TRUE;
return expectedMetrics;
}
static void AssertHitTestMetricsMatchExpected(HitTestMetrics% actual)
{
DWRITE_HIT_TEST_METRICS expected = ExpectedHitTestMetrics();
ASSERT_EQ( expected.textPosition, actual.TextPosition );
ASSERT_EQ( expected.length, actual.Length );
ASSERT_EQ( expected.left, actual.Left );
ASSERT_EQ( expected.top, actual.Top );
ASSERT_EQ( expected.width, actual.Width );
ASSERT_EQ( expected.height, actual.Height );
ASSERT_EQ( expected.bidiLevel, actual.BidiLevel );
ASSERT_EQ( expected.isText == TRUE, actual.IsText );
ASSERT_EQ( expected.isTrimmed == TRUE, actual.IsTrimmed );
}
TEST(TextLayoutTests, HitTestPoint)
{
IDWriteTextLayoutMock mockLayout;
TextLayout ^layout = TextLayout::FromPointer(System::IntPtr(&mockLayout));
EXPECT_CALL(mockLayout, HitTestPoint(10.0f, 12.0f, NotNull(), NotNull(), NotNull()))
.Times(1)
.WillOnce(DoAll(SetArgumentPointee<2>(false),
SetArgumentPointee<3>(false),
SetArgumentPointee<4>(ExpectedHitTestMetrics()),
Return(S_OK)));
bool isTrailingHit = true;
bool isInside = true;
HitTestMetrics metrics = layout->HitTestPoint(10.0f, 12.0f, isTrailingHit, isInside);
ASSERT_TRUE( Result::Last.IsSuccess );
ASSERT_FALSE( isTrailingHit );
ASSERT_FALSE( isInside );
AssertHitTestMetricsMatchExpected(metrics);
}
TEST(TextLayoutTests, HitTestTextPosition)
{
IDWriteTextLayoutMock mockLayout;
TextLayout ^layout = TextLayout::FromPointer(System::IntPtr(&mockLayout));
EXPECT_CALL(mockLayout, HitTestTextPosition(12U, FALSE, NotNull(), NotNull(), NotNull()))
.Times(1)
.WillOnce(DoAll(SetArgumentPointee<2>(12.5f),
SetArgumentPointee<3>(13.5f),
SetArgumentPointee<4>(ExpectedHitTestMetrics()),
Return(S_OK)));
float x, y;
HitTestMetrics metrics = layout->HitTestTextPosition(12U, false, x, y);
ASSERT_TRUE( Result::Last.IsSuccess );
ASSERT_EQ( 12.5f, x );
ASSERT_EQ( 13.5f, y );
AssertHitTestMetricsMatchExpected(metrics);
}
<|endoftext|>
|
<commit_before>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
/**
* \file lower_if_to_cond_assign.cpp
*
* This flattens if-statements to conditional assignments if:
*
* - the GPU has limited or no flow control support
* (controlled by max_depth)
*
* - small conditional branches are more expensive than conditional assignments
* (controlled by min_branch_cost, that's the cost for a branch to be
* preserved)
*
* It can't handle other control flow being inside of its block, such
* as calls or loops. Hopefully loop unrolling and inlining will take
* care of those.
*
* Drivers for GPUs with no control flow support should simply call
*
* lower_if_to_cond_assign(instructions)
*
* to attempt to flatten all if-statements.
*
* Some GPUs (such as i965 prior to gen6) do support control flow, but have a
* maximum nesting depth N. Drivers for such hardware can call
*
* lower_if_to_cond_assign(instructions, N)
*
* to attempt to flatten any if-statements appearing at depth > N.
*/
#include "compiler/glsl_types.h"
#include "ir.h"
#include "util/set.h"
#include "util/hash_table.h" /* Needed for the hashing functions */
#include "main/macros.h" /* for MAX2 */
namespace {
class ir_if_to_cond_assign_visitor : public ir_hierarchical_visitor {
public:
ir_if_to_cond_assign_visitor(gl_shader_stage stage,
unsigned max_depth,
unsigned min_branch_cost)
{
this->progress = false;
this->stage = stage;
this->max_depth = max_depth;
this->min_branch_cost = min_branch_cost;
this->depth = 0;
this->condition_variables =
_mesa_set_create(NULL, _mesa_hash_pointer,
_mesa_key_pointer_equal);
}
~ir_if_to_cond_assign_visitor()
{
_mesa_set_destroy(this->condition_variables, NULL);
}
ir_visitor_status visit_enter(ir_if *);
ir_visitor_status visit_leave(ir_if *);
bool found_unsupported_op;
bool found_expensive_op;
bool is_then;
bool progress;
gl_shader_stage stage;
unsigned then_cost;
unsigned else_cost;
unsigned min_branch_cost;
unsigned max_depth;
unsigned depth;
struct set *condition_variables;
};
} /* anonymous namespace */
bool
lower_if_to_cond_assign(gl_shader_stage stage, exec_list *instructions,
unsigned max_depth, unsigned min_branch_cost)
{
if (max_depth == UINT_MAX)
return false;
ir_if_to_cond_assign_visitor v(stage, max_depth, min_branch_cost);
visit_list_elements(&v, instructions);
return v.progress;
}
void
check_ir_node(ir_instruction *ir, void *data)
{
ir_if_to_cond_assign_visitor *v = (ir_if_to_cond_assign_visitor *)data;
switch (ir->ir_type) {
case ir_type_call:
case ir_type_discard:
case ir_type_loop:
case ir_type_loop_jump:
case ir_type_return:
case ir_type_emit_vertex:
case ir_type_end_primitive:
case ir_type_barrier:
v->found_unsupported_op = true;
break;
case ir_type_dereference_variable: {
ir_variable *var = ir->as_dereference_variable()->variable_referenced();
/* Lowering branches with TCS output accesses breaks many piglit tests,
* so don't touch them for now.
*/
if (v->stage == MESA_SHADER_TESS_CTRL &&
var->data.mode == ir_var_shader_out)
v->found_unsupported_op = true;
break;
}
/* SSBO, images, atomic counters are handled by ir_type_call */
case ir_type_texture:
v->found_expensive_op = true;
break;
case ir_type_expression:
case ir_type_dereference_array:
case ir_type_dereference_record:
if (v->is_then)
v->then_cost++;
else
v->else_cost++;
break;
default:
break;
}
}
void
move_block_to_cond_assign(void *mem_ctx,
ir_if *if_ir, ir_rvalue *cond_expr,
exec_list *instructions,
struct set *set)
{
foreach_in_list_safe(ir_instruction, ir, instructions) {
if (ir->ir_type == ir_type_assignment) {
ir_assignment *assign = (ir_assignment *)ir;
if (_mesa_set_search(set, assign) == NULL) {
_mesa_set_add(set, assign);
/* If the LHS of the assignment is a condition variable that was
* previously added, insert an additional assignment of false to
* the variable.
*/
const bool assign_to_cv =
_mesa_set_search(
set, assign->lhs->variable_referenced()) != NULL;
if (!assign->condition) {
if (assign_to_cv) {
assign->rhs =
new(mem_ctx) ir_expression(ir_binop_logic_and,
glsl_type::bool_type,
cond_expr->clone(mem_ctx, NULL),
assign->rhs);
} else {
assign->condition = cond_expr->clone(mem_ctx, NULL);
}
} else {
assign->condition =
new(mem_ctx) ir_expression(ir_binop_logic_and,
glsl_type::bool_type,
cond_expr->clone(mem_ctx, NULL),
assign->condition);
}
}
}
/* Now, move from the if block to the block surrounding it. */
ir->remove();
if_ir->insert_before(ir);
}
}
ir_visitor_status
ir_if_to_cond_assign_visitor::visit_enter(ir_if *ir)
{
(void) ir;
this->depth++;
return visit_continue;
}
ir_visitor_status
ir_if_to_cond_assign_visitor::visit_leave(ir_if *ir)
{
bool must_lower = this->depth-- > this->max_depth;
/* Only flatten when beyond the GPU's maximum supported nesting depth. */
if (!must_lower && this->min_branch_cost == 0)
return visit_continue;
this->found_unsupported_op = false;
this->found_expensive_op = false;
this->then_cost = 0;
this->else_cost = 0;
ir_assignment *assign;
/* Check that both blocks don't contain anything we can't support. */
this->is_then = true;
foreach_in_list(ir_instruction, then_ir, &ir->then_instructions) {
visit_tree(then_ir, check_ir_node, this);
}
this->is_then = false;
foreach_in_list(ir_instruction, else_ir, &ir->else_instructions) {
visit_tree(else_ir, check_ir_node, this);
}
if (this->found_unsupported_op)
return visit_continue; /* can't handle inner unsupported opcodes */
/* Skip if the branch cost is high enough or if there's an expensive op. */
if (!must_lower &&
(this->found_expensive_op ||
MAX2(this->then_cost, this->else_cost) >= this->min_branch_cost))
return visit_continue;
void *mem_ctx = ralloc_parent(ir);
/* Store the condition to a variable. Move all of the instructions from
* the then-clause of the if-statement. Use the condition variable as a
* condition for all assignments.
*/
ir_variable *const then_var =
new(mem_ctx) ir_variable(glsl_type::bool_type,
"if_to_cond_assign_then",
ir_var_temporary);
ir->insert_before(then_var);
ir_dereference_variable *then_cond =
new(mem_ctx) ir_dereference_variable(then_var);
assign = new(mem_ctx) ir_assignment(then_cond, ir->condition);
ir->insert_before(assign);
move_block_to_cond_assign(mem_ctx, ir, then_cond,
&ir->then_instructions,
this->condition_variables);
/* Add the new condition variable to the hash table. This allows us to
* find this variable when lowering other (enclosing) if-statements.
*/
_mesa_set_add(this->condition_variables, then_var);
/* If there are instructions in the else-clause, store the inverse of the
* condition to a variable. Move all of the instructions from the
* else-clause if the if-statement. Use the (inverse) condition variable
* as a condition for all assignments.
*/
if (!ir->else_instructions.is_empty()) {
ir_variable *const else_var =
new(mem_ctx) ir_variable(glsl_type::bool_type,
"if_to_cond_assign_else",
ir_var_temporary);
ir->insert_before(else_var);
ir_dereference_variable *else_cond =
new(mem_ctx) ir_dereference_variable(else_var);
ir_rvalue *inverse =
new(mem_ctx) ir_expression(ir_unop_logic_not,
then_cond->clone(mem_ctx, NULL));
assign = new(mem_ctx) ir_assignment(else_cond, inverse);
ir->insert_before(assign);
move_block_to_cond_assign(mem_ctx, ir, else_cond,
&ir->else_instructions,
this->condition_variables);
/* Add the new condition variable to the hash table. This allows us to
* find this variable when lowering other (enclosing) if-statements.
*/
_mesa_set_add(this->condition_variables, else_var);
}
ir->remove();
this->progress = true;
return visit_continue;
}
<commit_msg>glsl: don't flatten if-blocks with dynamic array indices<commit_after>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
/**
* \file lower_if_to_cond_assign.cpp
*
* This flattens if-statements to conditional assignments if:
*
* - the GPU has limited or no flow control support
* (controlled by max_depth)
*
* - small conditional branches are more expensive than conditional assignments
* (controlled by min_branch_cost, that's the cost for a branch to be
* preserved)
*
* It can't handle other control flow being inside of its block, such
* as calls or loops. Hopefully loop unrolling and inlining will take
* care of those.
*
* Drivers for GPUs with no control flow support should simply call
*
* lower_if_to_cond_assign(instructions)
*
* to attempt to flatten all if-statements.
*
* Some GPUs (such as i965 prior to gen6) do support control flow, but have a
* maximum nesting depth N. Drivers for such hardware can call
*
* lower_if_to_cond_assign(instructions, N)
*
* to attempt to flatten any if-statements appearing at depth > N.
*/
#include "compiler/glsl_types.h"
#include "ir.h"
#include "util/set.h"
#include "util/hash_table.h" /* Needed for the hashing functions */
#include "main/macros.h" /* for MAX2 */
namespace {
class ir_if_to_cond_assign_visitor : public ir_hierarchical_visitor {
public:
ir_if_to_cond_assign_visitor(gl_shader_stage stage,
unsigned max_depth,
unsigned min_branch_cost)
{
this->progress = false;
this->stage = stage;
this->max_depth = max_depth;
this->min_branch_cost = min_branch_cost;
this->depth = 0;
this->condition_variables =
_mesa_set_create(NULL, _mesa_hash_pointer,
_mesa_key_pointer_equal);
}
~ir_if_to_cond_assign_visitor()
{
_mesa_set_destroy(this->condition_variables, NULL);
}
ir_visitor_status visit_enter(ir_if *);
ir_visitor_status visit_leave(ir_if *);
bool found_unsupported_op;
bool found_expensive_op;
bool found_dynamic_arrayref;
bool is_then;
bool progress;
gl_shader_stage stage;
unsigned then_cost;
unsigned else_cost;
unsigned min_branch_cost;
unsigned max_depth;
unsigned depth;
struct set *condition_variables;
};
} /* anonymous namespace */
bool
lower_if_to_cond_assign(gl_shader_stage stage, exec_list *instructions,
unsigned max_depth, unsigned min_branch_cost)
{
if (max_depth == UINT_MAX)
return false;
ir_if_to_cond_assign_visitor v(stage, max_depth, min_branch_cost);
visit_list_elements(&v, instructions);
return v.progress;
}
void
check_ir_node(ir_instruction *ir, void *data)
{
ir_if_to_cond_assign_visitor *v = (ir_if_to_cond_assign_visitor *)data;
switch (ir->ir_type) {
case ir_type_call:
case ir_type_discard:
case ir_type_loop:
case ir_type_loop_jump:
case ir_type_return:
case ir_type_emit_vertex:
case ir_type_end_primitive:
case ir_type_barrier:
v->found_unsupported_op = true;
break;
case ir_type_dereference_variable: {
ir_variable *var = ir->as_dereference_variable()->variable_referenced();
/* Lowering branches with TCS output accesses breaks many piglit tests,
* so don't touch them for now.
*/
if (v->stage == MESA_SHADER_TESS_CTRL &&
var->data.mode == ir_var_shader_out)
v->found_unsupported_op = true;
break;
}
/* SSBO, images, atomic counters are handled by ir_type_call */
case ir_type_texture:
v->found_expensive_op = true;
break;
case ir_type_dereference_array: {
ir_dereference_array *deref = ir->as_dereference_array();
if (deref->array_index->ir_type != ir_type_constant)
v->found_dynamic_arrayref = true;
} /* fall-through */
case ir_type_expression:
case ir_type_dereference_record:
if (v->is_then)
v->then_cost++;
else
v->else_cost++;
break;
default:
break;
}
}
void
move_block_to_cond_assign(void *mem_ctx,
ir_if *if_ir, ir_rvalue *cond_expr,
exec_list *instructions,
struct set *set)
{
foreach_in_list_safe(ir_instruction, ir, instructions) {
if (ir->ir_type == ir_type_assignment) {
ir_assignment *assign = (ir_assignment *)ir;
if (_mesa_set_search(set, assign) == NULL) {
_mesa_set_add(set, assign);
/* If the LHS of the assignment is a condition variable that was
* previously added, insert an additional assignment of false to
* the variable.
*/
const bool assign_to_cv =
_mesa_set_search(
set, assign->lhs->variable_referenced()) != NULL;
if (!assign->condition) {
if (assign_to_cv) {
assign->rhs =
new(mem_ctx) ir_expression(ir_binop_logic_and,
glsl_type::bool_type,
cond_expr->clone(mem_ctx, NULL),
assign->rhs);
} else {
assign->condition = cond_expr->clone(mem_ctx, NULL);
}
} else {
assign->condition =
new(mem_ctx) ir_expression(ir_binop_logic_and,
glsl_type::bool_type,
cond_expr->clone(mem_ctx, NULL),
assign->condition);
}
}
}
/* Now, move from the if block to the block surrounding it. */
ir->remove();
if_ir->insert_before(ir);
}
}
ir_visitor_status
ir_if_to_cond_assign_visitor::visit_enter(ir_if *ir)
{
(void) ir;
this->depth++;
return visit_continue;
}
ir_visitor_status
ir_if_to_cond_assign_visitor::visit_leave(ir_if *ir)
{
bool must_lower = this->depth-- > this->max_depth;
/* Only flatten when beyond the GPU's maximum supported nesting depth. */
if (!must_lower && this->min_branch_cost == 0)
return visit_continue;
this->found_unsupported_op = false;
this->found_expensive_op = false;
this->found_dynamic_arrayref = false;
this->then_cost = 0;
this->else_cost = 0;
ir_assignment *assign;
/* Check that both blocks don't contain anything we can't support. */
this->is_then = true;
foreach_in_list(ir_instruction, then_ir, &ir->then_instructions) {
visit_tree(then_ir, check_ir_node, this);
}
this->is_then = false;
foreach_in_list(ir_instruction, else_ir, &ir->else_instructions) {
visit_tree(else_ir, check_ir_node, this);
}
if (this->found_unsupported_op)
return visit_continue; /* can't handle inner unsupported opcodes */
/* Skip if the branch cost is high enough or if there's an expensive op.
*
* Also skip if non-constant array indices were encountered, since those
* can be out-of-bounds for a not-taken branch, and so generating an
* assignment would be incorrect. In the case of must_lower, it's up to the
* backend to deal with any potential fall-out (perhaps by translating the
* assignments to hardware-predicated moves).
*/
if (!must_lower &&
(this->found_expensive_op ||
this->found_dynamic_arrayref ||
MAX2(this->then_cost, this->else_cost) >= this->min_branch_cost))
return visit_continue;
void *mem_ctx = ralloc_parent(ir);
/* Store the condition to a variable. Move all of the instructions from
* the then-clause of the if-statement. Use the condition variable as a
* condition for all assignments.
*/
ir_variable *const then_var =
new(mem_ctx) ir_variable(glsl_type::bool_type,
"if_to_cond_assign_then",
ir_var_temporary);
ir->insert_before(then_var);
ir_dereference_variable *then_cond =
new(mem_ctx) ir_dereference_variable(then_var);
assign = new(mem_ctx) ir_assignment(then_cond, ir->condition);
ir->insert_before(assign);
move_block_to_cond_assign(mem_ctx, ir, then_cond,
&ir->then_instructions,
this->condition_variables);
/* Add the new condition variable to the hash table. This allows us to
* find this variable when lowering other (enclosing) if-statements.
*/
_mesa_set_add(this->condition_variables, then_var);
/* If there are instructions in the else-clause, store the inverse of the
* condition to a variable. Move all of the instructions from the
* else-clause if the if-statement. Use the (inverse) condition variable
* as a condition for all assignments.
*/
if (!ir->else_instructions.is_empty()) {
ir_variable *const else_var =
new(mem_ctx) ir_variable(glsl_type::bool_type,
"if_to_cond_assign_else",
ir_var_temporary);
ir->insert_before(else_var);
ir_dereference_variable *else_cond =
new(mem_ctx) ir_dereference_variable(else_var);
ir_rvalue *inverse =
new(mem_ctx) ir_expression(ir_unop_logic_not,
then_cond->clone(mem_ctx, NULL));
assign = new(mem_ctx) ir_assignment(else_cond, inverse);
ir->insert_before(assign);
move_block_to_cond_assign(mem_ctx, ir, else_cond,
&ir->else_instructions,
this->condition_variables);
/* Add the new condition variable to the hash table. This allows us to
* find this variable when lowering other (enclosing) if-statements.
*/
_mesa_set_add(this->condition_variables, else_var);
}
ir->remove();
this->progress = true;
return visit_continue;
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.