text stringlengths 54 60.6k |
|---|
<commit_before>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <iostream>
#include <string>
#include <vector>
#include <exception>
#include <fstream>
#include <iomanip>
#include <limits>
#include <algorithm>
#include <ArgumentList.hpp>
#include <Observation.hpp>
#include <InitializeOpenCL.hpp>
#include <Kernel.hpp>
#include <SNR.hpp>
#include <utils.hpp>
#include <Timer.hpp>
#include <Stats.hpp>
typedef float dataType;
std::string typeName("float");
int main(int argc, char * argv[]) {
unsigned int nrIterations = 0;
unsigned int clPlatformID = 0;
unsigned int clDeviceID = 0;
unsigned int minThreads = 0;
unsigned int maxThreadsPerBlock = 0;
unsigned int maxItemsPerThread = 0;
unsigned int maxColumns = 0;
unsigned int maxRows = 0;
AstroData::Observation observation;
try {
isa::utils::ArgumentList args(argc, argv);
nrIterations = args.getSwitchArgument< unsigned int >("-iterations");
clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");
observation.setPadding(args.getSwitchArgument< unsigned int >("-padding"));
minThreads = args.getSwitchArgument< unsigned int >("-min_threads");
maxThreadsPerBlock = args.getSwitchArgument< unsigned int >("-max_threads");
maxItemsPerThread = args.getSwitchArgument< unsigned int >("-max_items");
maxColumns = args.getSwitchArgument< unsigned int >("-max_columns");
maxRows = args.getSwitchArgument< unsigned int >("-max_rows");
observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), 0.0, 0.0);
observation.setPeriodRange(args.getSwitchArgument< unsigned int >("-periods"), 0, 0);
observation.setNrBins(args.getSwitchArgument< unsigned int >("-bins"));
} catch ( isa::utils::EmptyCommandLine &err ) {
std::cerr << argv[0] << " -iterations ... -opencl_platform ... -opencl_device ... -padding ... -min_threads ... -max_threads ... -max_items ... -max_columns ... -max_rows ... -dms ... -periods ... -bins ... " << std::endl;
return 1;
} catch ( std::exception &err ) {
std::cerr << err.what() << std::endl;
return 1;
}
// Initialize OpenCL
cl::Context * clContext = new cl::Context();
std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >();
std::vector< cl::Device > * clDevices = new std::vector< cl::Device >();
std::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >();
isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues);
// Allocate memory
std::vector< dataType > foldedData = std::vector< dataType >(observation.getNrBins() * observation.getNrPeriods() * observation.getNrPaddedDMs());
cl::Buffer foldedData_d;
std::vector< dataType > snrs = std::vector< dataType >(observation.getNrPeriods() * observation.getNrPaddedDMs());
cl::Buffer snrs_d;
try {
foldedData_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, foldedData.size() * sizeof(dataType), 0, 0);
snrs_d = cl::Buffer(*clContext, CL_MEM_WRITE_ONLY, snrs.size() * sizeof(dataType), 0, 0);
} catch ( cl::Error &err ) {
std::cerr << "OpenCL error allocating memory: " << isa::utils::toString(err.err()) << "." << std::endl;
return 1;
}
srand(time(0));
for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {
for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) {
for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) {
foldedData[(bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + DM] = static_cast< dataType >(rand() % 10);
}
}
}
std::fill(snrs.begin(), snrs.end(), static_cast< dataType >(0));
// Copy data structures to device
try {
clQueues->at(clDeviceID)[0].enqueueWriteBuffer(foldedData_d, CL_FALSE, 0, foldedData.size() * sizeof(dataType), reinterpret_cast< void * >(foldedData.data()));
clQueues->at(clDeviceID)[0].enqueueWriteBuffer(snrs_d, CL_FALSE, 0, snrs.size() * sizeof(dataType), reinterpret_cast< void * >(snrs.data()));
} catch ( cl::Error &err ) {
std::cerr << "OpenCL error H2D transfer: " << isa::utils::toString(err.err()) << "." << std::endl;
return 1;
}
// Find the parameters
std::vector< unsigned int > DMsPerBlock;
for ( unsigned int DMs = minThreads; DMs <= maxColumns; DMs += minThreads ) {
if ( (observation.getNrPaddedDMs() % DMs) == 0 ) {
DMsPerBlock.push_back(DMs);
}
}
std::vector< unsigned int > periodsPerBlock;
for ( unsigned int periods = 1; periods <= maxRows; periods++ ) {
if ( (observation.getNrPeriods() % periods) == 0 ) {
periodsPerBlock.push_back(periods);
}
}
std::cout << std::fixed << std::endl;
std::cout << "# nrDMs nrPeriods nrBins DMsPerBlock periodsPerBlock DMsPerThread periodsPerThread GFLOP/s err time err" << std::endl << std::endl;
for ( std::vector< unsigned int >::iterator DMs = DMsPerBlock.begin(); DMs != DMsPerBlock.end(); ++DMs ) {
for ( std::vector< unsigned int >::iterator periods = periodsPerBlock.begin(); periods != periodsPerBlock.end(); ++periods ) {
if ( (*DMs * *periods) > maxThreadsPerBlock ) {
break;
}
for ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItemsPerThread; DMsPerThread++ ) {
if ( observation.getNrPaddedDMs() % (*DMs * DMsPerThread) != 0 ) {
continue;
}
for ( unsigned int periodsPerThread = 1; periodsPerThread <= maxItemsPerThread; periodsPerThread++ ) {
if ( observation.getNrPeriods() % (*periods * periodsPerThread) != 0 ) {
continue;
}
if ( DMsPerThread + periodsPerThread > maxItemsPerThread ) {
break;
}
// Generate kernel
double flops = isa::utils::giga(static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods() * observation.getNrBins());
isa::utils::Timer timer;
isa::utils::Stats< double > stats;
cl::Event event;
cl::Kernel * kernel;
std::string * code = PulsarSearch::getSNROpenCL(*DMs, *periods, DMsPerThread, periodsPerThread, typeName, observation);
try {
kernel = isa::OpenCL::compile("snr", *code, "-cl-mad-enable -Werror", *clContext, clDevices->at(clDeviceID));
} catch ( isa::OpenCL::OpenCLError &err ) {
std::cerr << err.what() << std::endl;
continue;
}
cl::NDRange global(observation.getNrPaddedDMs() / DMsPerThread, observation.getNrPeriods() / periodsPerThread);
cl::NDRange local(*DMs, *periods);
kernel->setArg(0, foldedData_d);
kernel->setArg(1, snrs_d);
// Warm-up run
try {
clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);
event.wait();
} catch ( cl::Error &err ) {
std::cerr << "OpenCL error kernel execution: " << isa::utils::toString(err.err()) << "." << std::endl;
continue;
}
// Tuning runs
try {
for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {
timer.start();
clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);
event.wait();
timer.stop();
stats.addElement(flops / timer.getLastRunTime());
}
} catch ( cl::Error &err ) {
std::cerr << "OpenCL error kernel execution: " << isa::utils::toString(err.err()) << "." << std::endl;
continue;
}
std::cout << observation.getNrDMs() << " " << observation.getNrPeriods() << " " << observation.getNrBins() << " " << *DMs << " " << *periods << " " << DMsPerThread << " " << periodsPerThread << " " << std::setprecision(3) << stats.getAverage() << " " << stats.getStdDev() << " " << std::setprecision(6) << timer.getAverageTime() << " " << timer.getStdDev() << std::endl;
}
}
}
}
std::cout << std::endl;
return 0;
}
<commit_msg>Updated the tuner.<commit_after>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <iostream>
#include <string>
#include <vector>
#include <exception>
#include <fstream>
#include <iomanip>
#include <limits>
#include <algorithm>
#include <ArgumentList.hpp>
#include <Observation.hpp>
#include <InitializeOpenCL.hpp>
#include <Kernel.hpp>
#include <SNR.hpp>
#include <utils.hpp>
#include <Timer.hpp>
#include <Stats.hpp>
typedef float dataType;
std::string typeName("float");
int main(int argc, char * argv[]) {
bool dSNR = false;
unsigned int nrIterations = 0;
unsigned int clPlatformID = 0;
unsigned int clDeviceID = 0;
unsigned int threadUnit = 0;
unsigned int threadInc = 0;
unsigned int minThreads = 0;
unsigned int maxThreadsPerBlock = 0;
unsigned int maxItemsPerThread = 0;
unsigned int maxColumns = 0;
unsigned int maxRows = 0;
AstroData::Observation observation;
try {
isa::utils::ArgumentList args(argc, argv);
dSNR = args.getSwitch("-dedispersed");
bool fSNR = args.getSwitch("-folded");
if ( (dSNR && fSNR) || (!dSNR && ! fSNR) ) {
throw std::exception();
}
nrIterations = args.getSwitchArgument< unsigned int >("-iterations");
clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");
observation.setPadding(args.getSwitchArgument< unsigned int >("-padding"));
threadUnit = args.getSwitchArgument< unsigned int >("-thread_unit");
threadInc = args.getSwitchArgument< unsigned int >("-thread_inc");
minThreads = args.getSwitchArgument< unsigned int >("-min_threads");
maxThreadsPerBlock = args.getSwitchArgument< unsigned int >("-max_threads");
maxItemsPerThread = args.getSwitchArgument< unsigned int >("-max_items");
maxColumns = args.getSwitchArgument< unsigned int >("-max_columns");
maxRows = args.getSwitchArgument< unsigned int >("-max_rows");
if ( dSNR ) {
observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples"));
}
observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), 0.0, 0.0);
observation.setPeriodRange(args.getSwitchArgument< unsigned int >("-periods"), 0, 0);
observation.setNrBins(args.getSwitchArgument< unsigned int >("-bins"));
} catch ( isa::utils::EmptyCommandLine & err ) {
std::cerr << argv[0] << " [-dedispersed | -folded] -iterations ... -opencl_platform ... -opencl_device ... -padding ... -thread_unit ... -thread_inc ... -min_threads ... -max_threads ... -max_items ... -max_columns ... -max_rows ... -dms ..." << std::endl;
std::cerr << "\t -dedispersed -samples ..." << std::endl;
std::cerr << "\t -folded -pb ... -pt ... -periods .... -bins ..." << std::endl;
return 1;
} catch ( std::exception & err ) {
std::cerr << err.what() << std::endl;
return 1;
}
// Initialize OpenCL
cl::Context * clContext = new cl::Context();
std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >();
std::vector< cl::Device > * clDevices = new std::vector< cl::Device >();
std::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >();
isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues);
// Allocate memory
std::vector< dataType > foldedData, snrs;
std::vector< dataType > transposedData, maxS, meanS, rmsS;
cl::Buffer foldedData_d, snrs_d;
cl::Buffer tranposedData_d, maxS_d, meanS_d, rmsS_d;
if ( dSNR ) {
foldedData.resize(observation.getNrBins() * observation.getNrPeriods() * observation.getNrPaddedBins());
snrs.resize(observation.getNrPeriods() * observation.getNrPaddedDMs());
} else {
tranposedData.resize(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs());
maxS.resize(observation.getNrPaddedDMs());
meanS.resize(observation.getNrPaddedDMs());
rmsS.resize(observation.getNrPaddedDMs());
}
try {
if ( dSNR ) {
transposedData_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, transposedData.size() * sizeof(dataType), 0, 0);
maxS_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, maxS.size() * sizeof(dataType), 0, 0);
meanS_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, meanS.size() * sizeof(dataType), 0, 0);
rmsS_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, rmsS.size() * sizeof(dataType), 0, 0);
} else {
foldedData_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, foldedData.size() * sizeof(dataType), 0, 0);
snrs_d = cl::Buffer(*clContext, CL_MEM_WRITE_ONLY, snrs.size() * sizeof(dataType), 0, 0);
}
} catch ( cl::Error & err ) {
std::cerr << "OpenCL error allocating memory: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl;
return 1;
}
srand(time(0));
if ( dSNR ) {
for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {
for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {
transposedData[(sample * observation.getNrPaddedDMs()) + dm] = static_cast< dataType >(rand() % 10);
}
}
std::fill(maxS.begin(), maxS.end(), static_cast< dataType >(0));
std::fill(meanS.begin(), meanS.end(), static_cast< dataType >(0));
std::fill(rmsS.begin(), rmsS.end(), static_cast< dataType >(0));
std::fill(maxS_c.begin(), maxS_c.end(), static_cast< dataType >(0));
std::fill(meanS_c.begin(), meanS_c.end(), static_cast< dataType >(0));
std::fill(rmsS_c.begin(), rmsS_c.end(), static_cast< dataType >(0));
} else {
for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {
for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) {
for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) {
foldedData[(bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + DM] = static_cast< dataType >(rand() % 10);
}
}
}
std::fill(snrs.begin(), snrs.end(), static_cast< dataType >(0));
std::fill(snrs_c.begin(), snrs_c.end(), static_cast< dataType >(0));
}
// Copy data structures to device
try {
if ( dSNR ) {
clQueues->at(clDeviceID)[0].enqueueWriteBuffer(transposedData_d, CL_FALSE, 0, transposedData.size() * sizeof(dataType), reinterpret_cast< void * >(transposedData.data()));
clQueues->at(clDeviceID)[0].enqueueWriteBuffer(maxS_d, CL_FALSE, 0, maxS.size() * sizeof(dataType), reinterpret_cast< void * >(maxS.data()));
clQueues->at(clDeviceID)[0].enqueueWriteBuffer(meanS_d, CL_FALSE, 0, meanS.size() * sizeof(dataType), reinterpret_cast< void * >(meanS.data()));
clQueues->at(clDeviceID)[0].enqueueWriteBuffer(rmsS_d, CL_FALSE, 0, rmsS.size() * sizeof(dataType), reinterpret_cast< void * >(rmsS.data()));
} else {
clQueues->at(clDeviceID)[0].enqueueWriteBuffer(foldedData_d, CL_FALSE, 0, foldedData.size() * sizeof(dataType), reinterpret_cast< void * >(foldedData.data()));
clQueues->at(clDeviceID)[0].enqueueWriteBuffer(snrs_d, CL_FALSE, 0, snrs.size() * sizeof(dataType), reinterpret_cast< void * >(snrs.data()));
}
} catch ( cl::Error & err ) {
std::cerr << "OpenCL error H2D transfer: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl;
return 1;
}
// Find the parameters
std::vector< unsigned int > DMsPerBlock;
for ( unsigned int DMs = minThreads; DMs <= maxColumns; DMs += threadInc ) {
if ( (observation.getNrPaddedDMs() % DMs) == 0 ) {
DMsPerBlock.push_back(DMs);
}
}
std::vector< unsigned int > periodsPerBlock;
if ( !dSNR ) {
for ( unsigned int periods = 1; periods <= maxRows; periods++ ) {
if ( (observation.getNrPeriods() % periods) == 0 ) {
periodsPerBlock.push_back(periods);
}
}
}
std::cout << std::fixed << std::endl;
if ( dSNR ) {
std::cout << "# nrDMs nrSamples DMsPerBlock DMsPerThread GFLOP/s GB/s time stdDeviation COV" << std::endl << std::endl;
} else {
std::cout << "# nrDMs nrPeriods nrBins DMsPerBlock periodsPerBlock DMsPerThread periodsPerThread GFLOP/s GB/s time stdDeviation COV" << std::endl << std::endl;
}
for ( std::vector< unsigned int >::iterator DMs = DMsPerBlock.begin(); DMs != DMsPerBlock.end(); ++DMs ) {
if ( dSNR ) {
if ( *DMs % threadUnit != 0 ) {
continue;
}
for ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItemsPerThread; DMsPerThread++ ) {
if ( observation.getNrPaddedDMs() % (*DMs * DMsPerThread) != 0 ) {
continue;
}
if ( (4 * DMsPerThread) > maxItemsPerThread ) {
break;
}
// Generate kernel
double flops = isa::utils::giga((static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrSamplesPerSecond() * 3) + (static_cast< long long unsigned int >(observation.getNrDMs()) * 12));
double gbs = isa::utils::giga((static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrSamplesPerSecond() * sizeof(dataType)) + (static_cast< long long unsigned int >(observation.getNrDMs()) * 3 * sizeof(dataType)));
cl::Event event;
cl::Kernel * kernel;
isa::utils::Timer timer;
std::string * code = PulsarSearch::getSNRDedispersedOpenCL(*DMs, DMsPerThread, typeName, observation);
try {
kernel = isa::OpenCL::compile("snrDedispersed", *code, "-cl-mad-enable -Werror", *clContext, clDevices->at(clDeviceID));
} catch ( isa::OpenCL::OpenCLError & err ) {
std::cerr << err.what() << std::endl;
continue;
}
delete code;
cl::NDRange global(observation.getNrPaddedDMs() / DMsPerThread);
cl::NDRange local(*DMs);
kernel->setArg(0, 0);
kernel->setArg(1, transposedData_d);
kernel->setArg(2, maxS_d);
kernel->setArg(3, meanS_d);
kernel->setArg(4, rmsS_d);
// Warm-up run
try {
clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);
event.wait();
} catch ( cl::Error & err ) {
std::cerr << "OpenCL error kernel execution: " << isa::utils::toString(err.err()) << "." << std::endl;
continue;
}
// Tuning runs
try {
for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {
timer.start();
clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);
event.wait();
timer.stop();
}
} catch ( cl::Error & err ) {
std::cerr << "OpenCL error kernel execution: " << isa::utils::toString(err.err()) << "." << std::endl;
continue;
}
std::cout << observation.getNrDMs() << " " << observation.getNrSamplesPerSecond() << " ";
std::cout << *DMs << " " << DMsPerThread << " ";
std::cout << std::setprecision(3);
std::cout << flops / timer.getAverageTime() << " " << gbs / timer.getAverageTime() << " ";
std::cout << std::setprecision(6);
std::cout << timer.getAverageTime() << " " << timer.getStandardDeviation() << " " << timer.getCoefficientOfVariation() << std::endl;
}
} else {
for ( std::vector< unsigned int >::iterator periods = periodsPerBlock.begin(); periods != periodsPerBlock.end(); ++periods ) {
if ( (*DMs * *periods) > maxThreadsPerBlock ) {
break;
} else if ( (*DMs * *periods) % threadUnit != 0 ) {
continue;
}
for ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItemsPerThread; DMsPerThread++ ) {
if ( observation.getNrPaddedDMs() % (*DMs * DMsPerThread) != 0 ) {
continue;
}
for ( unsigned int periodsPerThread = 1; periodsPerThread <= maxItemsPerThread; periodsPerThread++ ) {
if ( observation.getNrPeriods() % (*periods * periodsPerThread) != 0 ) {
continue;
}
if ( DMsPerThread + periodsPerThread + (3 * DMsPerThread * periodsPerThread) > maxItemsPerThread ) {
break;
}
// Generate kernel
double flops = isa::utils::giga((static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods() * observation.getNrBins() * 3) + (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods() * 4));
double gbs = isa::utils::giga((static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods() * observation.getNrBins() * sizeof(dataType)) + (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods() * sizeof(dataType)));
cl::Event event;
cl::Kernel * kernel;
isa::utils::Timer timer;
std::string * code = PulsarSearch::getSNRFoldedOpenCL(*DMs, *periods, DMsPerThread, periodsPerThread, typeName, observation);
try {
kernel = isa::OpenCL::compile("snrFolded", *code, "-cl-mad-enable -Werror", *clContext, clDevices->at(clDeviceID));
} catch ( isa::OpenCL::OpenCLError & err ) {
std::cerr << err.what() << std::endl;
continue;
}
delete code;
cl::NDRange global(observation.getNrPaddedDMs() / DMsPerThread, observation.getNrPeriods() / periodsPerThread);
cl::NDRange local(*DMs, *periods);
kernel->setArg(0, foldedData_d);
kernel->setArg(1, snrs_d);
// Warm-up run
try {
clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);
event.wait();
} catch ( cl::Error & err ) {
std::cerr << "OpenCL error kernel execution: " << isa::utils::toString(err.err()) << "." << std::endl;
continue;
}
// Tuning runs
try {
for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {
timer.start();
clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);
event.wait();
timer.stop();
}
} catch ( cl::Error & err ) {
std::cerr << "OpenCL error kernel execution: " << isa::utils::toString(err.err()) << "." << std::endl;
continue;
}
std::cout << observation.getNrDMs() << " " << observation.getNrPeriods() << " " << observation.getNrBins() << " ";
std::cout << *DMs << " " << *periods << " " << DMsPerThread << " " << periodsPerThread << " ";
std::cout << std::setprecision(3);
std::cout << flops / timer.getAverageTime() << " " << gbs / timer.getAverageTime() << " ";
std::cout << std::setprecision(6);
std::cout << timer.getAverageTime() << " " << timer.getStandardDeviation() << " " << timer.getCoefficientOfVariation() << std::endl;
}
}
}
}
}
std::cout << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>#include "AlembicMetadataUtils.h"
#include <icustattribcontainer.h>
#include <custattrib.h>
#include "AlembicObject.h"
Alembic::Abc::ICompoundProperty getCompoundFromObject(Alembic::Abc::IObject& object)
{
const Alembic::Abc::MetaData &md = object.getMetaData();
if(Alembic::AbcGeom::IXform::matches(md)) {
return Alembic::AbcGeom::IXform(object,Alembic::Abc::kWrapExisting).getSchema();
} else if(Alembic::AbcGeom::IPolyMesh::matches(md)) {
return Alembic::AbcGeom::IPolyMesh(object,Alembic::Abc::kWrapExisting).getSchema();
} else if(Alembic::AbcGeom::ICurves::matches(md)) {
return Alembic::AbcGeom::ICurves(object,Alembic::Abc::kWrapExisting).getSchema();
} else if(Alembic::AbcGeom::INuPatch::matches(md)) {
return Alembic::AbcGeom::INuPatch(object,Alembic::Abc::kWrapExisting).getSchema();
} else if(Alembic::AbcGeom::IPoints::matches(md)) {
return Alembic::AbcGeom::IPoints(object,Alembic::Abc::kWrapExisting).getSchema();
} else if(Alembic::AbcGeom::ISubD::matches(md)) {
return Alembic::AbcGeom::ISubD(object,Alembic::Abc::kWrapExisting).getSchema();
} else if(Alembic::AbcGeom::ICamera::matches(md)) {
return Alembic::AbcGeom::ICamera(object,Alembic::Abc::kWrapExisting).getSchema();
}
return Alembic::Abc::ICompoundProperty();
}
void importMetadata(Alembic::AbcGeom::IObject& iObj)
{
Alembic::AbcGeom::IObject* metadataChild = NULL;
if(getCompoundFromObject(iObj).getPropertyHeader(".metadata") == NULL){
return;
}
Alembic::Abc::IStringArrayProperty metaDataProp = Alembic::Abc::IStringArrayProperty( getCompoundFromObject(iObj), ".metadata" );
Alembic::Abc::StringArraySamplePtr ptr = metaDataProp.getValue(0);
//for(unsigned int i=0;i<ptr->size();i++){
// const char* name = ptr->get()[i].c_str();
// Alembic::Abc::StringArraySamplePtr ptr = metaDataProp.getValue(0);
//
//}
char szBuffer[10000];
sprintf_s( szBuffer, 10000,
"include \"Exocortex-Metadata.mcr\"\n"
"CreateAlembicMetadataModifier $\n"
"InitAlembicMetadataModifier $ \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \n",
(0 < ptr->size()) ? ptr->get()[0].c_str() : "",
(1 < ptr->size()) ? ptr->get()[1].c_str() : "",
(2 < ptr->size()) ? ptr->get()[2].c_str() : "",
(3 < ptr->size()) ? ptr->get()[3].c_str() : "",
(4 < ptr->size()) ? ptr->get()[4].c_str() : "",
(5 < ptr->size()) ? ptr->get()[5].c_str() : "",
(6 < ptr->size()) ? ptr->get()[6].c_str() : "",
(7 < ptr->size()) ? ptr->get()[7].c_str() : "",
(8 < ptr->size()) ? ptr->get()[8].c_str() : "",
(9 < ptr->size()) ? ptr->get()[9].c_str() : "",
(10 < ptr->size()) ? ptr->get()[10].c_str() : "",
(11 < ptr->size()) ? ptr->get()[11].c_str() : "",
(12 < ptr->size()) ? ptr->get()[12].c_str() : "",
(13 < ptr->size()) ? ptr->get()[13].c_str() : "",
(14 < ptr->size()) ? ptr->get()[14].c_str() : "",
(15 < ptr->size()) ? ptr->get()[15].c_str() : "",
(16 < ptr->size()) ? ptr->get()[16].c_str() : "",
(17 < ptr->size()) ? ptr->get()[17].c_str() : "",
(18 < ptr->size()) ? ptr->get()[18].c_str() : "",
(19 < ptr->size()) ? ptr->get()[19].c_str() : ""
//"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20"
);
ExecuteMAXScriptScript( szBuffer );
}
Modifier* FindModifier(INode* node, char* name)
{
int i = 0;
int idx = 0;
Modifier* pRetMod = NULL;
while(true){
Modifier* pMod;
IDerivedObject* pObj = GET_MAX_INTERFACE()->FindModifier(*node, i, idx, pMod);
if(!pObj){
break;
}
if(strstr(pMod->GetName(), name) != NULL){
pRetMod = pMod;
break;
}
//const char* cname = pObj->GetClassName();
//const char* oname = pMod->GetObjectName();
//const char* name = pMod->GetName();
i++;
}
return pRetMod;
}
void SaveMetaData(INode* node, AlembicObject* object)
{
if(object == NULL){
return;
}
if(object->GetNumSamples() > 0){
return;
}
Modifier* pMod = FindModifier(node, "metadata");
if(!pMod){
return;
}
ICustAttribContainer* cont = pMod->GetCustAttribContainer();
if(!cont){
return;
}
std::vector<std::string> metaData(20);
size_t offset = 0;
//for(int i=0; i<cont->GetNumCustAttribs(); i++)
//{
CustAttrib* ca = cont->GetCustAttrib(0);
//const char* name = ca->GetName();
IParamBlock2 *pblock = ca->GetParamBlockByID(0);
if(pblock){
int nNumParams = pblock->NumParams();
for(int i=0; i<nNumParams; i++){
ParamID id = pblock->IndextoID(i);
//MSTR name = pblock->GetLocalName(id, 0);
MSTR value = pblock->GetStr(id, 0);
metaData[offset++] = value;
}
}
//}
if(metaData.size() > 0){
Alembic::Abc::OStringArrayProperty metaDataProperty = Alembic::Abc::OStringArrayProperty(
object->GetCompound(), ".metadata", object->GetCompound().getMetaData(), object->GetCurrentJob()->GetAnimatedTs() );
Alembic::Abc::StringArraySample metaDataSample(&metaData.front(),metaData.size());
metaDataProperty.set(metaDataSample);
}
}<commit_msg>-fixed broken metadata export<commit_after>#include "AlembicMetadataUtils.h"
#include <icustattribcontainer.h>
#include <custattrib.h>
#include "AlembicObject.h"
Alembic::Abc::ICompoundProperty getCompoundFromObject(Alembic::Abc::IObject& object)
{
const Alembic::Abc::MetaData &md = object.getMetaData();
if(Alembic::AbcGeom::IXform::matches(md)) {
return Alembic::AbcGeom::IXform(object,Alembic::Abc::kWrapExisting).getSchema();
} else if(Alembic::AbcGeom::IPolyMesh::matches(md)) {
return Alembic::AbcGeom::IPolyMesh(object,Alembic::Abc::kWrapExisting).getSchema();
} else if(Alembic::AbcGeom::ICurves::matches(md)) {
return Alembic::AbcGeom::ICurves(object,Alembic::Abc::kWrapExisting).getSchema();
} else if(Alembic::AbcGeom::INuPatch::matches(md)) {
return Alembic::AbcGeom::INuPatch(object,Alembic::Abc::kWrapExisting).getSchema();
} else if(Alembic::AbcGeom::IPoints::matches(md)) {
return Alembic::AbcGeom::IPoints(object,Alembic::Abc::kWrapExisting).getSchema();
} else if(Alembic::AbcGeom::ISubD::matches(md)) {
return Alembic::AbcGeom::ISubD(object,Alembic::Abc::kWrapExisting).getSchema();
} else if(Alembic::AbcGeom::ICamera::matches(md)) {
return Alembic::AbcGeom::ICamera(object,Alembic::Abc::kWrapExisting).getSchema();
}
return Alembic::Abc::ICompoundProperty();
}
void importMetadata(Alembic::AbcGeom::IObject& iObj)
{
Alembic::AbcGeom::IObject* metadataChild = NULL;
if(getCompoundFromObject(iObj).getPropertyHeader(".metadata") == NULL){
return;
}
Alembic::Abc::IStringArrayProperty metaDataProp = Alembic::Abc::IStringArrayProperty( getCompoundFromObject(iObj), ".metadata" );
Alembic::Abc::StringArraySamplePtr ptr = metaDataProp.getValue(0);
//for(unsigned int i=0;i<ptr->size();i++){
// const char* name = ptr->get()[i].c_str();
// Alembic::Abc::StringArraySamplePtr ptr = metaDataProp.getValue(0);
//
//}
char szBuffer[10000];
sprintf_s( szBuffer, 10000,
"include \"Exocortex-Metadata.mcr\"\n"
"CreateAlembicMetadataModifier $\n"
"InitAlembicMetadataModifier $ \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \n",
(0 < ptr->size()) ? ptr->get()[0].c_str() : "",
(1 < ptr->size()) ? ptr->get()[1].c_str() : "",
(2 < ptr->size()) ? ptr->get()[2].c_str() : "",
(3 < ptr->size()) ? ptr->get()[3].c_str() : "",
(4 < ptr->size()) ? ptr->get()[4].c_str() : "",
(5 < ptr->size()) ? ptr->get()[5].c_str() : "",
(6 < ptr->size()) ? ptr->get()[6].c_str() : "",
(7 < ptr->size()) ? ptr->get()[7].c_str() : "",
(8 < ptr->size()) ? ptr->get()[8].c_str() : "",
(9 < ptr->size()) ? ptr->get()[9].c_str() : "",
(10 < ptr->size()) ? ptr->get()[10].c_str() : "",
(11 < ptr->size()) ? ptr->get()[11].c_str() : "",
(12 < ptr->size()) ? ptr->get()[12].c_str() : "",
(13 < ptr->size()) ? ptr->get()[13].c_str() : "",
(14 < ptr->size()) ? ptr->get()[14].c_str() : "",
(15 < ptr->size()) ? ptr->get()[15].c_str() : "",
(16 < ptr->size()) ? ptr->get()[16].c_str() : "",
(17 < ptr->size()) ? ptr->get()[17].c_str() : "",
(18 < ptr->size()) ? ptr->get()[18].c_str() : "",
(19 < ptr->size()) ? ptr->get()[19].c_str() : ""
//"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20"
);
ExecuteMAXScriptScript( szBuffer );
}
Modifier* FindModifier(INode* node, char* name)
{
int i = 0;
int idx = 0;
Modifier* pRetMod = NULL;
while(true){
Modifier* pMod;
IDerivedObject* pObj = GET_MAX_INTERFACE()->FindModifier(*node, i, idx, pMod);
if(!pObj){
break;
}
if(strstr(pMod->GetName(), name) != NULL){
pRetMod = pMod;
break;
}
//const char* cname = pObj->GetClassName();
//const char* oname = pMod->GetObjectName();
//const char* name = pMod->GetName();
i++;
}
return pRetMod;
}
void SaveMetaData(INode* node, AlembicObject* object)
{
if(object == NULL){
return;
}
if(object->GetNumSamples() > 0){
return;
}
Modifier* pMod = FindModifier(node, "Metadata");
if(!pMod){
return;
}
ICustAttribContainer* cont = pMod->GetCustAttribContainer();
if(!cont){
return;
}
std::vector<std::string> metaData(20);
size_t offset = 0;
//for(int i=0; i<cont->GetNumCustAttribs(); i++)
//{
CustAttrib* ca = cont->GetCustAttrib(0);
//const char* name = ca->GetName();
IParamBlock2 *pblock = ca->GetParamBlockByID(0);
if(pblock){
int nNumParams = pblock->NumParams();
for(int i=0; i<nNumParams; i++){
ParamID id = pblock->IndextoID(i);
//MSTR name = pblock->GetLocalName(id, 0);
MSTR value = pblock->GetStr(id, 0);
metaData[offset++] = value;
}
}
//}
if(metaData.size() > 0){
Alembic::Abc::OStringArrayProperty metaDataProperty = Alembic::Abc::OStringArrayProperty(
object->GetCompound(), ".metadata", object->GetCompound().getMetaData(), object->GetCurrentJob()->GetAnimatedTs() );
Alembic::Abc::StringArraySample metaDataSample(&metaData.front(),metaData.size());
metaDataProperty.set(metaDataSample);
}
}<|endoftext|> |
<commit_before>/*
* Copyright 2010-2011 Alessandro Francescon
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string>
#include <exception>
#include <stdlib.h>
#include <zxing/common/Counted.h>
#include <zxing/Binarizer.h>
#include <zxing/MultiFormatReader.h>
#include <zxing/Result.h>
#include <zxing/ReaderException.h>
#include <zxing/common/GlobalHistogramBinarizer.h>
#include <zxing/Exception.h>
#include <zxing/common/IllegalArgumentException.h>
#include <zxing/BinaryBitmap.h>
#include <zxing/DecodeHints.h>
#include <zxing/qrcode/QRCodeReader.h>
#include <zxing/MultiFormatReader.h>
#include <zxing/MatSource.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace std;
using namespace zxing;
using namespace zxing::qrcode;
using namespace cv;
void printUsage(char** argv) {
// Print usage
cout << "Usage: " << argv[0] << " [-d <DEVICE>] [-w <CAPTUREWIDTH>] [-h <CAPTUREHEIGHT>]" << endl
<< "Read QR code from given video device." << endl
<< endl;
}
Point toCvPoint(Ref<ResultPoint> resultPoint) {
return Point(resultPoint->getX(), resultPoint->getY());
}
int main(int argc, char** argv) {
int deviceId = 0;
int captureWidth = 640;
int captureHeight = 480;
bool multi = false;
for (int j = 0; j < argc; j++) {
// Get arg
string arg = argv[j];
if (arg.compare("-d") == 0) {
if ((j + 1) < argc) {
// Set device id
deviceId = atoi(argv[++j]);
} else {
// Log
cerr << "Missing device id after -d" << endl;
printUsage(argv);
return 1;
}
} else if (arg.compare("-w") == 0) {
if ((j + 1) < argc) {
// Set capture width
captureWidth = atoi(argv[++j]);
} else {
// Log
cerr << "Missing width after -w" << endl;
printUsage(argv);
return 1;
}
} else if (arg.compare("-h") == 0) {
if ((j + 1) < argc) {
// Set capture height
captureHeight = atoi(argv[++j]);
} else {
// Log
cerr << "Missing height after -h" << endl;
printUsage(argv);
return 1;
}
} else if (arg.compare("-m") == 0) {
// Set multi to true
multi = true;
}
}
// Log
cout << "Capturing from device " << deviceId << "..." << endl;
// Open video captire
VideoCapture videoCapture(deviceId);
if (!videoCapture.isOpened()) {
// Log
cerr << "Open video capture failed on device id: " << deviceId << endl;
return -1;
}
if (!videoCapture.set(CV_CAP_PROP_FRAME_WIDTH, captureWidth)) {
// Log
cerr << "Failed to set frame width: " << captureWidth << " (ignoring)" << endl;
}
if (!videoCapture.set(CV_CAP_PROP_FRAME_HEIGHT, captureHeight)) {
// Log
cerr << "Failed to set frame height: " << captureHeight << " (ignoring)" << endl;
}
// The captured image and its grey conversion
Mat image, grey;
// Open output window
namedWindow("ZXing", cv::WINDOW_AUTOSIZE);
// Stopped flag will be set to -1 from subsequent wayKey() if no key was pressed
int stopped = -1;
while (stopped == -1) {
// Capture image
bool result = videoCapture.read(image);
if (result) {
// Convert to grayscale
cvtColor(image, grey, CV_BGR2GRAY);
try {
// Create luminance source
Ref<LuminanceSource> source = MatSource::create(grey);
// Search for QR code
Ref<Reader> reader;
if (multi) {
reader.reset(new MultiFormatReader);
} else {
reader.reset(new QRCodeReader);
}
Ref<Binarizer> binarizer(new GlobalHistogramBinarizer(source));
Ref<BinaryBitmap> bitmap(new BinaryBitmap(binarizer));
Ref<Result> result(reader->decode(bitmap, DecodeHints(DecodeHints::TRYHARDER_HINT)));
// Get result point count
int resultPointCount = result->getResultPoints()->size();
for (int j = 0; j < resultPointCount; j++) {
// Draw circle
circle(image, toCvPoint(result->getResultPoints()[j]), 10, Scalar( 110, 220, 0 ), 2);
}
// Draw boundary on image
if (resultPointCount > 1) {
for (int j = 0; j < resultPointCount; j++) {
// Get start result point
Ref<ResultPoint> previousResultPoint = (j > 0) ? result->getResultPoints()[j - 1] : result->getResultPoints()[resultPointCount - 1];
// Draw line
line(image, toCvPoint(previousResultPoint), toCvPoint(result->getResultPoints()[j]), Scalar( 110, 220, 0 ), 2, 8 );
// Update previous point
previousResultPoint = result->getResultPoints()[j];
}
}
if (resultPointCount > 0) {
// Draw text
putText(image, result->getText()->getText(), toCvPoint(result->getResultPoints()[0]), FONT_HERSHEY_PLAIN, 1, Scalar( 110, 220, 0 ));
}
} catch (const ReaderException& e) {
cerr << e.what() << " (ignoring)" << endl;
} catch (const zxing::IllegalArgumentException& e) {
cerr << e.what() << " (ignoring)" << endl;
} catch (const zxing::Exception& e) {
cerr << e.what() << " (ignoring)" << endl;
} catch (const std::exception& e) {
cerr << e.what() << " (ignoring)" << endl;
}
// Show captured image
imshow("ZXing", image);
// Wait a key for 1 millis
stopped = waitKey(1);
} else {
// Log
cerr << "video capture failed" << endl;
}
}
// Release video capture
videoCapture.release();
return 0;
}
<commit_msg>Forward-compatible patches for opencv4<commit_after>/*
* Copyright 2010-2011 Alessandro Francescon
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string>
#include <exception>
#include <stdlib.h>
#include <zxing/common/Counted.h>
#include <zxing/Binarizer.h>
#include <zxing/MultiFormatReader.h>
#include <zxing/Result.h>
#include <zxing/ReaderException.h>
#include <zxing/common/GlobalHistogramBinarizer.h>
#include <zxing/Exception.h>
#include <zxing/common/IllegalArgumentException.h>
#include <zxing/BinaryBitmap.h>
#include <zxing/DecodeHints.h>
#include <zxing/qrcode/QRCodeReader.h>
#include <zxing/MultiFormatReader.h>
#include <zxing/MatSource.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace std;
using namespace zxing;
using namespace zxing::qrcode;
using namespace cv;
#if CV_MAJOR_VERSION >= 4
#ifndef CV_CAP_PROP_FRAME_WIDTH
#define CV_CAP_PROP_FRAME_WIDTH CAP_PROP_FRAME_WIDTH
#endif
#ifndef CV_CAP_PROP_FRAME_HEIGHT
#define CV_CAP_PROP_FRAME_HEIGHT CAP_PROP_FRAME_HEIGHT
#endif
#ifndef CV_BGR2GRAY
#define CV_BGR2GRAY COLOR_BGR2GRAY
#endif
#endif
void printUsage(char** argv) {
// Print usage
cout << "Usage: " << argv[0] << " [-d <DEVICE>] [-w <CAPTUREWIDTH>] [-h <CAPTUREHEIGHT>]" << endl
<< "Read QR code from given video device." << endl
<< endl;
}
Point toCvPoint(Ref<ResultPoint> resultPoint) {
return Point(resultPoint->getX(), resultPoint->getY());
}
int main(int argc, char** argv) {
int deviceId = 0;
int captureWidth = 640;
int captureHeight = 480;
bool multi = false;
for (int j = 0; j < argc; j++) {
// Get arg
string arg = argv[j];
if (arg.compare("-d") == 0) {
if ((j + 1) < argc) {
// Set device id
deviceId = atoi(argv[++j]);
} else {
// Log
cerr << "Missing device id after -d" << endl;
printUsage(argv);
return 1;
}
} else if (arg.compare("-w") == 0) {
if ((j + 1) < argc) {
// Set capture width
captureWidth = atoi(argv[++j]);
} else {
// Log
cerr << "Missing width after -w" << endl;
printUsage(argv);
return 1;
}
} else if (arg.compare("-h") == 0) {
if ((j + 1) < argc) {
// Set capture height
captureHeight = atoi(argv[++j]);
} else {
// Log
cerr << "Missing height after -h" << endl;
printUsage(argv);
return 1;
}
} else if (arg.compare("-m") == 0) {
// Set multi to true
multi = true;
}
}
// Log
cout << "Capturing from device " << deviceId << "..." << endl;
// Open video captire
VideoCapture videoCapture(deviceId);
if (!videoCapture.isOpened()) {
// Log
cerr << "Open video capture failed on device id: " << deviceId << endl;
return -1;
}
if (!videoCapture.set(CV_CAP_PROP_FRAME_WIDTH, captureWidth)) {
// Log
cerr << "Failed to set frame width: " << captureWidth << " (ignoring)" << endl;
}
if (!videoCapture.set(CV_CAP_PROP_FRAME_HEIGHT, captureHeight)) {
// Log
cerr << "Failed to set frame height: " << captureHeight << " (ignoring)" << endl;
}
// The captured image and its grey conversion
Mat image, grey;
// Open output window
namedWindow("ZXing", cv::WINDOW_AUTOSIZE);
// Stopped flag will be set to -1 from subsequent wayKey() if no key was pressed
int stopped = -1;
while (stopped == -1) {
// Capture image
bool result = videoCapture.read(image);
if (result) {
// Convert to grayscale
cvtColor(image, grey, CV_BGR2GRAY);
try {
// Create luminance source
Ref<LuminanceSource> source = MatSource::create(grey);
// Search for QR code
Ref<Reader> reader;
if (multi) {
reader.reset(new MultiFormatReader);
} else {
reader.reset(new QRCodeReader);
}
Ref<Binarizer> binarizer(new GlobalHistogramBinarizer(source));
Ref<BinaryBitmap> bitmap(new BinaryBitmap(binarizer));
Ref<Result> result(reader->decode(bitmap, DecodeHints(DecodeHints::TRYHARDER_HINT)));
// Get result point count
int resultPointCount = result->getResultPoints()->size();
for (int j = 0; j < resultPointCount; j++) {
// Draw circle
circle(image, toCvPoint(result->getResultPoints()[j]), 10, Scalar( 110, 220, 0 ), 2);
}
// Draw boundary on image
if (resultPointCount > 1) {
for (int j = 0; j < resultPointCount; j++) {
// Get start result point
Ref<ResultPoint> previousResultPoint = (j > 0) ? result->getResultPoints()[j - 1] : result->getResultPoints()[resultPointCount - 1];
// Draw line
line(image, toCvPoint(previousResultPoint), toCvPoint(result->getResultPoints()[j]), Scalar( 110, 220, 0 ), 2, 8 );
// Update previous point
previousResultPoint = result->getResultPoints()[j];
}
}
if (resultPointCount > 0) {
// Draw text
putText(image, result->getText()->getText(), toCvPoint(result->getResultPoints()[0]), FONT_HERSHEY_PLAIN, 1, Scalar( 110, 220, 0 ));
}
} catch (const ReaderException& e) {
cerr << e.what() << " (ignoring)" << endl;
} catch (const zxing::IllegalArgumentException& e) {
cerr << e.what() << " (ignoring)" << endl;
} catch (const zxing::Exception& e) {
cerr << e.what() << " (ignoring)" << endl;
} catch (const std::exception& e) {
cerr << e.what() << " (ignoring)" << endl;
}
// Show captured image
imshow("ZXing", image);
// Wait a key for 1 millis
stopped = waitKey(1);
} else {
// Log
cerr << "video capture failed" << endl;
}
}
// Release video capture
videoCapture.release();
return 0;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al.
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 Sony Pictures Imageworks nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/////////////////////////////////////////////////////////////////////////
/// \file
///
/// Shader interpreter implementation of string functions
/// such as format, concat, printf, etc.
///
/////////////////////////////////////////////////////////////////////////
#include <cstdarg>
#include <OpenImageIO/strutil.h>
#include <OpenImageIO/filesystem.h>
#include <OpenImageIO/fmath.h>
#include "oslexec_pvt.h"
#define USTR(cstr) (*((ustring *)&cstr))
OSL_NAMESPACE_ENTER
namespace pvt {
// Only define 2-arg version of concat, sort it out upstream
OSL_SHADEOP const char *
osl_concat_sss (const char *s, const char *t)
{
return ustring::sprintf("%s%s", s, t).c_str();
}
OSL_SHADEOP int
osl_strlen_is (const char *s)
{
return (int) USTR(s).length();
}
OSL_SHADEOP int
osl_hash_is (const char *s)
{
return (int) USTR(s).hash();
}
OSL_SHADEOP int
osl_getchar_isi (const char *str, int index)
{
return str && unsigned(index) < USTR(str).length() ? str[index] : 0;
}
OSL_SHADEOP int
osl_startswith_iss (const char *s_, const char *substr_)
{
ustring substr (USTR(substr_));
size_t substr_len = substr.length();
if (substr_len == 0) // empty substr always matches
return 1;
ustring s (USTR(s_));
size_t s_len = s.length();
if (substr_len > s_len) // longer needle than haystack can't
return 0; // match (including empty s)
return strncmp (s.c_str(), substr.c_str(), substr_len) == 0;
}
OSL_SHADEOP int
osl_endswith_iss (const char *s_, const char *substr_)
{
ustring substr (USTR(substr_));
size_t substr_len = substr.length();
if (substr_len == 0) // empty substr always matches
return 1;
ustring s (USTR(s_));
size_t s_len = s.length();
if (substr_len > s_len) // longer needle than haystack can't
return 0; // match (including empty s)
return strncmp (s.c_str()+s_len-substr_len, substr.c_str(), substr_len) == 0;
}
OSL_SHADEOP int
osl_stoi_is (const char *str)
{
return str ? Strutil::from_string<int>(str) : 0;
}
OSL_SHADEOP float
osl_stof_fs (const char *str)
{
return str ? Strutil::from_string<float>(str) : 0.0f;
}
OSL_SHADEOP const char *
osl_substr_ssii (const char *s_, int start, int length)
{
ustring s (USTR(s_));
int slen = int (s.length());
if (slen == 0)
return NULL; // No substring of empty string
int b = start;
if (b < 0)
b += slen;
b = Imath::clamp (b, 0, slen);
return ustring(s, b, Imath::clamp (length, 0, slen)).c_str();
}
OSL_SHADEOP int
osl_regex_impl (void *sg_, const char *subject_, void *results, int nresults,
const char *pattern, int fullmatch)
{
ShaderGlobals *sg = (ShaderGlobals *)sg_;
ShadingContext *ctx = sg->context;
const std::string &subject (ustring::from_unique(subject_).string());
match_results<std::string::const_iterator> mresults;
const regex ®ex (ctx->find_regex (USTR(pattern)));
if (nresults > 0) {
std::string::const_iterator start = subject.begin();
int res = fullmatch ? regex_match (subject, mresults, regex)
: regex_search (subject, mresults, regex);
int *m = (int *)results;
for (int r = 0; r < nresults; ++r) {
if (r/2 < (int)mresults.size()) {
if ((r & 1) == 0)
m[r] = mresults[r/2].first - start;
else
m[r] = mresults[r/2].second - start;
} else {
m[r] = USTR(pattern).length();
}
}
return res;
} else {
return fullmatch ? regex_match (subject, regex)
: regex_search (subject, regex);
}
}
OSL_SHADEOP const char *
osl_format (const char* format_str, ...)
{
va_list args;
va_start (args, format_str);
std::string s = Strutil::vformat (format_str, args);
va_end (args);
return ustring(s).c_str();
}
OSL_SHADEOP void
osl_printf (ShaderGlobals *sg, const char* format_str, ...)
{
va_list args;
va_start (args, format_str);
#if 0
// Make super sure we know we are excuting LLVM-generated code!
std::string newfmt = std::string("llvm: ") + format_str;
format_str = newfmt.c_str();
#endif
std::string s = Strutil::vformat (format_str, args);
va_end (args);
sg->context->messagef("%s", s);
}
OSL_SHADEOP void
osl_error (ShaderGlobals *sg, const char* format_str, ...)
{
va_list args;
va_start (args, format_str);
std::string s = Strutil::vformat (format_str, args);
va_end (args);
sg->context->errorf("%s", s);
}
OSL_SHADEOP void
osl_warning (ShaderGlobals *sg, const char* format_str, ...)
{
if (sg->context->allow_warnings()) {
va_list args;
va_start (args, format_str);
std::string s = Strutil::vformat (format_str, args);
va_end (args);
sg->context->warningf("%s", s);
}
}
OSL_SHADEOP void
osl_fprintf (ShaderGlobals *sg, const char *filename,
const char* format_str, ...)
{
va_list args;
va_start (args, format_str);
std::string s = Strutil::vformat (format_str, args);
va_end (args);
static OIIO::mutex fprintf_mutex;
OIIO::lock_guard lock (fprintf_mutex);
FILE *file = OIIO::Filesystem::fopen (filename, "a");
fputs (s.c_str(), file);
fclose (file);
}
OSL_SHADEOP int
osl_split (const char *str, ustring *results, const char *sep,
int maxsplit, int resultslen)
{
maxsplit = OIIO::clamp (maxsplit, 0, resultslen);
std::vector<std::string> splits;
Strutil::split (USTR(str).string(), splits, USTR(sep).string(), maxsplit);
int n = std::min (maxsplit, (int)splits.size());
for (int i = 0; i < n; ++i)
results[i] = ustring(splits[i]);
return n;
}
} // end namespace pvt
OSL_NAMESPACE_EXIT
<commit_msg>Speedup string concat op (#1104)<commit_after>/*
Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al.
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 Sony Pictures Imageworks nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/////////////////////////////////////////////////////////////////////////
/// \file
///
/// Shader interpreter implementation of string functions
/// such as format, concat, printf, etc.
///
/////////////////////////////////////////////////////////////////////////
#include <cstdarg>
#include <OpenImageIO/strutil.h>
#include <OpenImageIO/filesystem.h>
#include <OpenImageIO/fmath.h>
#include "oslexec_pvt.h"
#define USTR(cstr) (*((ustring *)&cstr))
OSL_NAMESPACE_ENTER
namespace pvt {
// Only define 2-arg version of concat, sort it out upstream
OSL_SHADEOP const char *
osl_concat_sss (const char *s, const char *t)
{
size_t sl = USTR(s).length();
size_t tl = USTR(t).length();
size_t len = sl + tl;
std::unique_ptr<char[]> heap_buf;
char local_buf[256];
char* buf = local_buf;
if (len > sizeof(local_buf)) {
heap_buf.reset(new char[len]);
buf = heap_buf.get();
}
memcpy(buf , s, sl);
memcpy(buf + sl, t, tl);
return ustring(local_buf, len).c_str();
}
OSL_SHADEOP int
osl_strlen_is (const char *s)
{
return (int) USTR(s).length();
}
OSL_SHADEOP int
osl_hash_is (const char *s)
{
return (int) USTR(s).hash();
}
OSL_SHADEOP int
osl_getchar_isi (const char *str, int index)
{
return str && unsigned(index) < USTR(str).length() ? str[index] : 0;
}
OSL_SHADEOP int
osl_startswith_iss (const char *s_, const char *substr_)
{
ustring substr (USTR(substr_));
size_t substr_len = substr.length();
if (substr_len == 0) // empty substr always matches
return 1;
ustring s (USTR(s_));
size_t s_len = s.length();
if (substr_len > s_len) // longer needle than haystack can't
return 0; // match (including empty s)
return strncmp (s.c_str(), substr.c_str(), substr_len) == 0;
}
OSL_SHADEOP int
osl_endswith_iss (const char *s_, const char *substr_)
{
ustring substr (USTR(substr_));
size_t substr_len = substr.length();
if (substr_len == 0) // empty substr always matches
return 1;
ustring s (USTR(s_));
size_t s_len = s.length();
if (substr_len > s_len) // longer needle than haystack can't
return 0; // match (including empty s)
return strncmp (s.c_str()+s_len-substr_len, substr.c_str(), substr_len) == 0;
}
OSL_SHADEOP int
osl_stoi_is (const char *str)
{
return str ? Strutil::from_string<int>(str) : 0;
}
OSL_SHADEOP float
osl_stof_fs (const char *str)
{
return str ? Strutil::from_string<float>(str) : 0.0f;
}
OSL_SHADEOP const char *
osl_substr_ssii (const char *s_, int start, int length)
{
ustring s (USTR(s_));
int slen = int (s.length());
if (slen == 0)
return NULL; // No substring of empty string
int b = start;
if (b < 0)
b += slen;
b = Imath::clamp (b, 0, slen);
return ustring(s, b, Imath::clamp (length, 0, slen)).c_str();
}
OSL_SHADEOP int
osl_regex_impl (void *sg_, const char *subject_, void *results, int nresults,
const char *pattern, int fullmatch)
{
ShaderGlobals *sg = (ShaderGlobals *)sg_;
ShadingContext *ctx = sg->context;
const std::string &subject (ustring::from_unique(subject_).string());
match_results<std::string::const_iterator> mresults;
const regex ®ex (ctx->find_regex (USTR(pattern)));
if (nresults > 0) {
std::string::const_iterator start = subject.begin();
int res = fullmatch ? regex_match (subject, mresults, regex)
: regex_search (subject, mresults, regex);
int *m = (int *)results;
for (int r = 0; r < nresults; ++r) {
if (r/2 < (int)mresults.size()) {
if ((r & 1) == 0)
m[r] = mresults[r/2].first - start;
else
m[r] = mresults[r/2].second - start;
} else {
m[r] = USTR(pattern).length();
}
}
return res;
} else {
return fullmatch ? regex_match (subject, regex)
: regex_search (subject, regex);
}
}
OSL_SHADEOP const char *
osl_format (const char* format_str, ...)
{
va_list args;
va_start (args, format_str);
std::string s = Strutil::vformat (format_str, args);
va_end (args);
return ustring(s).c_str();
}
OSL_SHADEOP void
osl_printf (ShaderGlobals *sg, const char* format_str, ...)
{
va_list args;
va_start (args, format_str);
#if 0
// Make super sure we know we are excuting LLVM-generated code!
std::string newfmt = std::string("llvm: ") + format_str;
format_str = newfmt.c_str();
#endif
std::string s = Strutil::vformat (format_str, args);
va_end (args);
sg->context->messagef("%s", s);
}
OSL_SHADEOP void
osl_error (ShaderGlobals *sg, const char* format_str, ...)
{
va_list args;
va_start (args, format_str);
std::string s = Strutil::vformat (format_str, args);
va_end (args);
sg->context->errorf("%s", s);
}
OSL_SHADEOP void
osl_warning (ShaderGlobals *sg, const char* format_str, ...)
{
if (sg->context->allow_warnings()) {
va_list args;
va_start (args, format_str);
std::string s = Strutil::vformat (format_str, args);
va_end (args);
sg->context->warningf("%s", s);
}
}
OSL_SHADEOP void
osl_fprintf (ShaderGlobals *sg, const char *filename,
const char* format_str, ...)
{
va_list args;
va_start (args, format_str);
std::string s = Strutil::vformat (format_str, args);
va_end (args);
static OIIO::mutex fprintf_mutex;
OIIO::lock_guard lock (fprintf_mutex);
FILE *file = OIIO::Filesystem::fopen (filename, "a");
fputs (s.c_str(), file);
fclose (file);
}
OSL_SHADEOP int
osl_split (const char *str, ustring *results, const char *sep,
int maxsplit, int resultslen)
{
maxsplit = OIIO::clamp (maxsplit, 0, resultslen);
std::vector<std::string> splits;
Strutil::split (USTR(str).string(), splits, USTR(sep).string(), maxsplit);
int n = std::min (maxsplit, (int)splits.size());
for (int i = 0; i < n; ++i)
results[i] = ustring(splits[i]);
return n;
}
} // end namespace pvt
OSL_NAMESPACE_EXIT
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sdgmoitm.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2007-04-11 16:09:23 $
*
* 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 _SDGMOITM_HXX
#define _SDGMOITM_HXX
#ifndef _GRFMGR_HXX
#include <goodies/grfmgr.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _SVDDEF_HXX
#include <svx/svddef.hxx>
#endif
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif
//------------------
// SdrGrafModeItem -
//------------------
class SVX_DLLPUBLIC SdrGrafModeItem : public SfxEnumItem
{
public:
TYPEINFO();
SdrGrafModeItem( GraphicDrawMode eMode = GRAPHICDRAWMODE_STANDARD ) : SfxEnumItem( SDRATTR_GRAFMODE, (USHORT)eMode ) {}
SdrGrafModeItem( SvStream& rIn ) : SfxEnumItem( SDRATTR_GRAFMODE, rIn ) {}
virtual SfxPoolItem* Clone( SfxItemPool* pPool = NULL ) const;
virtual SfxPoolItem* Create( SvStream& rIn, USHORT nVer ) const;
virtual USHORT GetValueCount() const;
GraphicDrawMode GetValue() const { return (GraphicDrawMode) SfxEnumItem::GetValue(); }
virtual String GetValueTextByPos( USHORT nPos ) const;
virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
SfxMapUnit eCoreMetric,
SfxMapUnit ePresMetric,
String& rText, const IntlWrapper * = 0) const;
};
#endif // _SDGMOITM_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.2.466); FILE MERGED 2008/04/01 15:49:36 thb 1.2.466.3: #i85898# Stripping all external header guards 2008/04/01 12:46:48 thb 1.2.466.2: #i85898# Stripping all external header guards 2008/03/31 14:18:15 rt 1.2.466.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sdgmoitm.hxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _SDGMOITM_HXX
#define _SDGMOITM_HXX
#include <goodies/grfmgr.hxx>
#include <svtools/eitem.hxx>
#include <svx/svddef.hxx>
#include "svx/svxdllapi.h"
//------------------
// SdrGrafModeItem -
//------------------
class SVX_DLLPUBLIC SdrGrafModeItem : public SfxEnumItem
{
public:
TYPEINFO();
SdrGrafModeItem( GraphicDrawMode eMode = GRAPHICDRAWMODE_STANDARD ) : SfxEnumItem( SDRATTR_GRAFMODE, (USHORT)eMode ) {}
SdrGrafModeItem( SvStream& rIn ) : SfxEnumItem( SDRATTR_GRAFMODE, rIn ) {}
virtual SfxPoolItem* Clone( SfxItemPool* pPool = NULL ) const;
virtual SfxPoolItem* Create( SvStream& rIn, USHORT nVer ) const;
virtual USHORT GetValueCount() const;
GraphicDrawMode GetValue() const { return (GraphicDrawMode) SfxEnumItem::GetValue(); }
virtual String GetValueTextByPos( USHORT nPos ) const;
virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
SfxMapUnit eCoreMetric,
SfxMapUnit ePresMetric,
String& rText, const IntlWrapper * = 0) const;
};
#endif // _SDGMOITM_HXX
<|endoftext|> |
<commit_before>/**
* @file lsh_test.cpp
*
* Unit tests for the 'LSHSearch' class.
*/
#include <mlpack/core.hpp>
#include <mlpack/core/metrics/lmetric.hpp>
#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"
#include <mlpack/methods/lsh/lsh_search.hpp>
#include <mlpack/methods/neighbor_search/neighbor_search.hpp>
using namespace std;
using namespace mlpack;
using namespace mlpack::neighbor;
double compute_recall(
const arma::Mat<size_t>& LSHneighbors,
const arma::Mat<size_t>& groundTruth)
{
const int queries = LSHneighbors.n_cols;
const int neigh = LSHneighbors.n_rows;
int found_same = 0;
for (size_t q = 0; q < queries; ++q)
{
for (size_t n = 0; n < neigh; ++n)
{
found_same+=(LSHneighbors(n,q)==groundTruth(n,q));
}
}
return static_cast<double>(found_same)/
(static_cast<double>(queries*neigh));
}
BOOST_AUTO_TEST_SUITE(LSHTest);
BOOST_AUTO_TEST_CASE(LSHSearchTest)
{
math::RandomSeed(time(0));
//kNN and LSH parameters (use LSH default parameters)
const int k = 4;
const int numTables = 30;
const int numProj = 10;
const double hashWidth = 0;
const int secondHashSize = 99901;
const int bucketSize = 500;
//test parameters
const double epsilon = 0.1; //allowed deviation from expected monotonicity
const int numTries = 5; //tries for each test before declaring failure
//read iris training and testing data as reference and query
const string data_train="iris_train.csv";
const string data_test="iris_test.csv";
arma::mat rdata;
arma::mat qdata;
data::Load(data_train, rdata, true);
data::Load(data_test, qdata, true);
//Run classic knn on reference data
AllkNN knn(rdata);
arma::Mat<size_t> groundTruth;
arma::mat groundDistances;
knn.Search(qdata, k, groundTruth, groundDistances);
//Test: Run LSH with varying number of tables, keeping all other parameters
//constant. Compute the recall, i.e. the number of reported neighbors that
//are real neighbors of the query.
//LSH's property is that (with high probability), increasing the number of
//tables will increase recall. Epsilon ensures that if noise lightly affects
//the projections, the test will not fail.
//This produces false negatives, so we attempt the test numTries times and
//only declare failure if all of them fail.
bool fail;
for (int t = 0; t < numTries; ++t){
fail = false;
const int Lsize = 6; //number of runs
const int L_value[] = {1, 8, 16, 32, 64, 128}; //number of tables
double L_value_recall[Lsize] = {0.0}; //recall of each LSH run
for (size_t l=0; l < Lsize; ++l)
{
//run LSH with only numTables varying (other values default)
LSHSearch<> lsh_test1(rdata, numProj, L_value[l],
hashWidth, secondHashSize, bucketSize);
arma::Mat<size_t> LSHneighbors;
arma::mat LSHdistances;
lsh_test1.Search(qdata, k, LSHneighbors, LSHdistances);
//compute recall for each query
L_value_recall[l] = compute_recall(LSHneighbors, groundTruth);
if (l > 0){
if(L_value_recall[l] < L_value_recall[l-1]-epsilon){
fail = true; //if test fails at one point, stop and retry
break;
}
}
}
if ( !fail )
{
break; //if test passes one time, it is sufficient
}
}
BOOST_REQUIRE(fail == false);
//Test: Run LSH with varying hash width, keeping all other parameters
//constant. Compute the recall, i.e. the number of reported neighbors that
//are real neighbors of the query.
//LSH's property is that (with high probability), increasing the hash width
//will increase recall. Epsilon ensures that if noise lightly affects the
//projections, the test will not fail.
const int Hsize = 7; //number of runs
const double H_value[] = {0.1, 0.5, 1, 5, 10, 50, 500}; //hash width
double H_value_recall[Hsize] = {0.0}; //recall of each run
for (size_t h=0; h < Hsize; ++h)
{
//run LSH with only hashWidth varying (other values default)
LSHSearch<> lsh_test2(rdata, numProj, numTables,
H_value[h], secondHashSize, bucketSize);
arma::Mat<size_t> LSHneighbors;
arma::mat LSHdistances;
lsh_test2.Search(qdata, k, LSHneighbors, LSHdistances);
//compute recall for each query
H_value_recall[h] = compute_recall(LSHneighbors, groundTruth);
if (h > 0)
BOOST_REQUIRE_GE(H_value_recall[h], H_value_recall[h-1]-epsilon);
}
//Test: Run LSH with varying number of projections, keeping other parameters
//constant. Compute the recall, i.e. the number of reported neighbors that
//are real neighbors of the query.
//LSH's property is that (with high probability), increasing the number of
//projections per table will decrease recall. Epsilon ensures that if noise
//lightly affects the projections, the test will not fail.
const int Psize = 5; //number of runs
const int P_value[] = {1, 10, 20, 50, 100}; //number of projections
double P_value_recall[Psize] = {0.0}; //recall of each run
for (size_t p=0; p < Psize; ++p)
{
//run LSH with only numProj varying (other values default)
LSHSearch<> lsh_test3(rdata, P_value[p], numTables,
hashWidth, secondHashSize, bucketSize);
arma::Mat<size_t> LSHneighbors;
arma::mat LSHdistances;
lsh_test3.Search(qdata, k, LSHneighbors, LSHdistances);
//compute recall for each query
P_value_recall[p] = compute_recall(LSHneighbors, groundTruth);
if (p > 0) //don't check first run, only that increasing P decreases recall
BOOST_REQUIRE_LE(P_value_recall[p] - epsilon, P_value_recall[p-1]);
}
//Test: Run a very expensive LSH search, with a large number of hash tables
//and a large hash width. This run should return an acceptable recall. We set
//the bar very low (recall >= 50%) to make sure that a test fail means bad
//implementation.
const int H_exp = 10000; //first-level hash width
const int K_exp = 1; //projections per table
const int T_exp = 128; //number of tables
const double recall_thresh_exp = 0.5;
LSHSearch<> lsh_test_exp(
rdata,
K_exp,
T_exp,
H_exp,
secondHashSize,
bucketSize);
arma::Mat<size_t> LSHneighbors_exp;
arma::mat LSHdistances_exp;
lsh_test_exp.Search(qdata, k, LSHneighbors_exp, LSHdistances_exp);
const double recall_exp = compute_recall(LSHneighbors_exp, groundTruth);
BOOST_REQUIRE_GE(recall_exp, recall_thresh_exp);
//Test: Run a very cheap LSH search, with parameters that should cause recall
//to be very low. Set the threshhold very high (recall <= 25%) to make sure
//that a test fail means bad implementation.
//This mainly checks that user-specified parameters are not ignored.
const int H_chp = 1; //small first-level hash width
const int K_chp = 1000; //large number of projections per table
const int T_chp = 1; //only one table
const double recall_thresh_chp = 0.25; //recall threshold
LSHSearch<> lsh_test_chp(
rdata,
K_chp,
T_chp,
H_chp,
secondHashSize,
bucketSize);
arma::Mat<size_t> LSHneighbors_chp;
arma::mat LSHdistances_chp;
lsh_test_chp.Search(qdata, k, LSHneighbors_chp, LSHdistances_chp);
const double recall_chp = compute_recall(LSHneighbors_chp, groundTruth);
BOOST_REQUIRE_LE(recall_chp, recall_thresh_chp);
}
BOOST_AUTO_TEST_CASE(LSHTrainTest)
{
// This is a not very good test that simply checks that the re-trained LSH
// model operates on the correct dimensionality and returns the correct number
// of results.
arma::mat referenceData = arma::randu<arma::mat>(3, 100);
arma::mat newReferenceData = arma::randu<arma::mat>(10, 400);
arma::mat queryData = arma::randu<arma::mat>(10, 200);
LSHSearch<> lsh(referenceData, 3, 2, 2.0, 11, 3);
lsh.Train(newReferenceData, 4, 3, 3.0, 12, 4);
arma::Mat<size_t> neighbors;
arma::mat distances;
lsh.Search(queryData, 3, neighbors, distances);
BOOST_REQUIRE_EQUAL(neighbors.n_cols, 200);
BOOST_REQUIRE_EQUAL(neighbors.n_rows, 3);
BOOST_REQUIRE_EQUAL(distances.n_cols, 200);
BOOST_REQUIRE_EQUAL(distances.n_rows, 3);
}
BOOST_AUTO_TEST_CASE(EmptyConstructorTest)
{
// If we create an empty LSH model and then call Search(), it should throw an
// exception.
LSHSearch<> lsh;
arma::mat dataset = arma::randu<arma::mat>(5, 50);
arma::mat distances;
arma::Mat<size_t> neighbors;
BOOST_REQUIRE_THROW(lsh.Search(dataset, 2, neighbors, distances),
std::invalid_argument);
// Now, train.
lsh.Train(dataset, 4, 3, 3.0, 12, 4);
lsh.Search(dataset, 3, neighbors, distances);
BOOST_REQUIRE_EQUAL(neighbors.n_cols, 50);
BOOST_REQUIRE_EQUAL(neighbors.n_rows, 3);
BOOST_REQUIRE_EQUAL(distances.n_cols, 50);
BOOST_REQUIRE_EQUAL(distances.n_rows, 3);
}
BOOST_AUTO_TEST_SUITE_END();
<commit_msg>Style Fixes In lsh_test<commit_after>/**
* @file lsh_test.cpp
*
* Unit tests for the 'LSHSearch' class.
*/
#include <mlpack/core.hpp>
#include <mlpack/core/metrics/lmetric.hpp>
#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"
#include <mlpack/methods/lsh/lsh_search.hpp>
#include <mlpack/methods/neighbor_search/neighbor_search.hpp>
using namespace std;
using namespace mlpack;
using namespace mlpack::neighbor;
double compute_recall(
const arma::Mat<size_t>& LSHneighbors,
const arma::Mat<size_t>& groundTruth)
{
const size_t queries = LSHneighbors.n_cols;
const size_t neigh = LSHneighbors.n_rows;
int found_same = 0;
for (size_t q = 0; q < queries; ++q)
{
for (size_t n = 0; n < neigh; ++n)
{
found_same+=(LSHneighbors(n,q)==groundTruth(n,q));
}
}
return static_cast<double>(found_same)/
(static_cast<double>(queries*neigh));
}
BOOST_AUTO_TEST_SUITE(LSHTest);
BOOST_AUTO_TEST_CASE(LSHSearchTest)
{
math::RandomSeed(time(0));
//kNN and LSH parameters (use LSH default parameters)
const int k = 4;
const int numTables = 30;
const int numProj = 10;
const double hashWidth = 0;
const int secondHashSize = 99901;
const int bucketSize = 500;
//test parameters
const double epsilon = 0.1; //allowed deviation from expected monotonicity
const int numTries = 5; //tries for each test before declaring failure
//read iris training and testing data as reference and query
const string trainSet="iris_train.csv";
const string testSet="iris_test.csv";
arma::mat rdata;
arma::mat qdata;
data::Load(trainSet, rdata, true);
data::Load(testSet, qdata, true);
//Run classic knn on reference data
AllkNN knn(rdata);
arma::Mat<size_t> groundTruth;
arma::mat groundDistances;
knn.Search(qdata, k, groundTruth, groundDistances);
//Test: Run LSH with varying number of tables, keeping all other parameters
//constant. Compute the recall, i.e. the number of reported neighbors that
//are real neighbors of the query.
//LSH's property is that (with high probability), increasing the number of
//tables will increase recall. Epsilon ensures that if noise lightly affects
//the projections, the test will not fail.
//This produces false negatives, so we attempt the test numTries times and
//only declare failure if all of them fail.
bool fail;
for (int t = 0; t < numTries; ++t){
fail = false;
const int lSize = 6; //number of runs
const int lValue[] = {1, 8, 16, 32, 64, 128}; //number of tables
double lValueRecall[lSize] = {0.0}; //recall of each LSH run
for (size_t l=0; l < lSize; ++l)
{
//run LSH with only numTables varying (other values default)
LSHSearch<> lsh_test1(rdata, numProj, lValue[l],
hashWidth, secondHashSize, bucketSize);
arma::Mat<size_t> LSHneighbors;
arma::mat LSHdistances;
lsh_test1.Search(qdata, k, LSHneighbors, LSHdistances);
//compute recall for each query
lValueRecall[l] = compute_recall(LSHneighbors, groundTruth);
if (l > 0){
if(lValueRecall[l] < lValueRecall[l-1]-epsilon){
fail = true; //if test fails at one point, stop and retry
break;
}
}
}
if ( !fail )
{
break; //if test passes one time, it is sufficient
}
}
BOOST_REQUIRE(fail == false);
//Test: Run LSH with varying hash width, keeping all other parameters
//constant. Compute the recall, i.e. the number of reported neighbors that
//are real neighbors of the query.
//LSH's property is that (with high probability), increasing the hash width
//will increase recall. Epsilon ensures that if noise lightly affects the
//projections, the test will not fail.
const int hSize = 7; //number of runs
const double hValue[] = {0.1, 0.5, 1, 5, 10, 50, 500}; //hash width
double hValueRecall[hSize] = {0.0}; //recall of each run
for (size_t h=0; h < hSize; ++h)
{
//run LSH with only hashWidth varying (other values default)
LSHSearch<> lsh_test2(
rdata,
numProj,
numTables,
hValue[h],
secondHashSize,
bucketSize);
arma::Mat<size_t> LSHneighbors;
arma::mat LSHdistances;
lsh_test2.Search(qdata, k, LSHneighbors, LSHdistances);
//compute recall for each query
hValueRecall[h] = compute_recall(LSHneighbors, groundTruth);
if (h > 0)
BOOST_REQUIRE_GE(hValueRecall[h], hValueRecall[h-1]-epsilon);
}
//Test: Run LSH with varying number of projections, keeping other parameters
//constant. Compute the recall, i.e. the number of reported neighbors that
//are real neighbors of the query.
//LSH's property is that (with high probability), increasing the number of
//projections per table will decrease recall. Epsilon ensures that if noise
//lightly affects the projections, the test will not fail.
const int pSize = 5; //number of runs
const int pValue[] = {1, 10, 20, 50, 100}; //number of projections
double pValueRecall[pSize] = {0.0}; //recall of each run
for (size_t p=0; p < pSize; ++p)
{
//run LSH with only numProj varying (other values default)
LSHSearch<> lsh_test3(
rdata,
pValue[p],
numTables,
hashWidth,
secondHashSize,
bucketSize);
arma::Mat<size_t> LSHneighbors;
arma::mat LSHdistances;
lsh_test3.Search(qdata, k, LSHneighbors, LSHdistances);
//compute recall for each query
pValueRecall[p] = compute_recall(LSHneighbors, groundTruth);
if (p > 0) //don't check first run, only that increasing P decreases recall
BOOST_REQUIRE_LE(pValueRecall[p] - epsilon, pValueRecall[p-1]);
}
//Test: Run a very expensive LSH search, with a large number of hash tables
//and a large hash width. This run should return an acceptable recall. We set
//the bar very low (recall >= 50%) to make sure that a test fail means bad
//implementation.
const int hExp = 10000; //first-level hash width
const int kExp = 1; //projections per table
const int tExp = 128; //number of tables
const double recallThreshExp = 0.5;
LSHSearch<> lsh_test_exp(
rdata,
kExp,
tExp,
hExp,
secondHashSize,
bucketSize);
arma::Mat<size_t> LSHneighborsExp;
arma::mat LSHdistancesExp;
lsh_test_exp.Search(qdata, k, LSHneighborsExp, LSHdistancesExp);
const double recallExp = compute_recall(LSHneighborsExp, groundTruth);
BOOST_REQUIRE_GE(recallExp, recallThreshExp);
//Test: Run a very cheap LSH search, with parameters that should cause recall
//to be very low. Set the threshhold very high (recall <= 25%) to make sure
//that a test fail means bad implementation.
//This mainly checks that user-specified parameters are not ignored.
const int hChp = 1; //small first-level hash width
const int kChp = 1000; //large number of projections per table
const int tChp = 1; //only one table
const double recallThreshChp = 0.25; //recall threshold
LSHSearch<> lsh_test_chp(
rdata,
kChp,
tChp,
hChp,
secondHashSize,
bucketSize);
arma::Mat<size_t> LSHneighborsChp;
arma::mat LSHdistancesChp;
lsh_test_chp.Search(qdata, k, LSHneighborsChp, LSHdistancesChp);
const double recallChp = compute_recall(LSHneighborsChp, groundTruth);
BOOST_REQUIRE_LE(recallChp, recallThreshChp);
}
BOOST_AUTO_TEST_CASE(LSHTrainTest)
{
// This is a not very good test that simply checks that the re-trained LSH
// model operates on the correct dimensionality and returns the correct number
// of results.
arma::mat referenceData = arma::randu<arma::mat>(3, 100);
arma::mat newReferenceData = arma::randu<arma::mat>(10, 400);
arma::mat queryData = arma::randu<arma::mat>(10, 200);
LSHSearch<> lsh(referenceData, 3, 2, 2.0, 11, 3);
lsh.Train(newReferenceData, 4, 3, 3.0, 12, 4);
arma::Mat<size_t> neighbors;
arma::mat distances;
lsh.Search(queryData, 3, neighbors, distances);
BOOST_REQUIRE_EQUAL(neighbors.n_cols, 200);
BOOST_REQUIRE_EQUAL(neighbors.n_rows, 3);
BOOST_REQUIRE_EQUAL(distances.n_cols, 200);
BOOST_REQUIRE_EQUAL(distances.n_rows, 3);
}
BOOST_AUTO_TEST_CASE(EmptyConstructorTest)
{
// If we create an empty LSH model and then call Search(), it should throw an
// exception.
LSHSearch<> lsh;
arma::mat dataset = arma::randu<arma::mat>(5, 50);
arma::mat distances;
arma::Mat<size_t> neighbors;
BOOST_REQUIRE_THROW(lsh.Search(dataset, 2, neighbors, distances),
std::invalid_argument);
// Now, train.
lsh.Train(dataset, 4, 3, 3.0, 12, 4);
lsh.Search(dataset, 3, neighbors, distances);
BOOST_REQUIRE_EQUAL(neighbors.n_cols, 50);
BOOST_REQUIRE_EQUAL(neighbors.n_rows, 3);
BOOST_REQUIRE_EQUAL(distances.n_cols, 50);
BOOST_REQUIRE_EQUAL(distances.n_rows, 3);
}
BOOST_AUTO_TEST_SUITE_END();
<|endoftext|> |
<commit_before>/*
* UNIX signal.h for Mickey Scheme
*
* Copyright (C) 2013 Christian Stigen Larsen
* Distributed under the LGPL 2.1; see LICENSE
*/
#include <signal.h>
#include <errno.h>
#include "mickey.h"
static const int SIGHANDLERS = 31;
static closure_t* sighandlers[SIGHANDLERS] = {NULL};
/*
* Dispatch signal to closure
*/
static void sighandler(int sig)
{
if ( signal<0 || sig > SIGHANDLERS )
return;
closure_t *proc = sighandlers[sig];
if ( proc == NULL )
return;
cons_t *p = new cons_t();
p->type = CLOSURE;
p->closure = proc;
eval(cons(p, cons(integer(sig))), proc->environment);
}
/*
* Setup a signal handler closure
*/
static sig_t set_handler(int sig, closure_t* hdl)
{
sighandlers[sig] = hdl;
return signal(sig, hdl!=NULL? sighandler : NULL);
}
extern "C" cons_t* proc_signal(cons_t* p, environment_t*)
{
assert_length(p, 2);
assert_type(INTEGER, car(p));
assert_type(CLOSURE, cadr(p));
integer_t sig = car(p)->number.integer;
closure_t* func = cadr(p)->closure;
if ( sig<0 || sig > SIGHANDLERS )
raise(runtime_exception(format("Invalid signal: %d", sig)));
if ( SIG_ERR == set_handler(sig, func) )
raise(runtime_exception(format("signal: %s", strerror(errno))));
return nil();
}
extern "C" cons_t* proc_deactivate_signal(cons_t* p, environment_t*)
{
assert_length(p, 1);
assert_type(INTEGER, car(p));
integer_t sig = car(p)->number.integer;
if ( sig<0 || sig > SIGHANDLERS )
raise(runtime_exception(format("Invalid signal: %d", sig)));
if ( SIG_ERR == set_handler(sig, NULL) )
raise(runtime_exception(strerror(errno)));
return nil();
}
<commit_msg>Bugfix; compare numbers, not function pointers...<commit_after>/*
* UNIX signal.h for Mickey Scheme
*
* Copyright (C) 2013 Christian Stigen Larsen
* Distributed under the LGPL 2.1; see LICENSE
*/
#include <signal.h>
#include <errno.h>
#include "mickey.h"
static const int SIGHANDLERS = 31;
static closure_t* sighandlers[SIGHANDLERS] = {NULL};
/*
* Dispatch signal to closure
*/
static void sighandler(int sig)
{
if ( sig<0 || sig > SIGHANDLERS )
return;
closure_t *proc = sighandlers[sig];
if ( proc == NULL )
return;
cons_t *p = new cons_t();
p->type = CLOSURE;
p->closure = proc;
eval(cons(p, cons(integer(sig))), proc->environment);
}
/*
* Setup a signal handler closure
*/
static sig_t set_handler(int sig, closure_t* hdl)
{
sighandlers[sig] = hdl;
return signal(sig, hdl!=NULL? sighandler : NULL);
}
extern "C" cons_t* proc_signal(cons_t* p, environment_t*)
{
assert_length(p, 2);
assert_type(INTEGER, car(p));
assert_type(CLOSURE, cadr(p));
integer_t sig = car(p)->number.integer;
closure_t* func = cadr(p)->closure;
if ( sig<0 || sig > SIGHANDLERS )
raise(runtime_exception(format("Invalid signal: %d", sig)));
if ( SIG_ERR == set_handler(sig, func) )
raise(runtime_exception(format("signal: %s", strerror(errno))));
return nil();
}
extern "C" cons_t* proc_deactivate_signal(cons_t* p, environment_t*)
{
assert_length(p, 1);
assert_type(INTEGER, car(p));
integer_t sig = car(p)->number.integer;
if ( sig<0 || sig > SIGHANDLERS )
raise(runtime_exception(format("Invalid signal: %d", sig)));
if ( SIG_ERR == set_handler(sig, NULL) )
raise(runtime_exception(strerror(errno)));
return nil();
}
<|endoftext|> |
<commit_before>#include "Toast.h"
#include "../utils/compiler.h"
USING_NS_CC;
Toast *Toast::makeText(cocos2d::Scene *scene, const std::string &text, Duration duration) {
Toast *ret = new (std::nothrow) Toast();
if (ret != nullptr && ret->initWithText(scene, text, duration)) {
ret->autorelease();
return ret;
}
CC_SAFE_DELETE(ret);
return nullptr;
}
bool Toast::initWithText(cocos2d::Scene *scene, const std::string &text, Duration duration) {
if (UNLIKELY(!Node::init())) {
return false;
}
_scene = scene;
_duration = duration;
const float width = maxWidth();
Label *label = Label::createWithSystemFont(text, "Arail", 12);
Size size = label->getContentSize();
if (size.width > width - 15.0f) {
label->setHorizontalAlignment(TextHAlignment::CENTER);
label->setDimensions(width - 15.0f, 0.0f);
size = label->getContentSize();
}
size.width += 15.0f;
size.height += 15.0f;
this->setContentSize(Size(size.width, size.height));
this->addChild(label);
label->setPosition(Vec2(size.width * 0.5f, size.height * 0.5f));
this->addChild(LayerColor::create(Color4B(0x20, 0x20, 0x20, 0xF0), size.width, size.height), -1);
this->setIgnoreAnchorPointForPosition(false);
this->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
float yPos = visibleSize.height * 0.15f;
if (yPos + size.height * 0.5f > visibleSize.height) {
yPos = visibleSize.height * 0.5f;
}
this->setPosition(Vec2(origin.x + visibleSize.width * 0.5f, origin.y + yPos));
return true;
}
void Toast::show() {
_scene->addChild(this, 100);
_scene = nullptr;
float dt = _duration == LENGTH_LONG ? 3.5f : 2.0f;
auto thiz = makeRef(this);
// FIXME: 当scene不在前台时,schedule的暂停机制引起Toast延迟remove
Director::getInstance()->getScheduler()->schedule([thiz](float) { thiz->removeFromParent(); },
this, 0.0f, 0U, dt, false, "Toast::show");
}
<commit_msg>修复一个fixme<commit_after>#include "Toast.h"
#include "../utils/compiler.h"
USING_NS_CC;
Toast *Toast::makeText(cocos2d::Scene *scene, const std::string &text, Duration duration) {
Toast *ret = new (std::nothrow) Toast();
if (ret != nullptr && ret->initWithText(scene, text, duration)) {
ret->autorelease();
return ret;
}
CC_SAFE_DELETE(ret);
return nullptr;
}
bool Toast::initWithText(cocos2d::Scene *scene, const std::string &text, Duration duration) {
if (UNLIKELY(!Node::init())) {
return false;
}
_scene = scene;
_duration = duration;
const float width = maxWidth();
Label *label = Label::createWithSystemFont(text, "Arail", 12);
Size size = label->getContentSize();
if (size.width > width - 15.0f) {
label->setHorizontalAlignment(TextHAlignment::CENTER);
label->setDimensions(width - 15.0f, 0.0f);
size = label->getContentSize();
}
size.width += 15.0f;
size.height += 15.0f;
this->setContentSize(Size(size.width, size.height));
this->addChild(label);
label->setPosition(Vec2(size.width * 0.5f, size.height * 0.5f));
this->addChild(LayerColor::create(Color4B(0x20, 0x20, 0x20, 0xF0), size.width, size.height), -1);
this->setIgnoreAnchorPointForPosition(false);
this->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
float yPos = visibleSize.height * 0.15f;
if (yPos + size.height * 0.5f > visibleSize.height) {
yPos = visibleSize.height * 0.5f;
}
this->setPosition(Vec2(origin.x + visibleSize.width * 0.5f, origin.y + yPos));
return true;
}
void Toast::show() {
_scene->addChild(this, 100);
_scene = nullptr;
float dt = _duration == LENGTH_LONG ? 3.5f : 2.0f;
auto thiz = makeRef(this);
Director::getInstance()->getScheduler()->schedule([thiz](float) { thiz->removeFromParent(); },
reinterpret_cast<void *>(1), 0.0f, 0U, dt, false, "Toast::show");
}
<|endoftext|> |
<commit_before>#include "argument_list.hpp"
#include "process.hpp"
#include "log/log.hpp"
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <system_error>
#include <iostream>
#include <boost/filesystem.hpp>
gorc::process::process(path const &executable,
argument_list const &args,
maybe<gorc::pipe*> std_input,
maybe<gorc::pipe*> std_output,
maybe<gorc::pipe*> std_error,
maybe<path> working_directory)
: std_input(std_input)
, std_output(std_output)
, std_error(std_error)
, working_directory(working_directory)
{
// LCOV_EXCL_START
// Not much hope capturing coverage between fork-exec
pid_t result = ::fork();
if(result < 0) {
throw std::system_error(errno, std::generic_category());
}
if(result == 0) {
// Inside child process
std::string prog_finalname = executable.filename().string();
// Child address space will be wiped out by exec()
// Don't need to free arguments.
std::vector<char *> finalargs;
finalargs.push_back(&prog_finalname[0]);
for(auto const &arg : args) {
finalargs.push_back(::strdup(arg.c_str()));
}
finalargs.push_back(nullptr);
internal_inside_child(executable, finalargs);
}
else {
// Inside parent process
internal_inside_parent(result);
}
// LCOV_EXCL_STOP
}
gorc::process::~process()
{
if(pid.has_value()) {
LOG_ERROR("zombie process not reaped");
try {
join();
// LCOV_EXCL_START
}
catch(std::exception const &e) {
LOG_ERROR(format("error while reaping: %s") % e.what());
}
// LCOV_EXCL_STOP
}
}
// LCOV_EXCL_START
// Inside child process between fork and exec
namespace {
void safe_dup2(int old_fd, int new_fd)
{
int result = 0;
do {
result = ::dup2(old_fd, new_fd);
} while(result < 0 && errno == EINTR);
if(result < 0) {
std::cerr << "[ERROR] " << std::generic_category().message(errno) << std::endl;
::abort();
}
}
}
void gorc::process::internal_inside_child(path const &executable,
std::vector<char *> const &args)
{
// Inside child.
// Close parent ends of pipes.
// Redirect and close original pipes.
if(std_input.has_value()) {
safe_dup2(std_input.get_value()->get_input().fd, STDIN_FILENO);
std_input.get_value()->close_input();
std_input.get_value()->close_output();
}
if(std_output.has_value()) {
safe_dup2(std_output.get_value()->get_output().fd, STDOUT_FILENO);
std_output.get_value()->close_input();
std_output.get_value()->close_output();
}
if(std_error.has_value()) {
safe_dup2(std_error.get_value()->get_output().fd, STDERR_FILENO);
std_error.get_value()->close_input();
std_error.get_value()->close_output();
}
if(working_directory.has_value()) {
boost::filesystem::current_path(working_directory.get_value());
}
std::string prog_name = executable.string();
::execvp(prog_name.c_str(), args.data());
// Still here? Must be an error.
std::cerr << "[ERROR] Cannot execute: "
<< std::generic_category().message(errno)
<< std::endl;
exit(126);
}
// LCOV_EXCL_STOP
void gorc::process::internal_inside_parent(::pid_t child_pid)
{
pid = child_pid;
// Close child ends of pipe
if(std_input.has_value()) {
std_input.get_value()->close_input();
}
if(std_output.has_value()) {
std_output.get_value()->close_output();
}
if(std_error.has_value()) {
std_error.get_value()->close_output();
}
}
int gorc::process::join()
{
if(pid.has_value()) {
int status = 0;
pid_t result = -1;
// LCOV_EXCL_START
do {
result = ::waitpid(pid.get_value(), &status, 0);
} while(result < 0 && errno == EINTR);
if(result < 0) {
// Essentially uncoverable - system would need to be in a bad state
throw std::system_error(errno, std::generic_category());
}
// LCOV_EXCL_STOP
pid = nothing;
if(WIFEXITED(status)) {
return WEXITSTATUS(status);
}
// LCOV_EXCL_START
else if(WIFSIGNALED(status)) {
LOG_ERROR(format("process terminated with signal: %s") %
strsignal(WTERMSIG(status)));
return 128 + WTERMSIG(status);
}
else {
LOG_ERROR("process terminated abnormally");
return 1;
}
// LCOV_EXCL_STOP
}
else {
throw std::logic_error("no process");
}
}
<commit_msg>Marked the process destructor as uncoverable<commit_after>#include "argument_list.hpp"
#include "process.hpp"
#include "log/log.hpp"
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <system_error>
#include <iostream>
#include <boost/filesystem.hpp>
gorc::process::process(path const &executable,
argument_list const &args,
maybe<gorc::pipe*> std_input,
maybe<gorc::pipe*> std_output,
maybe<gorc::pipe*> std_error,
maybe<path> working_directory)
: std_input(std_input)
, std_output(std_output)
, std_error(std_error)
, working_directory(working_directory)
{
// LCOV_EXCL_START
// Not much hope capturing coverage between fork-exec
pid_t result = ::fork();
if(result < 0) {
throw std::system_error(errno, std::generic_category());
}
if(result == 0) {
// Inside child process
std::string prog_finalname = executable.filename().string();
// Child address space will be wiped out by exec()
// Don't need to free arguments.
std::vector<char *> finalargs;
finalargs.push_back(&prog_finalname[0]);
for(auto const &arg : args) {
finalargs.push_back(::strdup(arg.c_str()));
}
finalargs.push_back(nullptr);
internal_inside_child(executable, finalargs);
}
else {
// Inside parent process
internal_inside_parent(result);
}
// LCOV_EXCL_STOP
}
// LCOV_EXCL_START
gorc::process::~process()
{
if(pid.has_value()) {
LOG_ERROR("zombie process not reaped");
try {
join();
}
catch(std::exception const &e) {
LOG_ERROR(format("error while reaping: %s") % e.what());
}
}
}
// LCOV_EXCL_STOP
// LCOV_EXCL_START
// Inside child process between fork and exec
namespace {
void safe_dup2(int old_fd, int new_fd)
{
int result = 0;
do {
result = ::dup2(old_fd, new_fd);
} while(result < 0 && errno == EINTR);
if(result < 0) {
std::cerr << "[ERROR] " << std::generic_category().message(errno) << std::endl;
::abort();
}
}
}
void gorc::process::internal_inside_child(path const &executable,
std::vector<char *> const &args)
{
// Inside child.
// Close parent ends of pipes.
// Redirect and close original pipes.
if(std_input.has_value()) {
safe_dup2(std_input.get_value()->get_input().fd, STDIN_FILENO);
std_input.get_value()->close_input();
std_input.get_value()->close_output();
}
if(std_output.has_value()) {
safe_dup2(std_output.get_value()->get_output().fd, STDOUT_FILENO);
std_output.get_value()->close_input();
std_output.get_value()->close_output();
}
if(std_error.has_value()) {
safe_dup2(std_error.get_value()->get_output().fd, STDERR_FILENO);
std_error.get_value()->close_input();
std_error.get_value()->close_output();
}
if(working_directory.has_value()) {
boost::filesystem::current_path(working_directory.get_value());
}
std::string prog_name = executable.string();
::execvp(prog_name.c_str(), args.data());
// Still here? Must be an error.
std::cerr << "[ERROR] Cannot execute: "
<< std::generic_category().message(errno)
<< std::endl;
exit(126);
}
// LCOV_EXCL_STOP
void gorc::process::internal_inside_parent(::pid_t child_pid)
{
pid = child_pid;
// Close child ends of pipe
if(std_input.has_value()) {
std_input.get_value()->close_input();
}
if(std_output.has_value()) {
std_output.get_value()->close_output();
}
if(std_error.has_value()) {
std_error.get_value()->close_output();
}
}
int gorc::process::join()
{
if(pid.has_value()) {
int status = 0;
pid_t result = -1;
// LCOV_EXCL_START
do {
result = ::waitpid(pid.get_value(), &status, 0);
} while(result < 0 && errno == EINTR);
if(result < 0) {
// Essentially uncoverable - system would need to be in a bad state
throw std::system_error(errno, std::generic_category());
}
// LCOV_EXCL_STOP
pid = nothing;
if(WIFEXITED(status)) {
return WEXITSTATUS(status);
}
// LCOV_EXCL_START
else if(WIFSIGNALED(status)) {
LOG_ERROR(format("process terminated with signal: %s") %
strsignal(WTERMSIG(status)));
return 128 + WTERMSIG(status);
}
else {
LOG_ERROR("process terminated abnormally");
return 1;
}
// LCOV_EXCL_STOP
}
else {
throw std::logic_error("no process");
}
}
<|endoftext|> |
<commit_before>// Begin CVS Header
// $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/layoutUI/CQLayoutMainWindow.cpp,v $
// $Revision: 1.11 $
// $Name: $
// $Author: urost $
// $Date: 2007/06/01 08:31:42 $
// End CVS Header
// Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
#include "CopasiDataModel/CCopasiDataModel.h"
#include "layout/CListOfLayouts.h"
#include "layout/CLayout.h"
#include "layout/CLBase.h"
#include"CQLayoutMainWindow.h"
//#include "sbmlDocumentLoader.h"
#include <string>
#include <iostream>
using namespace std;
CQLayoutMainWindow::CQLayoutMainWindow(QWidget *parent, const char *name) : QMainWindow(parent, name)
{
setCaption(tr("Reaction network graph"));
createActions();
createMenus();
// create split window
QSplitter *splitter = new QSplitter(Qt::Horizontal, this);
splitter->setCaption("Test");
//QLabel *label = new QLabel(splitter, "Test Label", 0);
//QTextEdit *testEditor = new QTextEdit(splitter);
timeSlider = new QSlider(Qt::Horizontal, splitter);
timeSlider->setRange(0, 100);
timeSlider->setValue(0);
//timeSlider->setTickmarks(QSlider::Below);
timeSlider->setDisabled(TRUE);
connect(timeSlider, SIGNAL(valueChanged(int)),
this, SLOT(showStep(int)));
// create sroll view
scrollView = new QScrollView(splitter);
//scrollView = new QScrollView(this);
scrollView->setCaption("Network Graph Viewer");
//scrollView->viewport()->setPaletteBackgroundColor(QColor(255,255,240));
scrollView->viewport()->setPaletteBackgroundColor(QColor(219, 235, 255));
//scrollView->viewport()->setMouseTracking(TRUE);
// Create OpenGL widget
//cout << "viewport: " << scrollView.viewport() << endl;
CListOfLayouts *pLayoutList;
if (CCopasiDataModel::Global != NULL)
{
pLayoutList = CCopasiDataModel::Global->getListOfLayouts();
}
else
pLayoutList = NULL;
glPainter = new CQGLNetworkPainter(scrollView->viewport());
if (pLayoutList != NULL)
{
CLayout * pLayout;
if (pLayoutList->size() > 0)
{
pLayout = (*pLayoutList)[0];
CLDimensions dim = pLayout->getDimensions();
CLPoint c1;
CLPoint c2(dim.getWidth(), dim.getHeight());
glPainter->setGraphSize(c1, c2);
glPainter->createGraph(pLayout); // create local data structures
//glPainter->drawGraph(); // create display list
}
}
// put OpenGL widget into scrollView
scrollView->addChild(glPainter);
//setCentralWidget(scrollView);
//scrollView->show();
setCentralWidget(splitter);
splitter->show();
//glPainter->drawGraph();
}
void CQLayoutMainWindow::createActions()
{
openSBMLFile = new QAction("SBML",
"Load SBML file",
CTRL + Key_F,
this);
openSBMLFile->setStatusTip("Load SBML file with/without layout");
connect(openSBMLFile, SIGNAL(activated()) , this, SLOT(loadSBMLFile()));
openDataFile = new QAction("data",
"Load Simulation Data",
CTRL + Key_D,
this);
openDataFile->setStatusTip("Load simulation data");
connect(openDataFile, SIGNAL(activated()), this, SLOT(loadData()));
closeAction = new QAction ("close",
"Close Window",
CTRL + Key_Q ,
this);
closeAction->setStatusTip("Close Layout Window");
connect(closeAction, SIGNAL(activated()), this, SLOT(closeApplication()));
runAnimation = new QAction("animate",
"Run animation",
CTRL + Key_A,
this);
runAnimation->setStatusTip("show complete animation sequence of current times series");
connect(runAnimation, SIGNAL(activated()), this, SLOT(showAnimation()));
rectangularShape = new QAction ("rectangle",
"rectangle",
CTRL + Key_R ,
this);
rectangularShape->setStatusTip("Show labels as rectangles");
connect(rectangularShape, SIGNAL(activated()), this, SLOT(mapLabelsToRectangles()));
circularShape = new QAction ("circle",
"circle",
CTRL + Key_C ,
this);
connect(circularShape, SIGNAL(activated()), this, SLOT(mapLabelsToCircles()));
circularShape->setStatusTip("Show labels as circles");
}
void CQLayoutMainWindow::createMenus()
{
fileMenu = new QPopupMenu(this);
openSBMLFile->addTo(fileMenu);
openDataFile->addTo(fileMenu);
fileMenu->insertSeparator();
closeAction->addTo(fileMenu);
actionsMenu = new QPopupMenu(this);
runAnimation->addTo(actionsMenu);
labelShapeMenu = new QPopupMenu(this);
rectangularShape->addTo(labelShapeMenu);
circularShape->addTo(labelShapeMenu);
optionsMenu = new QPopupMenu(this);
optionsMenu->insertItem("Shape of Label", labelShapeMenu);
menuBar()->insertItem("File", fileMenu);
menuBar()->insertItem("Actions", actionsMenu);
menuBar()->insertItem("Options", optionsMenu);
}
//void CQLayoutMainWindow::contextMenuEvent(QContextMenuEvent *cme){
// QPopupMenu *contextMenu = new QPopupMenu(this);
// exitAction->addTo(contextMenu);
// contextMenu->exec(cme->globalPos());
//}
void CQLayoutMainWindow::loadSBMLFile()
{
//string filename = "/localhome/ulla/project/data/peroxiShortNew.xml"; // test file
//string filename = "/home/ulla/project/simulation/data/peroxiShortNew.xml";
//SBMLDocumentLoader docLoader;
//network *networkP = docLoader.loadDocument(filename.c_str());
//glPainter->createGraph(networkP);
std::cout << "load SBMLfile" << std::endl;
CListOfLayouts *pLayoutList;
if (CCopasiDataModel::Global != NULL)
{
pLayoutList = CCopasiDataModel::Global->getListOfLayouts();
}
else
pLayoutList = NULL;
glPainter = new CQGLNetworkPainter(scrollView->viewport());
if (pLayoutList != NULL)
{
CLayout * pLayout;
if (pLayoutList->size() > 0)
{
pLayout = (*pLayoutList)[0];
CLDimensions dim = pLayout->getDimensions();
CLPoint c1;
CLPoint c2(dim.getWidth(), dim.getHeight());
glPainter->setGraphSize(c1, c2);
glPainter->createGraph(pLayout); // create local data structures
//glPainter->drawGraph(); // create display list
}
}
}
void CQLayoutMainWindow::mapLabelsToCircles()
{
if (glPainter != NULL)
{
glPainter->mapLabelsToCircles();
}
}
void CQLayoutMainWindow::mapLabelsToRectangles()
{
if (glPainter != NULL)
{
glPainter->mapLabelsToRectangles();
}
}
void CQLayoutMainWindow::loadData()
{
bool successfulP = glPainter->createDataSets();
if (successfulP)
{
this->timeSlider->setEnabled(true);
int maxVal = glPainter->getNumberOfSteps();
//std::cout << "number of steps: " << maxVal << std::endl;
this->timeSlider->setRange(0, maxVal);
glPainter->updateGL();
}
}
void CQLayoutMainWindow::showAnimation()
{
glPainter->runAnimation();
}
void CQLayoutMainWindow::showStep(int i)
{
glPainter->showStep(i);
}
void CQLayoutMainWindow::closeApplication()
{
close();
}
void CQLayoutMainWindow::closeEvent(QCloseEvent *event)
{
if (maybeSave())
{
//writeSettings();
event->accept();
}
else
{
event->ignore();
}
}
// returns true because window is opened from Copasi and can be easily reopened
bool CQLayoutMainWindow::maybeSave()
{
// int ret = QMessageBox::warning(this, "SimWiz",
// "Do you really want to quit?",
// // tr("Do you really want to quit?\n"
// // "XXXXXXXX"),
// QMessageBox::Yes | QMessageBox::Default,
// QMessageBox::No,
// QMessageBox::Cancel | QMessageBox::Escape);
// if (ret == QMessageBox::Yes)
// return true;
// else if (ret == QMessageBox::Cancel)
// return false;
return true;
}
//int main(int argc, char *argv[]) {
// //cout << argc << "------" << *argv << endl;
// QApplication app(argc,argv);
// CQLayoutMainWindow win;
// //app.setMainWidget(&gui);
// win.resize(400,230);
// win.show();
// return app.exec();
//}
<commit_msg>using the slide, a primitive kind of animation works<commit_after>// Begin CVS Header
// $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/layoutUI/CQLayoutMainWindow.cpp,v $
// $Revision: 1.12 $
// $Name: $
// $Author: urost $
// $Date: 2007/06/01 08:37:02 $
// End CVS Header
// Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
#include "CopasiDataModel/CCopasiDataModel.h"
#include "layout/CListOfLayouts.h"
#include "layout/CLayout.h"
#include "layout/CLBase.h"
#include"CQLayoutMainWindow.h"
//#include "sbmlDocumentLoader.h"
#include <string>
#include <iostream>
using namespace std;
CQLayoutMainWindow::CQLayoutMainWindow(QWidget *parent, const char *name) : QMainWindow(parent, name)
{
setCaption(tr("Reaction network graph"));
createActions();
createMenus();
// create split window
QSplitter *splitter = new QSplitter(Qt::Horizontal, this);
splitter->setCaption("Test");
//QLabel *label = new QLabel(splitter, "Test Label", 0);
//QTextEdit *testEditor = new QTextEdit(splitter);
timeSlider = new QSlider(Qt::Horizontal, splitter);
timeSlider->setRange(0, 100);
timeSlider->setValue(0);
//timeSlider->setTickmarks(QSlider::Below);
timeSlider->setDisabled(TRUE);
connect(timeSlider, SIGNAL(valueChanged(int)),
this, SLOT(showStep(int)));
// create sroll view
scrollView = new QScrollView(splitter);
//scrollView = new QScrollView(this);
scrollView->setCaption("Network Graph Viewer");
//scrollView->viewport()->setPaletteBackgroundColor(QColor(255,255,240));
scrollView->viewport()->setPaletteBackgroundColor(QColor(219, 235, 255));
//scrollView->viewport()->setMouseTracking(TRUE);
// Create OpenGL widget
//cout << "viewport: " << scrollView.viewport() << endl;
CListOfLayouts *pLayoutList;
if (CCopasiDataModel::Global != NULL)
{
pLayoutList = CCopasiDataModel::Global->getListOfLayouts();
}
else
pLayoutList = NULL;
glPainter = new CQGLNetworkPainter(scrollView->viewport());
if (pLayoutList != NULL)
{
CLayout * pLayout;
if (pLayoutList->size() > 0)
{
pLayout = (*pLayoutList)[0];
CLDimensions dim = pLayout->getDimensions();
CLPoint c1;
CLPoint c2(dim.getWidth(), dim.getHeight());
glPainter->setGraphSize(c1, c2);
glPainter->createGraph(pLayout); // create local data structures
//glPainter->drawGraph(); // create display list
}
}
// put OpenGL widget into scrollView
scrollView->addChild(glPainter);
//setCentralWidget(scrollView);
//scrollView->show();
setCentralWidget(splitter);
splitter->show();
//glPainter->drawGraph();
}
void CQLayoutMainWindow::createActions()
{
openSBMLFile = new QAction("SBML",
"Load SBML file",
CTRL + Key_F,
this);
openSBMLFile->setStatusTip("Load SBML file with/without layout");
connect(openSBMLFile, SIGNAL(activated()) , this, SLOT(loadSBMLFile()));
openDataFile = new QAction("data",
"Load Simulation Data",
CTRL + Key_D,
this);
openDataFile->setStatusTip("Load simulation data");
connect(openDataFile, SIGNAL(activated()), this, SLOT(loadData()));
closeAction = new QAction ("close",
"Close Window",
CTRL + Key_Q ,
this);
closeAction->setStatusTip("Close Layout Window");
connect(closeAction, SIGNAL(activated()), this, SLOT(closeApplication()));
runAnimation = new QAction("animate",
"Run animation",
CTRL + Key_A,
this);
runAnimation->setStatusTip("show complete animation sequence of current times series");
connect(runAnimation, SIGNAL(activated()), this, SLOT(showAnimation()));
rectangularShape = new QAction ("rectangle",
"rectangle",
CTRL + Key_R ,
this);
rectangularShape->setStatusTip("Show labels as rectangles");
connect(rectangularShape, SIGNAL(activated()), this, SLOT(mapLabelsToRectangles()));
circularShape = new QAction ("circle",
"circle",
CTRL + Key_C ,
this);
connect(circularShape, SIGNAL(activated()), this, SLOT(mapLabelsToCircles()));
circularShape->setStatusTip("Show labels as circles");
}
void CQLayoutMainWindow::createMenus()
{
fileMenu = new QPopupMenu(this);
openSBMLFile->addTo(fileMenu);
openDataFile->addTo(fileMenu);
fileMenu->insertSeparator();
closeAction->addTo(fileMenu);
actionsMenu = new QPopupMenu(this);
runAnimation->addTo(actionsMenu);
labelShapeMenu = new QPopupMenu(this);
rectangularShape->addTo(labelShapeMenu);
circularShape->addTo(labelShapeMenu);
optionsMenu = new QPopupMenu(this);
optionsMenu->insertItem("Shape of Label", labelShapeMenu);
menuBar()->insertItem("File", fileMenu);
menuBar()->insertItem("Actions", actionsMenu);
menuBar()->insertItem("Options", optionsMenu);
}
//void CQLayoutMainWindow::contextMenuEvent(QContextMenuEvent *cme){
// QPopupMenu *contextMenu = new QPopupMenu(this);
// exitAction->addTo(contextMenu);
// contextMenu->exec(cme->globalPos());
//}
void CQLayoutMainWindow::loadSBMLFile()
{
//string filename = "/localhome/ulla/project/data/peroxiShortNew.xml"; // test file
//string filename = "/home/ulla/project/simulation/data/peroxiShortNew.xml";
//SBMLDocumentLoader docLoader;
//network *networkP = docLoader.loadDocument(filename.c_str());
//glPainter->createGraph(networkP);
std::cout << "load SBMLfile" << std::endl;
CListOfLayouts *pLayoutList;
if (CCopasiDataModel::Global != NULL)
{
pLayoutList = CCopasiDataModel::Global->getListOfLayouts();
}
else
pLayoutList = NULL;
glPainter = new CQGLNetworkPainter(scrollView->viewport());
if (pLayoutList != NULL)
{
CLayout * pLayout;
if (pLayoutList->size() > 0)
{
pLayout = (*pLayoutList)[0];
CLDimensions dim = pLayout->getDimensions();
CLPoint c1;
CLPoint c2(dim.getWidth(), dim.getHeight());
glPainter->setGraphSize(c1, c2);
glPainter->createGraph(pLayout); // create local data structures
//glPainter->drawGraph(); // create display list
}
}
}
void CQLayoutMainWindow::mapLabelsToCircles()
{
if (glPainter != NULL)
{
glPainter->mapLabelsToCircles();
}
}
void CQLayoutMainWindow::mapLabelsToRectangles()
{
if (glPainter != NULL)
{
glPainter->mapLabelsToRectangles();
}
}
void CQLayoutMainWindow::loadData()
{
bool successfulP = glPainter->createDataSets();
if (successfulP)
{
this->timeSlider->setEnabled(true);
int maxVal = glPainter->getNumberOfSteps();
//std::cout << "number of steps: " << maxVal << std::endl;
this->timeSlider->setRange(0, maxVal);
glPainter->updateGL();
}
}
void CQLayoutMainWindow::showAnimation()
{
glPainter->runAnimation();
}
void CQLayoutMainWindow::showStep(int i)
{
glPainter->showStep(i);
glPainter->updateGL();
}
void CQLayoutMainWindow::closeApplication()
{
close();
}
void CQLayoutMainWindow::closeEvent(QCloseEvent *event)
{
if (maybeSave())
{
//writeSettings();
event->accept();
}
else
{
event->ignore();
}
}
// returns true because window is opened from Copasi and can be easily reopened
bool CQLayoutMainWindow::maybeSave()
{
// int ret = QMessageBox::warning(this, "SimWiz",
// "Do you really want to quit?",
// // tr("Do you really want to quit?\n"
// // "XXXXXXXX"),
// QMessageBox::Yes | QMessageBox::Default,
// QMessageBox::No,
// QMessageBox::Cancel | QMessageBox::Escape);
// if (ret == QMessageBox::Yes)
// return true;
// else if (ret == QMessageBox::Cancel)
// return false;
return true;
}
//int main(int argc, char *argv[]) {
// //cout << argc << "------" << *argv << endl;
// QApplication app(argc,argv);
// CQLayoutMainWindow win;
// //app.setMainWidget(&gui);
// win.resize(400,230);
// win.show();
// return app.exec();
//}
<|endoftext|> |
<commit_before>// @(#)root/core/meta:$Id$
// Author: Paul Russo 30/07/2012
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TClingDataMemberInfo //
// //
// Emulation of the CINT DataMemberInfo class. //
// //
// The CINT C++ interpreter provides an interface to metadata about //
// the data members of a class through the DataMemberInfo class. This //
// class provides the same functionality, using an interface as close //
// as possible to DataMemberInfo but the data member metadata comes //
// from the Clang C++ compiler, not CINT. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TClingDataMemberInfo.h"
#include "Property.h"
#include "TClingProperty.h"
#include "TClingTypeInfo.h"
#include "TMetaUtils.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/PrettyPrinter.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/Type.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
TClingDataMemberInfo::TClingDataMemberInfo(cling::Interpreter *interp,
TClingClassInfo *ci)
: fInterp(interp), fClassInfo(0), fFirstTime(true), fTitle("")
{
if (!ci || !ci->IsValid()) {
fClassInfo = new TClingClassInfo(fInterp);
fIter = fInterp->getCI()->getASTContext().getTranslationUnitDecl()->
decls_begin();
// Move to first global variable.
InternalNext();
return;
}
fClassInfo = new TClingClassInfo(*ci);
if (ci->IsValid()) {
fIter = llvm::cast<clang::DeclContext>(ci->GetDecl())->decls_begin();
// Move to first data member.
InternalNext();
}
}
int TClingDataMemberInfo::ArrayDim() const
{
if (!IsValid()) {
return -1;
}
// Sanity check the current data member.
clang::Decl::Kind DK = fIter->getKind();
if (
(DK != clang::Decl::Field) &&
(DK != clang::Decl::Var) &&
(DK != clang::Decl::EnumConstant)
) {
// Error, was not a data member, variable, or enumerator.
return -1;
}
if (DK == clang::Decl::EnumConstant) {
// We know that an enumerator value does not have array type.
return 0;
}
// To get this information we must count the number
// of arry type nodes in the canonical type chain.
const clang::ValueDecl *VD = llvm::dyn_cast<clang::ValueDecl>(*fIter);
clang::QualType QT = VD->getType().getCanonicalType();
int cnt = 0;
while (1) {
if (QT->isArrayType()) {
++cnt;
QT = llvm::cast<clang::ArrayType>(QT)->getElementType();
continue;
}
else if (QT->isReferenceType()) {
QT = llvm::cast<clang::ReferenceType>(QT)->getPointeeType();
continue;
}
else if (QT->isPointerType()) {
QT = llvm::cast<clang::PointerType>(QT)->getPointeeType();
continue;
}
else if (QT->isMemberPointerType()) {
QT = llvm::cast<clang::MemberPointerType>(QT)->getPointeeType();
continue;
}
break;
}
return cnt;
}
int TClingDataMemberInfo::MaxIndex(int dim) const
{
if (!IsValid()) {
return -1;
}
// Sanity check the current data member.
clang::Decl::Kind DK = fIter->getKind();
if (
(DK != clang::Decl::Field) &&
(DK != clang::Decl::Var) &&
(DK != clang::Decl::EnumConstant)
) {
// Error, was not a data member, variable, or enumerator.
return -1;
}
if (DK == clang::Decl::EnumConstant) {
// We know that an enumerator value does not have array type.
return 0;
}
// To get this information we must count the number
// of arry type nodes in the canonical type chain.
const clang::ValueDecl *VD = llvm::dyn_cast<clang::ValueDecl>(*fIter);
clang::QualType QT = VD->getType().getCanonicalType();
int paran = ArrayDim();
if ((dim < 0) || (dim >= paran)) {
// Passed dimension is out of bounds.
return -1;
}
int cnt = dim;
int max = 0;
while (1) {
if (QT->isArrayType()) {
if (cnt == 0) {
if (const clang::ConstantArrayType *CAT =
llvm::dyn_cast<clang::ConstantArrayType>(QT)
) {
max = static_cast<int>(CAT->getSize().getZExtValue());
}
else if (llvm::dyn_cast<clang::IncompleteArrayType>(QT)) {
max = INT_MAX;
}
else {
max = -1;
}
break;
}
--cnt;
QT = llvm::cast<clang::ArrayType>(QT)->getElementType();
continue;
}
else if (QT->isReferenceType()) {
QT = llvm::cast<clang::ReferenceType>(QT)->getPointeeType();
continue;
}
else if (QT->isPointerType()) {
QT = llvm::cast<clang::PointerType>(QT)->getPointeeType();
continue;
}
else if (QT->isMemberPointerType()) {
QT = llvm::cast<clang::MemberPointerType>(QT)->getPointeeType();
continue;
}
break;
}
return max;
}
int TClingDataMemberInfo::InternalNext()
{
// Move to next acceptable data member.
while (*fIter) {
// Move to next decl in context.
if (fFirstTime) {
fFirstTime = false;
}
else {
++fIter;
}
// Handle reaching end of current decl context.
if (!*fIter && fIterStack.size()) {
// End of current decl context, and we have more to go.
fIter = fIterStack.back();
fIterStack.pop_back();
++fIter;
continue;
}
// Handle final termination.
if (!*fIter) {
return 0;
}
// Valid decl, recurse into it, accept it, or reject it.
clang::Decl::Kind DK = fIter->getKind();
if (DK == clang::Decl::Enum) {
// We have an enum, recurse into these.
// Note: For C++11 we will have to check for a transparent context.
fIterStack.push_back(fIter);
fIter = llvm::dyn_cast<clang::DeclContext>(*fIter)->decls_begin();
continue;
}
if ((DK == clang::Decl::Field) || (DK == clang::Decl::EnumConstant) ||
(DK == clang::Decl::Var)) {
// Stop on class data members, enumerator values,
// and namespace variable members.
return 1;
}
}
return 0;
}
long TClingDataMemberInfo::Offset() const
{
if (!IsValid()) {
return -1L;
}
// Sanity check the current data member.
clang::Decl::Kind DK = fIter->getKind();
if (
(DK != clang::Decl::Field) &&
(DK != clang::Decl::Var) &&
(DK != clang::Decl::EnumConstant)
) {
// Error, was not a data member, variable, or enumerator.
return -1L;
}
if (DK == clang::Decl::Field) {
// The current member is a non-static data member.
const clang::FieldDecl *FD = llvm::dyn_cast<clang::FieldDecl>(*fIter);
clang::ASTContext &Context = FD->getASTContext();
const clang::RecordDecl *RD = FD->getParent();
const clang::ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
uint64_t bits = Layout.getFieldOffset(FD->getFieldIndex());
int64_t offset = Context.toCharUnitsFromBits(bits).getQuantity();
return static_cast<long>(offset);
}
// The current member is static data member, enumerator constant,
// or a global variable.
// FIXME: We are supposed to return the address of the storage
// for the member here, only the interpreter knows that.
return -1L;
}
long TClingDataMemberInfo::Property() const
{
if (!IsValid()) {
return 0L;
}
long property = 0L;
switch (fIter->getAccess()) {
case clang::AS_public:
property |= G__BIT_ISPUBLIC;
break;
case clang::AS_protected:
property |= G__BIT_ISPROTECTED;
break;
case clang::AS_private:
property |= G__BIT_ISPRIVATE;
break;
case clang::AS_none:
// IMPOSSIBLE
break;
default:
// IMPOSSIBLE
break;
}
if (const clang::VarDecl *vard = llvm::dyn_cast<clang::VarDecl>(*fIter)) {
if (vard->getStorageClass() == clang::SC_Static) {
property |= G__BIT_ISSTATIC;
}
}
const clang::ValueDecl *vd = llvm::dyn_cast<clang::ValueDecl>(*fIter);
clang::QualType qt = vd->getType();
if (llvm::isa<clang::TypedefType>(qt)) {
property |= G__BIT_ISTYPEDEF;
}
qt = qt.getCanonicalType();
if (qt.isConstQualified()) {
property |= G__BIT_ISCONSTANT;
}
while (1) {
if (qt->isArrayType()) {
property |= G__BIT_ISARRAY;
qt = llvm::cast<clang::ArrayType>(qt)->getElementType();
continue;
}
else if (qt->isReferenceType()) {
property |= G__BIT_ISREFERENCE;
qt = llvm::cast<clang::ReferenceType>(qt)->getPointeeType();
continue;
}
else if (qt->isPointerType()) {
property |= G__BIT_ISPOINTER;
if (qt.isConstQualified()) {
property |= G__BIT_ISPCONSTANT;
}
qt = llvm::cast<clang::PointerType>(qt)->getPointeeType();
continue;
}
else if (qt->isMemberPointerType()) {
qt = llvm::cast<clang::MemberPointerType>(qt)->getPointeeType();
continue;
}
break;
}
if (qt->isBuiltinType()) {
property |= G__BIT_ISFUNDAMENTAL;
}
if (qt.isConstQualified()) {
property |= G__BIT_ISCONSTANT;
}
const clang::DeclContext *dc = fIter->getDeclContext();
if (const clang::TagDecl *td = llvm::dyn_cast<clang::TagDecl>(dc)) {
if (td->isClass()) {
property |= G__BIT_ISCLASS;
}
else if (td->isStruct()) {
property |= G__BIT_ISSTRUCT;
}
else if (td->isUnion()) {
property |= G__BIT_ISUNION;
}
else if (td->isEnum()) {
property |= G__BIT_ISENUM;
}
}
if (dc->isNamespace() && !dc->isTranslationUnit()) {
property |= G__BIT_ISNAMESPACE;
}
return property;
}
long TClingDataMemberInfo::TypeProperty() const
{
if (!IsValid()) {
return 0L;
}
const clang::ValueDecl *vd = llvm::dyn_cast<clang::ValueDecl>(*fIter);
clang::QualType qt = vd->getType();
return TClingTypeInfo(fInterp, qt).Property();
}
int TClingDataMemberInfo::TypeSize() const
{
if (!IsValid()) {
return -1;
}
// Sanity check the current data member.
clang::Decl::Kind dk = fIter->getKind();
if ((dk != clang::Decl::Field) && (dk != clang::Decl::Var) &&
(dk != clang::Decl::EnumConstant)) {
// Error, was not a data member, variable, or enumerator.
return -1;
}
const clang::ValueDecl *vd = llvm::dyn_cast<clang::ValueDecl>(*fIter);
clang::QualType qt = vd->getType();
if (qt->isIncompleteType()) {
// We cannot determine the size of forward-declared types.
return -1;
}
clang::ASTContext &context = fIter->getASTContext();
// Truncate cast to fit to cint interface.
return static_cast<int>(context.getTypeSizeInChars(qt).getQuantity());
}
const char *TClingDataMemberInfo::TypeName() const
{
if (!IsValid()) {
return 0;
}
// Note: This must be static because we return a pointer inside it!
static std::string buf;
buf.clear();
clang::PrintingPolicy policy(fIter->getASTContext().getPrintingPolicy());
policy.AnonymousTagLocations = false;
if (const clang::ValueDecl *vd = llvm::dyn_cast<clang::ValueDecl>(*fIter)) {
buf = vd->getType().getAsString(policy);
return buf.c_str();
}
return 0;
}
const char *TClingDataMemberInfo::TypeTrueName() const
{
if (!IsValid()) {
return 0;
}
// Note: This must be static because we return a pointer inside it!
static std::string buf;
buf.clear();
clang::PrintingPolicy policy(fIter->getASTContext().getPrintingPolicy());
policy.AnonymousTagLocations = false;
if (const clang::ValueDecl *vd = llvm::dyn_cast<clang::ValueDecl>(*fIter)) {
buf = vd->getType().getCanonicalType().getAsString(policy);
return buf.c_str();
}
return 0;
}
const char *TClingDataMemberInfo::Name() const
{
if (!IsValid()) {
return 0;
}
// Note: This must be static because we return a pointer inside it!
static std::string buf;
buf.clear();
if (const clang::NamedDecl *nd = llvm::dyn_cast<clang::NamedDecl>(*fIter)) {
clang::PrintingPolicy policy(fIter->getASTContext().getPrintingPolicy());
nd->getNameForDiagnostic(buf, policy, /*Qualified=*/false);
return buf.c_str();
}
return 0;
}
const char *TClingDataMemberInfo::Title()
{
if (!IsValid()) {
return 0;
}
//NOTE: We can't use it as a cache due to the "thoughtful" self iterator
//if (fTitle.size())
// return fTitle.c_str();
// Try to get the comment either from the annotation or the header file if present
if (AnnotateAttr *A = GetDecl()->getAttr<AnnotateAttr>())
fTitle = A->getAnnotation().str();
else
// Try to get the comment from the header file if present
fTitle = ROOT::TMetaUtils::GetComment(*GetDecl()).str();
return fTitle.c_str();
}
const char *TClingDataMemberInfo::ValidArrayIndex() const
{
if (!IsValid()) {
return 0;
}
// FIXME: Implement when rootcint makes this available!
return 0;
}
<commit_msg>Fix internal iterator starts at second member problem. During construction we must move to the first data member in the decl context of the class, and then we must set the first time flag so that we stay there on the first call to Next(). Silly cint iterator semantics.<commit_after>// @(#)root/core/meta:$Id$
// Author: Paul Russo 30/07/2012
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TClingDataMemberInfo //
// //
// Emulation of the CINT DataMemberInfo class. //
// //
// The CINT C++ interpreter provides an interface to metadata about //
// the data members of a class through the DataMemberInfo class. This //
// class provides the same functionality, using an interface as close //
// as possible to DataMemberInfo but the data member metadata comes //
// from the Clang C++ compiler, not CINT. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TClingDataMemberInfo.h"
#include "Property.h"
#include "TClingProperty.h"
#include "TClingTypeInfo.h"
#include "TMetaUtils.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/PrettyPrinter.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/Type.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
TClingDataMemberInfo::TClingDataMemberInfo(cling::Interpreter *interp,
TClingClassInfo *ci)
: fInterp(interp), fClassInfo(0), fFirstTime(true), fTitle("")
{
if (!ci || !ci->IsValid()) {
fClassInfo = new TClingClassInfo(fInterp);
fIter = fInterp->getCI()->getASTContext().getTranslationUnitDecl()->
decls_begin();
// Move to first global variable.
InternalNext();
fFirstTime = true;
return;
}
fClassInfo = new TClingClassInfo(*ci);
if (ci->IsValid()) {
fIter = llvm::cast<clang::DeclContext>(ci->GetDecl())->decls_begin();
// Move to first data member.
InternalNext();
fFirstTime = true;
}
}
int TClingDataMemberInfo::ArrayDim() const
{
if (!IsValid()) {
return -1;
}
// Sanity check the current data member.
clang::Decl::Kind DK = fIter->getKind();
if (
(DK != clang::Decl::Field) &&
(DK != clang::Decl::Var) &&
(DK != clang::Decl::EnumConstant)
) {
// Error, was not a data member, variable, or enumerator.
return -1;
}
if (DK == clang::Decl::EnumConstant) {
// We know that an enumerator value does not have array type.
return 0;
}
// To get this information we must count the number
// of arry type nodes in the canonical type chain.
const clang::ValueDecl *VD = llvm::dyn_cast<clang::ValueDecl>(*fIter);
clang::QualType QT = VD->getType().getCanonicalType();
int cnt = 0;
while (1) {
if (QT->isArrayType()) {
++cnt;
QT = llvm::cast<clang::ArrayType>(QT)->getElementType();
continue;
}
else if (QT->isReferenceType()) {
QT = llvm::cast<clang::ReferenceType>(QT)->getPointeeType();
continue;
}
else if (QT->isPointerType()) {
QT = llvm::cast<clang::PointerType>(QT)->getPointeeType();
continue;
}
else if (QT->isMemberPointerType()) {
QT = llvm::cast<clang::MemberPointerType>(QT)->getPointeeType();
continue;
}
break;
}
return cnt;
}
int TClingDataMemberInfo::MaxIndex(int dim) const
{
if (!IsValid()) {
return -1;
}
// Sanity check the current data member.
clang::Decl::Kind DK = fIter->getKind();
if (
(DK != clang::Decl::Field) &&
(DK != clang::Decl::Var) &&
(DK != clang::Decl::EnumConstant)
) {
// Error, was not a data member, variable, or enumerator.
return -1;
}
if (DK == clang::Decl::EnumConstant) {
// We know that an enumerator value does not have array type.
return 0;
}
// To get this information we must count the number
// of arry type nodes in the canonical type chain.
const clang::ValueDecl *VD = llvm::dyn_cast<clang::ValueDecl>(*fIter);
clang::QualType QT = VD->getType().getCanonicalType();
int paran = ArrayDim();
if ((dim < 0) || (dim >= paran)) {
// Passed dimension is out of bounds.
return -1;
}
int cnt = dim;
int max = 0;
while (1) {
if (QT->isArrayType()) {
if (cnt == 0) {
if (const clang::ConstantArrayType *CAT =
llvm::dyn_cast<clang::ConstantArrayType>(QT)
) {
max = static_cast<int>(CAT->getSize().getZExtValue());
}
else if (llvm::dyn_cast<clang::IncompleteArrayType>(QT)) {
max = INT_MAX;
}
else {
max = -1;
}
break;
}
--cnt;
QT = llvm::cast<clang::ArrayType>(QT)->getElementType();
continue;
}
else if (QT->isReferenceType()) {
QT = llvm::cast<clang::ReferenceType>(QT)->getPointeeType();
continue;
}
else if (QT->isPointerType()) {
QT = llvm::cast<clang::PointerType>(QT)->getPointeeType();
continue;
}
else if (QT->isMemberPointerType()) {
QT = llvm::cast<clang::MemberPointerType>(QT)->getPointeeType();
continue;
}
break;
}
return max;
}
int TClingDataMemberInfo::InternalNext()
{
// Move to next acceptable data member.
while (*fIter) {
// Move to next decl in context.
if (fFirstTime) {
fFirstTime = false;
}
else {
++fIter;
}
// Handle reaching end of current decl context.
if (!*fIter && fIterStack.size()) {
// End of current decl context, and we have more to go.
fIter = fIterStack.back();
fIterStack.pop_back();
++fIter;
continue;
}
// Handle final termination.
if (!*fIter) {
return 0;
}
// Valid decl, recurse into it, accept it, or reject it.
clang::Decl::Kind DK = fIter->getKind();
if (DK == clang::Decl::Enum) {
// We have an enum, recurse into these.
// Note: For C++11 we will have to check for a transparent context.
fIterStack.push_back(fIter);
fIter = llvm::dyn_cast<clang::DeclContext>(*fIter)->decls_begin();
continue;
}
if ((DK == clang::Decl::Field) || (DK == clang::Decl::EnumConstant) ||
(DK == clang::Decl::Var)) {
// Stop on class data members, enumerator values,
// and namespace variable members.
return 1;
}
}
return 0;
}
long TClingDataMemberInfo::Offset() const
{
if (!IsValid()) {
return -1L;
}
// Sanity check the current data member.
clang::Decl::Kind DK = fIter->getKind();
if (
(DK != clang::Decl::Field) &&
(DK != clang::Decl::Var) &&
(DK != clang::Decl::EnumConstant)
) {
// Error, was not a data member, variable, or enumerator.
return -1L;
}
if (DK == clang::Decl::Field) {
// The current member is a non-static data member.
const clang::FieldDecl *FD = llvm::dyn_cast<clang::FieldDecl>(*fIter);
clang::ASTContext &Context = FD->getASTContext();
const clang::RecordDecl *RD = FD->getParent();
const clang::ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
uint64_t bits = Layout.getFieldOffset(FD->getFieldIndex());
int64_t offset = Context.toCharUnitsFromBits(bits).getQuantity();
return static_cast<long>(offset);
}
// The current member is static data member, enumerator constant,
// or a global variable.
// FIXME: We are supposed to return the address of the storage
// for the member here, only the interpreter knows that.
return -1L;
}
long TClingDataMemberInfo::Property() const
{
if (!IsValid()) {
return 0L;
}
long property = 0L;
switch (fIter->getAccess()) {
case clang::AS_public:
property |= G__BIT_ISPUBLIC;
break;
case clang::AS_protected:
property |= G__BIT_ISPROTECTED;
break;
case clang::AS_private:
property |= G__BIT_ISPRIVATE;
break;
case clang::AS_none:
// IMPOSSIBLE
break;
default:
// IMPOSSIBLE
break;
}
if (const clang::VarDecl *vard = llvm::dyn_cast<clang::VarDecl>(*fIter)) {
if (vard->getStorageClass() == clang::SC_Static) {
property |= G__BIT_ISSTATIC;
}
}
const clang::ValueDecl *vd = llvm::dyn_cast<clang::ValueDecl>(*fIter);
clang::QualType qt = vd->getType();
if (llvm::isa<clang::TypedefType>(qt)) {
property |= G__BIT_ISTYPEDEF;
}
qt = qt.getCanonicalType();
if (qt.isConstQualified()) {
property |= G__BIT_ISCONSTANT;
}
while (1) {
if (qt->isArrayType()) {
property |= G__BIT_ISARRAY;
qt = llvm::cast<clang::ArrayType>(qt)->getElementType();
continue;
}
else if (qt->isReferenceType()) {
property |= G__BIT_ISREFERENCE;
qt = llvm::cast<clang::ReferenceType>(qt)->getPointeeType();
continue;
}
else if (qt->isPointerType()) {
property |= G__BIT_ISPOINTER;
if (qt.isConstQualified()) {
property |= G__BIT_ISPCONSTANT;
}
qt = llvm::cast<clang::PointerType>(qt)->getPointeeType();
continue;
}
else if (qt->isMemberPointerType()) {
qt = llvm::cast<clang::MemberPointerType>(qt)->getPointeeType();
continue;
}
break;
}
if (qt->isBuiltinType()) {
property |= G__BIT_ISFUNDAMENTAL;
}
if (qt.isConstQualified()) {
property |= G__BIT_ISCONSTANT;
}
const clang::DeclContext *dc = fIter->getDeclContext();
if (const clang::TagDecl *td = llvm::dyn_cast<clang::TagDecl>(dc)) {
if (td->isClass()) {
property |= G__BIT_ISCLASS;
}
else if (td->isStruct()) {
property |= G__BIT_ISSTRUCT;
}
else if (td->isUnion()) {
property |= G__BIT_ISUNION;
}
else if (td->isEnum()) {
property |= G__BIT_ISENUM;
}
}
if (dc->isNamespace() && !dc->isTranslationUnit()) {
property |= G__BIT_ISNAMESPACE;
}
return property;
}
long TClingDataMemberInfo::TypeProperty() const
{
if (!IsValid()) {
return 0L;
}
const clang::ValueDecl *vd = llvm::dyn_cast<clang::ValueDecl>(*fIter);
clang::QualType qt = vd->getType();
return TClingTypeInfo(fInterp, qt).Property();
}
int TClingDataMemberInfo::TypeSize() const
{
if (!IsValid()) {
return -1;
}
// Sanity check the current data member.
clang::Decl::Kind dk = fIter->getKind();
if ((dk != clang::Decl::Field) && (dk != clang::Decl::Var) &&
(dk != clang::Decl::EnumConstant)) {
// Error, was not a data member, variable, or enumerator.
return -1;
}
const clang::ValueDecl *vd = llvm::dyn_cast<clang::ValueDecl>(*fIter);
clang::QualType qt = vd->getType();
if (qt->isIncompleteType()) {
// We cannot determine the size of forward-declared types.
return -1;
}
clang::ASTContext &context = fIter->getASTContext();
// Truncate cast to fit to cint interface.
return static_cast<int>(context.getTypeSizeInChars(qt).getQuantity());
}
const char *TClingDataMemberInfo::TypeName() const
{
if (!IsValid()) {
return 0;
}
// Note: This must be static because we return a pointer inside it!
static std::string buf;
buf.clear();
clang::PrintingPolicy policy(fIter->getASTContext().getPrintingPolicy());
policy.AnonymousTagLocations = false;
if (const clang::ValueDecl *vd = llvm::dyn_cast<clang::ValueDecl>(*fIter)) {
buf = vd->getType().getAsString(policy);
return buf.c_str();
}
return 0;
}
const char *TClingDataMemberInfo::TypeTrueName() const
{
if (!IsValid()) {
return 0;
}
// Note: This must be static because we return a pointer inside it!
static std::string buf;
buf.clear();
clang::PrintingPolicy policy(fIter->getASTContext().getPrintingPolicy());
policy.AnonymousTagLocations = false;
if (const clang::ValueDecl *vd = llvm::dyn_cast<clang::ValueDecl>(*fIter)) {
buf = vd->getType().getCanonicalType().getAsString(policy);
return buf.c_str();
}
return 0;
}
const char *TClingDataMemberInfo::Name() const
{
if (!IsValid()) {
return 0;
}
// Note: This must be static because we return a pointer inside it!
static std::string buf;
buf.clear();
if (const clang::NamedDecl *nd = llvm::dyn_cast<clang::NamedDecl>(*fIter)) {
clang::PrintingPolicy policy(fIter->getASTContext().getPrintingPolicy());
nd->getNameForDiagnostic(buf, policy, /*Qualified=*/false);
return buf.c_str();
}
return 0;
}
const char *TClingDataMemberInfo::Title()
{
if (!IsValid()) {
return 0;
}
//NOTE: We can't use it as a cache due to the "thoughtful" self iterator
//if (fTitle.size())
// return fTitle.c_str();
// Try to get the comment either from the annotation or the header file if present
if (AnnotateAttr *A = GetDecl()->getAttr<AnnotateAttr>())
fTitle = A->getAnnotation().str();
else
// Try to get the comment from the header file if present
fTitle = ROOT::TMetaUtils::GetComment(*GetDecl()).str();
return fTitle.c_str();
}
const char *TClingDataMemberInfo::ValidArrayIndex() const
{
if (!IsValid()) {
return 0;
}
// FIXME: Implement when rootcint makes this available!
return 0;
}
<|endoftext|> |
<commit_before>/**
* Clever programming language
* Copyright (c) 2011-2012 Clever Team
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 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 "types/type.h"
#include "types/array.h"
#include "compiler/compiler.h"
namespace clever {
CLEVER_TYPE_METHOD(Array::push) {
ValueVector* vec = CLEVER_THIS()->getVector();
Value* val = new Value();
val->copy(CLEVER_ARG(0));
vec->push_back(val);
}
CLEVER_TYPE_METHOD(Array::pop) {
ValueVector* vec = CLEVER_THIS()->getVector();
if (vec->size() > 0) {
retval->copy(vec->back());
vec->pop_back();
}
else {
const Type* value_type = ((const TemplatedType*)CLEVER_THIS()
->getTypePtr())->getTypeArg(0);
Compiler::warningf("Popping from a empty Array<%S>! Returning"
" default value of type %S.",
value_type->getName(), value_type->getName());
retval->setTypePtr(value_type);
retval->initialize();
}
}
CLEVER_TYPE_METHOD(Array::size) {
ValueVector* vec = CLEVER_THIS()->getVector();
CLEVER_RETURN_INT(vec->size());
}
CLEVER_TYPE_METHOD(Array::isEmpty) {
ValueVector* vec = CLEVER_THIS()->getVector();
CLEVER_RETURN_BOOL(vec->empty());
}
CLEVER_TYPE_METHOD(Array::clear) {
ValueVector* vec = CLEVER_THIS()->getVector();
size_t sz = vec->size();
for (size_t i = 0; i < sz; ++i) {
vec->at(i)->delRef();
}
vec->clear();
}
CLEVER_TYPE_METHOD(Array::at) {
ValueVector* vec = CLEVER_THIS()->getVector();
int64_t idx = CLEVER_ARG(0)->getInteger();
if (size_t(idx) < vec->size() && idx >= 0) {
retval->copy(vec->at(idx));
}
else {
const Type* value_type = ((const TemplatedType*)CLEVER_THIS()
->getTypePtr())->getTypeArg(0);
clever_assert(value_type != NULL, "Cannot be NULL");
if (idx >= 0) {
Compiler::warningf("Indexing position %l an Array<%S>"
" with %N elements. Returning default value of type %S.",
idx, value_type->getName(), vec->size(),
value_type->getName());
}
else {
Compiler::warningf("Indexing negative position %l an Array<%S>!"
" Returning default value of type %S.",
idx, value_type->getName(), value_type->getName());
}
retval->setTypePtr(value_type);
retval->initialize();
}
}
CLEVER_TYPE_METHOD(Array::set) {
ValueVector* vec = CLEVER_THIS()->getVector();
int64_t idx = CLEVER_ARG(0)->getInteger();
if (size_t(idx) < vec->size() && idx >= 0) {
Value* val = new Value();
val->copy(CLEVER_ARG(1));
vec->at(idx)->delRef();
vec->at(idx) = val;
}
else {
const Type* value_type = ((const TemplatedType*)CLEVER_THIS()
->getTypePtr())->getTypeArg(0);
if (idx >= 0) {
Compiler::warningf("Setting position %l an Array<%S> with %N elements.",
idx, value_type->getName(), vec->size());
}
else {
Compiler::warningf("Setting negative position %l an Array<%S>!",
idx, value_type->getName());
}
}
}
CLEVER_TYPE_METHOD(Array::resize) {
ValueVector* vec = CLEVER_THIS()->getVector();
int nsz = CLEVER_ARG(0)->getInteger();
size_t sz = vec->size();
for (size_t i = 0; i < sz; ++i) {
vec->at(i)->delRef();
}
vec->resize(nsz);
for (int i = 0; i < nsz; ++i) {
vec->at(i) = new Value();
vec->at(i)->copy(CLEVER_ARG(1));
}
}
CLEVER_TYPE_METHOD(Array::toString) {
ValueVector* vec = CLEVER_THIS()->getVector();
std::string ret = "[", sep = ", ";
for (unsigned int i = 0, j = vec->size(); i < j; ++i) {
ret += vec->at(i)->toString();
if (i+1 < j) {
ret += sep;
}
}
ret += "]";
CLEVER_RETURN_STR(CSTRING(ret));
}
void Array::init() {
/* If we are in our "virtual" Array type */
if (CLEVER_TPL_ARG(0) == NULL) {
return;
}
addMethod(new Method("toString", (MethodPtr)&Array::toString, CLEVER_STR));
addMethod(
(new Method("push", (MethodPtr)&Array::push, CLEVER_VOID))
->addArg("arg1", CLEVER_TPL_ARG(0))
);
addMethod(
new Method("pop", (MethodPtr)&Array::pop, CLEVER_TPL_ARG(0))
);
addMethod(new Method("size", (MethodPtr)&Array::size, CLEVER_INT));
addMethod(new Method("isEmpty", (MethodPtr)&Array::isEmpty, CLEVER_BOOL));
addMethod(new Method("clear", (MethodPtr)&Array::clear, CLEVER_VOID));
addMethod((new Method("at", (MethodPtr)&Array::at, CLEVER_TPL_ARG(0)))
->addArg("index", CLEVER_INT)
);
addMethod((new Method("set", (MethodPtr)&Array::set, CLEVER_VOID))
->addArg("index", CLEVER_INT)
->addArg("element", CLEVER_TPL_ARG(0))
);
addMethod((new Method("resize", (MethodPtr)&Array::resize, CLEVER_VOID))
->addArg("new_size", CLEVER_INT)
->addArg("value", CLEVER_TPL_ARG(0))
);
}
DataValue* Array::allocateValue() const {
return NULL;
}
} // clever
<commit_msg>- Fixed memory leak in array_004.test<commit_after>/**
* Clever programming language
* Copyright (c) 2011-2012 Clever Team
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 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 "types/type.h"
#include "types/array.h"
#include "compiler/compiler.h"
namespace clever {
CLEVER_TYPE_METHOD(Array::push) {
ValueVector* vec = CLEVER_THIS()->getVector();
Value* val = new Value();
val->copy(CLEVER_ARG(0));
vec->push_back(val);
}
CLEVER_TYPE_METHOD(Array::pop) {
ValueVector* vec = CLEVER_THIS()->getVector();
if (vec->size() > 0) {
retval->copy(vec->back());
vec->back()->delRef();
vec->pop_back();
}
else {
const Type* value_type = ((const TemplatedType*)CLEVER_THIS()
->getTypePtr())->getTypeArg(0);
Compiler::warningf("Popping from a empty Array<%S>! Returning"
" default value of type %S.",
value_type->getName(), value_type->getName());
retval->setTypePtr(value_type);
retval->initialize();
}
}
CLEVER_TYPE_METHOD(Array::size) {
ValueVector* vec = CLEVER_THIS()->getVector();
CLEVER_RETURN_INT(vec->size());
}
CLEVER_TYPE_METHOD(Array::isEmpty) {
ValueVector* vec = CLEVER_THIS()->getVector();
CLEVER_RETURN_BOOL(vec->empty());
}
CLEVER_TYPE_METHOD(Array::clear) {
ValueVector* vec = CLEVER_THIS()->getVector();
size_t sz = vec->size();
for (size_t i = 0; i < sz; ++i) {
vec->at(i)->delRef();
}
vec->clear();
}
CLEVER_TYPE_METHOD(Array::at) {
ValueVector* vec = CLEVER_THIS()->getVector();
int64_t idx = CLEVER_ARG(0)->getInteger();
if (size_t(idx) < vec->size() && idx >= 0) {
retval->copy(vec->at(idx));
}
else {
const Type* value_type = ((const TemplatedType*)CLEVER_THIS()
->getTypePtr())->getTypeArg(0);
clever_assert(value_type != NULL, "Cannot be NULL");
if (idx >= 0) {
Compiler::warningf("Indexing position %l an Array<%S>"
" with %N elements. Returning default value of type %S.",
idx, value_type->getName(), vec->size(),
value_type->getName());
}
else {
Compiler::warningf("Indexing negative position %l an Array<%S>!"
" Returning default value of type %S.",
idx, value_type->getName(), value_type->getName());
}
retval->setTypePtr(value_type);
retval->initialize();
}
}
CLEVER_TYPE_METHOD(Array::set) {
ValueVector* vec = CLEVER_THIS()->getVector();
int64_t idx = CLEVER_ARG(0)->getInteger();
if (size_t(idx) < vec->size() && idx >= 0) {
Value* val = new Value();
val->copy(CLEVER_ARG(1));
vec->at(idx)->delRef();
vec->at(idx) = val;
}
else {
const Type* value_type = ((const TemplatedType*)CLEVER_THIS()
->getTypePtr())->getTypeArg(0);
if (idx >= 0) {
Compiler::warningf("Setting position %l an Array<%S> with %N elements.",
idx, value_type->getName(), vec->size());
}
else {
Compiler::warningf("Setting negative position %l an Array<%S>!",
idx, value_type->getName());
}
}
}
CLEVER_TYPE_METHOD(Array::resize) {
ValueVector* vec = CLEVER_THIS()->getVector();
int nsz = CLEVER_ARG(0)->getInteger();
size_t sz = vec->size();
for (size_t i = 0; i < sz; ++i) {
vec->at(i)->delRef();
}
vec->resize(nsz);
for (int i = 0; i < nsz; ++i) {
vec->at(i) = new Value();
vec->at(i)->copy(CLEVER_ARG(1));
}
}
CLEVER_TYPE_METHOD(Array::toString) {
ValueVector* vec = CLEVER_THIS()->getVector();
std::string ret = "[", sep = ", ";
for (unsigned int i = 0, j = vec->size(); i < j; ++i) {
ret += vec->at(i)->toString();
if (i+1 < j) {
ret += sep;
}
}
ret += "]";
CLEVER_RETURN_STR(CSTRING(ret));
}
void Array::init() {
/* If we are in our "virtual" Array type */
if (CLEVER_TPL_ARG(0) == NULL) {
return;
}
addMethod(new Method("toString", (MethodPtr)&Array::toString, CLEVER_STR));
addMethod(
(new Method("push", (MethodPtr)&Array::push, CLEVER_VOID))
->addArg("arg1", CLEVER_TPL_ARG(0))
);
addMethod(
new Method("pop", (MethodPtr)&Array::pop, CLEVER_TPL_ARG(0))
);
addMethod(new Method("size", (MethodPtr)&Array::size, CLEVER_INT));
addMethod(new Method("isEmpty", (MethodPtr)&Array::isEmpty, CLEVER_BOOL));
addMethod(new Method("clear", (MethodPtr)&Array::clear, CLEVER_VOID));
addMethod((new Method("at", (MethodPtr)&Array::at, CLEVER_TPL_ARG(0)))
->addArg("index", CLEVER_INT)
);
addMethod((new Method("set", (MethodPtr)&Array::set, CLEVER_VOID))
->addArg("index", CLEVER_INT)
->addArg("element", CLEVER_TPL_ARG(0))
);
addMethod((new Method("resize", (MethodPtr)&Array::resize, CLEVER_VOID))
->addArg("new_size", CLEVER_INT)
->addArg("value", CLEVER_TPL_ARG(0))
);
}
DataValue* Array::allocateValue() const {
return NULL;
}
} // clever
<|endoftext|> |
<commit_before>#include <cassert>
#include <sstream>
#include <aikido/statespace/RealVectorStateSpace.hpp>
#include <aikido/statespace/RealVectorJointStateSpace.hpp>
#include <aikido/statespace/SO2StateSpace.hpp>
#include <aikido/statespace/SO2JointStateSpace.hpp>
#include <aikido/statespace/SO3StateSpace.hpp>
#include <aikido/statespace/SE2StateSpace.hpp>
#include <aikido/statespace/SE3StateSpace.hpp>
#include <aikido/statespace/SE3JointStateSpace.hpp>
#include <aikido/statespace/CompoundStateSpace.hpp>
#include <aikido/statespace/MetaSkeletonStateSpace.hpp>
#include <dart/common/StlHelpers.h>
#include <dart/common/console.h>
using dart::dynamics::MetaSkeleton;
using dart::dynamics::MetaSkeletonPtr;
using dart::dynamics::BallJoint;
using dart::dynamics::FreeJoint;
using dart::dynamics::EulerJoint;
using dart::dynamics::PlanarJoint;
using dart::dynamics::PrismaticJoint;
using dart::dynamics::RevoluteJoint;
using dart::dynamics::Joint;
using dart::dynamics::ScrewJoint;
using dart::dynamics::TranslationalJoint;
using dart::dynamics::SingleDofJoint;
using dart::dynamics::WeldJoint;
using dart::dynamics::INVALID_INDEX;
namespace aikido {
namespace statespace {
using JointStateSpacePtr = std::shared_ptr<JointStateSpace>;
namespace {
//=============================================================================
template <class Input, class Output>
std::vector<Output> convertVectorType(const std::vector<Input>& _input)
{
std::vector<Output> output;
output.reserve(_input.size());
for (const auto& x : _input)
output.emplace_back(x);
return std::move(output);
}
//=============================================================================
template <class T>
T* isJointOfType(dart::dynamics::Joint* _joint)
{
// It's safe to do a pointer comparison here, since getType is guaranteed to
// return the same reference to the corresponding getTypeStatic method.
if (&_joint->getType() == &T::getStaticType())
return static_cast<T*>(_joint);
else
return nullptr;
}
//=============================================================================
std::vector<std::shared_ptr<JointStateSpace>> createStateSpace(
MetaSkeleton& _metaskeleton)
{
std::vector<std::shared_ptr<JointStateSpace>> spaces;
spaces.reserve(_metaskeleton.getNumJoints());
for (size_t ijoint = 0; ijoint < _metaskeleton.getNumJoints(); ++ijoint)
{
const auto joint = _metaskeleton.getJoint(ijoint);
// Verify that the joint is not missing any DOFs. This could alter the
// topology of the space that we create.
for (size_t idof = 0; idof < joint->getNumDofs(); ++idof)
{
const auto dof = joint->getDof(idof);
if (_metaskeleton.getIndexOf(dof, false) == INVALID_INDEX)
{
std::stringstream msg;
msg << "MetaSkeleton is missing DegreeOfFreedom '" << dof->getName()
<< "' (index: " << idof << ") of Joint '" << joint->getName()
<< "'.";
throw std::runtime_error(msg.str());
}
}
spaces.emplace_back(createJointStateSpace(joint).release());
}
return std::move(spaces);
}
} // namespace
//=============================================================================
MetaSkeletonStateSpace::MetaSkeletonStateSpace(MetaSkeletonPtr _metaskeleton)
: CompoundStateSpace(
convertVectorType<JointStateSpacePtr, StateSpacePtr>(
createStateSpace(*_metaskeleton)))
, mMetaSkeleton(std::move(_metaskeleton))
{
}
//=============================================================================
MetaSkeletonPtr MetaSkeletonStateSpace::getMetaSkeleton() const
{
return mMetaSkeleton;
}
//=============================================================================
void MetaSkeletonStateSpace::getStateFromMetaSkeleton(State* _state) const
{
for (size_t ijoint = 0; ijoint < getNumStates(); ++ijoint)
{
auto jointSpace = getSubSpace<JointStateSpace>(ijoint);
jointSpace->getState(getSubState(_state, ijoint));
}
}
//=============================================================================
auto MetaSkeletonStateSpace::getScopedStateFromMetaSkeleton() const
-> ScopedState
{
auto scopedState = createState();
getStateFromMetaSkeleton(scopedState.getState());
return std::move(scopedState);
}
//=============================================================================
void MetaSkeletonStateSpace::setStateOnMetaSkeleton(const State* _state)
{
for (size_t ijoint = 0; ijoint < getNumStates(); ++ijoint)
{
auto jointSpace = getSubSpace<JointStateSpace>(ijoint);
jointSpace->setState(getSubState(_state, ijoint));
}
}
//=============================================================================
std::unique_ptr<JointStateSpace> createJointStateSpace(Joint* _joint)
{
auto space = detail::ForOneOf<
RevoluteJoint,
PrismaticJoint,
TranslationalJoint,
FreeJoint
>::create(_joint);
if (!space)
{
std::stringstream msg;
msg << "Joint '" << _joint->getName() << "' has unsupported type '"
<< _joint->getType() << "'.";
throw std::runtime_error(msg.str());
}
return std::move(space);
}
} // namespace statespace
} // namespace aikido
<commit_msg>Removed superfluous includes.<commit_after>#include <cassert>
#include <sstream>
#include <aikido/statespace/MetaSkeletonStateSpace.hpp>
#include <dart/common/StlHelpers.h>
#include <dart/common/console.h>
using dart::dynamics::MetaSkeleton;
using dart::dynamics::MetaSkeletonPtr;
using dart::dynamics::BallJoint;
using dart::dynamics::FreeJoint;
using dart::dynamics::EulerJoint;
using dart::dynamics::PlanarJoint;
using dart::dynamics::PrismaticJoint;
using dart::dynamics::RevoluteJoint;
using dart::dynamics::Joint;
using dart::dynamics::ScrewJoint;
using dart::dynamics::TranslationalJoint;
using dart::dynamics::SingleDofJoint;
using dart::dynamics::WeldJoint;
using dart::dynamics::INVALID_INDEX;
namespace aikido {
namespace statespace {
using JointStateSpacePtr = std::shared_ptr<JointStateSpace>;
namespace {
//=============================================================================
template <class Input, class Output>
std::vector<Output> convertVectorType(const std::vector<Input>& _input)
{
std::vector<Output> output;
output.reserve(_input.size());
for (const auto& x : _input)
output.emplace_back(x);
return std::move(output);
}
//=============================================================================
template <class T>
T* isJointOfType(dart::dynamics::Joint* _joint)
{
// It's safe to do a pointer comparison here, since getType is guaranteed to
// return the same reference to the corresponding getTypeStatic method.
if (&_joint->getType() == &T::getStaticType())
return static_cast<T*>(_joint);
else
return nullptr;
}
//=============================================================================
std::vector<std::shared_ptr<JointStateSpace>> createStateSpace(
MetaSkeleton& _metaskeleton)
{
std::vector<std::shared_ptr<JointStateSpace>> spaces;
spaces.reserve(_metaskeleton.getNumJoints());
for (size_t ijoint = 0; ijoint < _metaskeleton.getNumJoints(); ++ijoint)
{
const auto joint = _metaskeleton.getJoint(ijoint);
// Verify that the joint is not missing any DOFs. This could alter the
// topology of the space that we create.
for (size_t idof = 0; idof < joint->getNumDofs(); ++idof)
{
const auto dof = joint->getDof(idof);
if (_metaskeleton.getIndexOf(dof, false) == INVALID_INDEX)
{
std::stringstream msg;
msg << "MetaSkeleton is missing DegreeOfFreedom '" << dof->getName()
<< "' (index: " << idof << ") of Joint '" << joint->getName()
<< "'.";
throw std::runtime_error(msg.str());
}
}
spaces.emplace_back(createJointStateSpace(joint).release());
}
return std::move(spaces);
}
} // namespace
//=============================================================================
MetaSkeletonStateSpace::MetaSkeletonStateSpace(MetaSkeletonPtr _metaskeleton)
: CompoundStateSpace(
convertVectorType<JointStateSpacePtr, StateSpacePtr>(
createStateSpace(*_metaskeleton)))
, mMetaSkeleton(std::move(_metaskeleton))
{
}
//=============================================================================
MetaSkeletonPtr MetaSkeletonStateSpace::getMetaSkeleton() const
{
return mMetaSkeleton;
}
//=============================================================================
void MetaSkeletonStateSpace::getStateFromMetaSkeleton(State* _state) const
{
for (size_t ijoint = 0; ijoint < getNumStates(); ++ijoint)
{
auto jointSpace = getSubSpace<JointStateSpace>(ijoint);
jointSpace->getState(getSubState(_state, ijoint));
}
}
//=============================================================================
auto MetaSkeletonStateSpace::getScopedStateFromMetaSkeleton() const
-> ScopedState
{
auto scopedState = createState();
getStateFromMetaSkeleton(scopedState.getState());
return std::move(scopedState);
}
//=============================================================================
void MetaSkeletonStateSpace::setStateOnMetaSkeleton(const State* _state)
{
for (size_t ijoint = 0; ijoint < getNumStates(); ++ijoint)
{
auto jointSpace = getSubSpace<JointStateSpace>(ijoint);
jointSpace->setState(getSubState(_state, ijoint));
}
}
//=============================================================================
std::unique_ptr<JointStateSpace> createJointStateSpace(Joint* _joint)
{
auto space = detail::ForOneOf<
RevoluteJoint,
PrismaticJoint,
TranslationalJoint,
FreeJoint
>::create(_joint);
if (!space)
{
std::stringstream msg;
msg << "Joint '" << _joint->getName() << "' has unsupported type '"
<< _joint->getType() << "'.";
throw std::runtime_error(msg.str());
}
return std::move(space);
}
} // namespace statespace
} // namespace aikido
<|endoftext|> |
<commit_before>/******************************************************************************
This source file is part of the Avogadro project.
This source code is released under the 3-Clause BSD License, (see "LICENSE").
******************************************************************************/
#include "ballandstick.h"
#include <avogadro/core/elements.h>
#include <avogadro/qtgui/molecule.h>
#include <avogadro/rendering/cylindergeometry.h>
#include <avogadro/rendering/geometrynode.h>
#include <avogadro/rendering/groupnode.h>
#include <avogadro/rendering/spheregeometry.h>
#include <QtCore/QSettings>
#include <QtWidgets/QCheckBox>
#include <QtWidgets/QFormLayout>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QSlider>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
namespace Avogadro::QtPlugins {
using Core::Elements;
using QtGui::PluginLayerManager;
using Rendering::CylinderGeometry;
using Rendering::GeometryNode;
using Rendering::GroupNode;
using Rendering::SphereGeometry;
struct LayerBallAndStick : Core::LayerData
{
QWidget* widget;
bool multiBonds;
bool showHydrogens;
float atomScale;
float bondRadius;
LayerBallAndStick()
{
widget = nullptr;
QSettings settings;
atomScale = settings.value("ballandstick/atomScale", 0.3).toDouble();
bondRadius = settings.value("ballandstick/bondRadius", 0.1).toDouble();
multiBonds = settings.value("ballandstick/multiBonds", true).toBool();
showHydrogens = settings.value("ballandstick/showHydrogens", true).toBool();
}
~LayerBallAndStick() override
{
if (widget)
widget->deleteLater();
}
std::string serialize() final
{
return boolToString(multiBonds) + " " + boolToString(showHydrogens) + " " +
std::to_string(atomScale) + " " + std::to_string(bondRadius);
}
void deserialize(std::string text) final
{
std::stringstream ss(text);
std::string aux;
ss >> aux;
multiBonds = stringToBool(aux);
ss >> aux;
showHydrogens = stringToBool(aux);
ss >> aux;
atomScale = std::stof(aux);
ss >> aux;
bondRadius = std::stof(aux);
}
void setupWidget(BallAndStick* slot)
{
if (!widget) {
widget = new QWidget(qobject_cast<QWidget*>(slot->parent()));
auto* v = new QVBoxLayout;
auto* f = new QFormLayout;
auto* atomRadiusSlider = new QSlider(Qt::Horizontal);
atomRadiusSlider->setMinimum(1);
atomRadiusSlider->setMaximum(9);
atomRadiusSlider->setTickInterval(1);
atomRadiusSlider->setValue(atomScale * 10);
QObject::connect(atomRadiusSlider, &QSlider::valueChanged, slot,
&BallAndStick::atomRadiusChanged);
f->addRow(QObject::tr("Atom scale"), atomRadiusSlider);
auto* bondRadiusSlider = new QSlider(Qt::Horizontal);
bondRadiusSlider->setMinimum(1);
bondRadiusSlider->setMaximum(8);
bondRadiusSlider->setTickInterval(1);
bondRadiusSlider->setValue(bondRadius * 10);
QObject::connect(bondRadiusSlider, &QSlider::valueChanged, slot,
&BallAndStick::bondRadiusChanged);
f->addRow(QObject::tr("Bond scale"), bondRadiusSlider);
v->addLayout(f);
auto* check = new QCheckBox(QObject::tr("Show multiple bonds"));
check->setChecked(multiBonds);
QObject::connect(check, &QCheckBox::clicked, slot,
&BallAndStick::multiBonds);
v->addWidget(check);
check = new QCheckBox(QObject::tr("Show hydrogens"));
check->setChecked(showHydrogens);
QObject::connect(check, &QCheckBox::clicked, slot,
&BallAndStick::showHydrogens);
v->addWidget(check);
v->addStretch(1);
widget->setLayout(v);
}
}
};
BallAndStick::BallAndStick(QObject* p) : ScenePlugin(p), m_group(nullptr)
{
m_layerManager = PluginLayerManager(m_name);
}
BallAndStick::~BallAndStick() {}
void BallAndStick::process(const QtGui::Molecule& molecule,
Rendering::GroupNode& node)
{
m_layerManager.load<LayerBallAndStick>();
// Add a sphere node to contain all of the spheres.
m_group = &node;
auto* geometry = new GeometryNode;
node.addChild(geometry);
auto* spheres = new SphereGeometry;
auto selectedSpheres = new SphereGeometry;
selectedSpheres->setOpacity(0.42);
spheres->identifier().molecule = reinterpret_cast<const void*>(&molecule);
spheres->identifier().type = Rendering::AtomType;
geometry->addDrawable(spheres);
geometry->addDrawable(selectedSpheres);
for (Index i = 0; i < molecule.atomCount(); ++i) {
Core::Atom atom = molecule.atom(i);
if (!m_layerManager.atomEnabled(i)) {
continue;
}
unsigned char atomicNumber = atom.atomicNumber();
auto& interface = m_layerManager.getSetting<LayerBallAndStick>(
m_layerManager.getLayerID(i));
if (atomicNumber == 1 && !interface.showHydrogens)
continue;
Vector3ub color = atom.color();
auto radius = static_cast<float>(Elements::radiusVDW(atomicNumber));
float scale = interface.atomScale;
spheres->addSphere(atom.position3d().cast<float>(), color, radius * scale,
i);
if (atom.selected()) {
color = Vector3ub(0, 0, 255);
radius *= 1.2;
selectedSpheres->addSphere(atom.position3d().cast<float>(), color,
radius * scale, i);
}
}
auto* cylinders = new CylinderGeometry;
cylinders->identifier().molecule = &molecule;
cylinders->identifier().type = Rendering::BondType;
geometry->addDrawable(cylinders);
for (Index i = 0; i < molecule.bondCount(); ++i) {
Core::Bond bond = molecule.bond(i);
if (!m_layerManager.bondEnabled(bond.atom1().index(),
bond.atom2().index())) {
continue;
}
auto& interface1 =
m_layerManager.getSetting<LayerBallAndStick>(
m_layerManager.getLayerID(bond.atom1().index()));
auto& interface2 =
m_layerManager.getSetting<LayerBallAndStick>(
m_layerManager.getLayerID(bond.atom2().index()));
if (!interface1.showHydrogens && !interface2.showHydrogens &&
(bond.atom1().atomicNumber() == 1 ||
bond.atom2().atomicNumber() == 1)) {
continue;
}
float bondRadius = (interface1.bondRadius + interface2.bondRadius) * 0.5f;
Vector3f pos1 = bond.atom1().position3d().cast<float>();
Vector3f pos2 = bond.atom2().position3d().cast<float>();
Vector3ub color1 = bond.atom1().color();
Vector3ub color2 = bond.atom2().color();
Vector3f bondVector = pos2 - pos1;
float bondLength = bondVector.norm();
bondVector /= bondLength;
switch (interface1.multiBonds || interface2.multiBonds ? bond.order() : 1) {
case 3: {
Vector3f delta = bondVector.unitOrthogonal() * (2.0f * bondRadius);
cylinders->addCylinder(pos1 + delta, pos2 + delta, bondRadius, color1,
color2, i);
cylinders->addCylinder(pos1 - delta, pos2 - delta, bondRadius, color1,
color2, i);
}
default:
case 1:
cylinders->addCylinder(pos1, pos2, m_bondRadius, color1, color2, i);
break;
case 2: {
Vector3f delta = bondVector.unitOrthogonal() * bondRadius;
cylinders->addCylinder(pos1 + delta, pos2 + delta, bondRadius, color1,
color2, i);
cylinders->addCylinder(pos1 - delta, pos2 - delta, bondRadius, color1,
color2, i);
}
}
}
}
QWidget* BallAndStick::setupWidget()
{
auto& interface = m_layerManager.getSetting<LayerBallAndStick>();
interface.setupWidget(this);
return interface.widget;
}
void BallAndStick::atomRadiusChanged(int value)
{
m_atomScale = static_cast<float>(value) / 10.0f;
auto& interface = m_layerManager.getSetting<LayerBallAndStick>();
if (m_atomScale != interface.atomScale) {
interface.atomScale = m_atomScale;
emit drawablesChanged();
}
QSettings settings;
settings.setValue("ballandstick/atomScale", m_atomScale);
}
void BallAndStick::bondRadiusChanged(int value)
{
m_bondRadius = static_cast<float>(value) / 10.0f;
auto& interface = m_layerManager.getSetting<LayerBallAndStick>();
if (m_bondRadius != interface.bondRadius) {
interface.bondRadius = m_bondRadius;
emit drawablesChanged();
}
QSettings settings;
settings.setValue("ballandstick/bondRadius", m_bondRadius);
}
void BallAndStick::multiBonds(bool show)
{
auto& interface = m_layerManager.getSetting<LayerBallAndStick>();
if (show != interface.multiBonds) {
interface.multiBonds = show;
emit drawablesChanged();
}
QSettings settings;
settings.setValue("ballandstick/multiBonds", show);
}
void BallAndStick::showHydrogens(bool show)
{
auto& interface = m_layerManager.getSetting<LayerBallAndStick>();
if (show != interface.showHydrogens) {
interface.showHydrogens = show;
emit drawablesChanged();
}
QSettings settings;
settings.setValue("ballandstick/showHydrogens", show);
}
} // namespace Avogadro
<commit_msg>Tweak rendering multiple bonds, rotate 45 degree angle<commit_after>/******************************************************************************
This source file is part of the Avogadro project.
This source code is released under the 3-Clause BSD License, (see "LICENSE").
******************************************************************************/
#include "ballandstick.h"
#include <avogadro/core/elements.h>
#include <avogadro/qtgui/molecule.h>
#include <avogadro/rendering/cylindergeometry.h>
#include <avogadro/rendering/geometrynode.h>
#include <avogadro/rendering/groupnode.h>
#include <avogadro/rendering/spheregeometry.h>
#include <QtCore/QSettings>
#include <QtWidgets/QCheckBox>
#include <QtWidgets/QFormLayout>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QSlider>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
namespace Avogadro::QtPlugins {
using Core::Elements;
using QtGui::PluginLayerManager;
using Rendering::CylinderGeometry;
using Rendering::GeometryNode;
using Rendering::GroupNode;
using Rendering::SphereGeometry;
struct LayerBallAndStick : Core::LayerData
{
QWidget* widget;
bool multiBonds;
bool showHydrogens;
float atomScale;
float bondRadius;
LayerBallAndStick()
{
widget = nullptr;
QSettings settings;
atomScale = settings.value("ballandstick/atomScale", 0.3).toDouble();
bondRadius = settings.value("ballandstick/bondRadius", 0.1).toDouble();
multiBonds = settings.value("ballandstick/multiBonds", true).toBool();
showHydrogens = settings.value("ballandstick/showHydrogens", true).toBool();
}
~LayerBallAndStick() override
{
if (widget)
widget->deleteLater();
}
std::string serialize() final
{
return boolToString(multiBonds) + " " + boolToString(showHydrogens) + " " +
std::to_string(atomScale) + " " + std::to_string(bondRadius);
}
void deserialize(std::string text) final
{
std::stringstream ss(text);
std::string aux;
ss >> aux;
multiBonds = stringToBool(aux);
ss >> aux;
showHydrogens = stringToBool(aux);
ss >> aux;
atomScale = std::stof(aux);
ss >> aux;
bondRadius = std::stof(aux);
}
void setupWidget(BallAndStick* slot)
{
if (!widget) {
widget = new QWidget(qobject_cast<QWidget*>(slot->parent()));
auto* v = new QVBoxLayout;
auto* f = new QFormLayout;
auto* atomRadiusSlider = new QSlider(Qt::Horizontal);
atomRadiusSlider->setMinimum(1);
atomRadiusSlider->setMaximum(9);
atomRadiusSlider->setTickInterval(1);
atomRadiusSlider->setValue(atomScale * 10);
QObject::connect(atomRadiusSlider, &QSlider::valueChanged, slot,
&BallAndStick::atomRadiusChanged);
f->addRow(QObject::tr("Atom scale"), atomRadiusSlider);
auto* bondRadiusSlider = new QSlider(Qt::Horizontal);
bondRadiusSlider->setMinimum(1);
bondRadiusSlider->setMaximum(8);
bondRadiusSlider->setTickInterval(1);
bondRadiusSlider->setValue(bondRadius * 10);
QObject::connect(bondRadiusSlider, &QSlider::valueChanged, slot,
&BallAndStick::bondRadiusChanged);
f->addRow(QObject::tr("Bond scale"), bondRadiusSlider);
v->addLayout(f);
auto* check = new QCheckBox(QObject::tr("Show multiple bonds"));
check->setChecked(multiBonds);
QObject::connect(check, &QCheckBox::clicked, slot,
&BallAndStick::multiBonds);
v->addWidget(check);
check = new QCheckBox(QObject::tr("Show hydrogens"));
check->setChecked(showHydrogens);
QObject::connect(check, &QCheckBox::clicked, slot,
&BallAndStick::showHydrogens);
v->addWidget(check);
v->addStretch(1);
widget->setLayout(v);
}
}
};
BallAndStick::BallAndStick(QObject* p) : ScenePlugin(p), m_group(nullptr)
{
m_layerManager = PluginLayerManager(m_name);
}
BallAndStick::~BallAndStick() {}
void BallAndStick::process(const QtGui::Molecule& molecule,
Rendering::GroupNode& node)
{
m_layerManager.load<LayerBallAndStick>();
// Add a sphere node to contain all of the spheres.
m_group = &node;
auto* geometry = new GeometryNode;
node.addChild(geometry);
auto* spheres = new SphereGeometry;
auto selectedSpheres = new SphereGeometry;
selectedSpheres->setOpacity(0.42);
spheres->identifier().molecule = reinterpret_cast<const void*>(&molecule);
spheres->identifier().type = Rendering::AtomType;
geometry->addDrawable(spheres);
geometry->addDrawable(selectedSpheres);
for (Index i = 0; i < molecule.atomCount(); ++i) {
Core::Atom atom = molecule.atom(i);
if (!m_layerManager.atomEnabled(i)) {
continue;
}
unsigned char atomicNumber = atom.atomicNumber();
auto& interface = m_layerManager.getSetting<LayerBallAndStick>(
m_layerManager.getLayerID(i));
if (atomicNumber == 1 && !interface.showHydrogens)
continue;
Vector3ub color = atom.color();
auto radius = static_cast<float>(Elements::radiusVDW(atomicNumber));
float scale = interface.atomScale;
spheres->addSphere(atom.position3d().cast<float>(), color, radius * scale,
i);
if (atom.selected()) {
color = Vector3ub(0, 0, 255);
radius *= 1.2;
selectedSpheres->addSphere(atom.position3d().cast<float>(), color,
radius * scale, i);
}
}
auto* cylinders = new CylinderGeometry;
cylinders->identifier().molecule = &molecule;
cylinders->identifier().type = Rendering::BondType;
geometry->addDrawable(cylinders);
for (Index i = 0; i < molecule.bondCount(); ++i) {
Core::Bond bond = molecule.bond(i);
if (!m_layerManager.bondEnabled(bond.atom1().index(),
bond.atom2().index())) {
continue;
}
auto& interface1 = m_layerManager.getSetting<LayerBallAndStick>(
m_layerManager.getLayerID(bond.atom1().index()));
auto& interface2 = m_layerManager.getSetting<LayerBallAndStick>(
m_layerManager.getLayerID(bond.atom2().index()));
if (!interface1.showHydrogens && !interface2.showHydrogens &&
(bond.atom1().atomicNumber() == 1 ||
bond.atom2().atomicNumber() == 1)) {
continue;
}
float bondRadius = (interface1.bondRadius + interface2.bondRadius) * 0.5f;
Vector3f pos1 = bond.atom1().position3d().cast<float>();
Vector3f pos2 = bond.atom2().position3d().cast<float>();
Vector3ub color1 = bond.atom1().color();
Vector3ub color2 = bond.atom2().color();
Vector3f bondVector = pos2 - pos1;
float bondLength = bondVector.norm();
bondVector /= bondLength;
switch (interface1.multiBonds || interface2.multiBonds ? bond.order() : 1) {
case 3: {
Vector3f delta = bondVector.unitOrthogonal();
// Rotate 45 degrees around the bond vector.
Eigen::Quaternionf q;
q = Eigen::AngleAxisf(45.0f * DEG_TO_RAD_F, bondVector);
delta = q * delta * 2.0f * bondRadius;
cylinders->addCylinder(pos1 + delta, pos2 + delta, bondRadius * 1.15,
color1, color2, i);
cylinders->addCylinder(pos1 - delta, pos2 - delta, bondRadius * 1.15,
color1, color2, i);
}
default:
case 1:
cylinders->addCylinder(pos1, pos2, m_bondRadius, color1, color2, i);
break;
case 2: {
Vector3f delta = bondVector.unitOrthogonal();
// Rotate 45 degrees around the bond vector.
Eigen::Quaternionf q;
q = Eigen::AngleAxisf(45.0f * DEG_TO_RAD_F, bondVector);
delta = q * delta * bondRadius;
cylinders->addCylinder(pos1 + delta, pos2 + delta, bondRadius * 1.3,
color1, color2, i);
cylinders->addCylinder(pos1 - delta, pos2 - delta, bondRadius * 1.3,
color1, color2, i);
}
}
}
}
QWidget* BallAndStick::setupWidget()
{
auto& interface = m_layerManager.getSetting<LayerBallAndStick>();
interface.setupWidget(this);
return interface.widget;
}
void BallAndStick::atomRadiusChanged(int value)
{
m_atomScale = static_cast<float>(value) / 10.0f;
auto& interface = m_layerManager.getSetting<LayerBallAndStick>();
if (m_atomScale != interface.atomScale) {
interface.atomScale = m_atomScale;
emit drawablesChanged();
}
QSettings settings;
settings.setValue("ballandstick/atomScale", m_atomScale);
}
void BallAndStick::bondRadiusChanged(int value)
{
m_bondRadius = static_cast<float>(value) / 10.0f;
auto& interface = m_layerManager.getSetting<LayerBallAndStick>();
if (m_bondRadius != interface.bondRadius) {
interface.bondRadius = m_bondRadius;
emit drawablesChanged();
}
QSettings settings;
settings.setValue("ballandstick/bondRadius", m_bondRadius);
}
void BallAndStick::multiBonds(bool show)
{
auto& interface = m_layerManager.getSetting<LayerBallAndStick>();
if (show != interface.multiBonds) {
interface.multiBonds = show;
emit drawablesChanged();
}
QSettings settings;
settings.setValue("ballandstick/multiBonds", show);
}
void BallAndStick::showHydrogens(bool show)
{
auto& interface = m_layerManager.getSetting<LayerBallAndStick>();
if (show != interface.showHydrogens) {
interface.showHydrogens = show;
emit drawablesChanged();
}
QSettings settings;
settings.setValue("ballandstick/showHydrogens", show);
}
} // namespace Avogadro::QtPlugins
<|endoftext|> |
<commit_before>#pragma once
#include <map>
#include <utki/shared.hpp>
#include <papki/file.hpp>
#include <puu/tree.hpp>
namespace morda{
class resource;
class context;
/**
* @brief Resource loader.
* This class manages application recources loading from puu resource description scripts.
*
* Format of resource description scripts is simple. It uses puu markup.
* Each resource is a root-level puu node, the value is a name of the resource, by that name
* the application will load that resource.The children of resource name are the properties of the resource.
* Each resource type defines their own properties.
*
* It is also possible to include another resource descriptions using the include directive at the root level.
*
* Example:
* @code
* // include another resource script into this one
* include{some_other.res}
*
* // Example of resource declaration
* img_may_image_resource // resource name
* {
* // image resource has only one attribute 'file' which tells from
* // from which file to load the image
* file{sample_image.png}
* }
*
* @endcode
*/
class resource_loader{
friend class context;
friend class resource;
std::map<const std::string, std::weak_ptr<resource>> resMap;
class ResPackEntry{
public:
ResPackEntry() = default;
//For MSVC compiler, it does not generate move constructor automatically
//TODO: check if this is still needed.
ResPackEntry(ResPackEntry&& r){
this->fi = std::move(r.fi);
this->script = std::move(r.script);
}
std::unique_ptr<const papki::file> fi;
puu::forest script;
};
std::vector<ResPackEntry> resPacks;
class FindInScriptRet{
public:
FindInScriptRet(ResPackEntry& resPack, const puu::tree& element) :
rp(resPack),
e(element)
{}
ResPackEntry& rp;
const puu::tree& e;
};
FindInScriptRet findResourceInScript(const std::string& resName);
template <class T> std::shared_ptr<T> findResourceInResMap(const char* resName);
// Add resource to resources map
void addResource(const std::shared_ptr<resource>& res, const std::string& name);
private:
context& ctx;
resource_loader(context& ctx) :
ctx(ctx)
{}
public:
/**
* @brief Mount a resource pack.
* This function adds a resource pack to the list of known resource packs.
* It loads the resource description and uses it when searching for resource
* when resource loading is needed.
* @param fi - file interface pointing to the resource pack's STOB description.
* If file interface points to a directory instead of a file then
* resource description filename is assumed to be "main.res.stob".
*/
void mount_res_pack(const papki::file& fi);
/**
* @brief Load a resource.
* This is a template function. Resource types are not indicated anyhow in
* resource descriptions, so it is necessary to indicate resource of which type
* you are loading by specifying a resource class as a template parameter of the function.
*
* Example:
* @code
* auto image = this->context->loader().load<morda::ResImage>("img_my_image_name");
* @endcode
*
* @param name - name of the resource as it appears in resource description.
* @return Loaded resource.
*/
template <class T> std::shared_ptr<T> load(const char* name);
template <class T> std::shared_ptr<T> load(const std::string& name){
return this->load<T>(resName.c_str());
}
private:
};
/**
* @brief Base class for all resources.
*/
class resource : virtual public utki::shared{
friend class resource_loader;
protected:
const std::shared_ptr<morda::context> context;
// this can only be used as a base class
resource(std::shared_ptr<morda::context> c) :
context(std::move(c))
{
if(!this->context){
throw std::invalid_argument("ResImage::ResImage(): passed in context is null");
}
}
public:
virtual ~resource()noexcept{}
};
template <class T> std::shared_ptr<T> resource_loader::findResourceInResMap(const char* resName){
auto i = this->resMap.find(resName);
if(i != this->resMap.end()){
if(auto r = (*i).second.lock()){
return std::dynamic_pointer_cast<T>(std::move(r));
}
this->resMap.erase(i);
}
return nullptr;//no resource found with given name, return invalid reference
}
template <class T> std::shared_ptr<T> resource_loader::load(const char* resName){
// TRACE(<< "ResMan::Load(): enter" << std::endl)
if(auto r = this->findResourceInResMap<T>(resName)){
// TRACE(<< "ResManHGE::Load(): resource found in map" << std::endl)
return r;
}
// TRACE(<< "ResMan::Load(): searching for resource in script..." << std::endl)
FindInScriptRet ret = this->findResourceInScript(resName);
ASSERT(ret.rp.fi)
// TRACE(<< "ResMan::Load(): resource found in script" << std::endl)
auto resource = T::load(this->ctx, ret.e.children, *ret.rp.fi);
this->addResource(resource, ret.e.value.to_string());
// TRACE(<< "ResMan::LoadTexture(): exit" << std::endl)
return resource;
}
}
<commit_msg>stuff<commit_after>#pragma once
#include <map>
#include <utki/shared.hpp>
#include <papki/file.hpp>
#include <puu/tree.hpp>
namespace morda{
class resource;
class context;
/**
* @brief Resource loader.
* This class manages application recources loading from puu resource description scripts.
*
* Format of resource description scripts is simple. It uses puu markup.
* Each resource is a root-level puu node, the value is a name of the resource, by that name
* the application will load that resource.The children of resource name are the properties of the resource.
* Each resource type defines their own properties.
*
* It is also possible to include another resource descriptions using the include directive at the root level.
*
* Example:
* @code
* // include another resource script into this one
* include{some_other.res}
*
* // Example of resource declaration
* img_may_image_resource // resource name
* {
* // image resource has only one attribute 'file' which tells from
* // from which file to load the image
* file{sample_image.png}
* }
*
* @endcode
*/
class resource_loader{
friend class context;
friend class resource;
std::map<const std::string, std::weak_ptr<resource>> resMap;
class ResPackEntry{
public:
ResPackEntry() = default;
//For MSVC compiler, it does not generate move constructor automatically
//TODO: check if this is still needed.
ResPackEntry(ResPackEntry&& r){
this->fi = std::move(r.fi);
this->script = std::move(r.script);
}
std::unique_ptr<const papki::file> fi;
puu::forest script;
};
std::vector<ResPackEntry> resPacks;
class FindInScriptRet{
public:
FindInScriptRet(ResPackEntry& resPack, const puu::tree& element) :
rp(resPack),
e(element)
{}
ResPackEntry& rp;
const puu::tree& e;
};
FindInScriptRet findResourceInScript(const std::string& resName);
template <class T> std::shared_ptr<T> findResourceInResMap(const char* resName);
// Add resource to resources map
void addResource(const std::shared_ptr<resource>& res, const std::string& name);
private:
context& ctx;
resource_loader(context& ctx) :
ctx(ctx)
{}
public:
/**
* @brief Mount a resource pack.
* This function adds a resource pack to the list of known resource packs.
* It loads the resource description and uses it when searching for resource
* when resource loading is needed.
* @param fi - file interface pointing to the resource pack's STOB description.
* If file interface points to a directory instead of a file then
* resource description filename is assumed to be "main.res.stob".
*/
void mount_res_pack(const papki::file& fi);
/**
* @brief Load a resource.
* This is a template function. Resource types are not indicated anyhow in
* resource descriptions, so it is necessary to indicate resource of which type
* you are loading by specifying a resource class as a template parameter of the function.
*
* Example:
* @code
* auto image = this->context->loader().load<morda::ResImage>("img_my_image_name");
* @endcode
*
* @param name - name of the resource as it appears in resource description.
* @return Loaded resource.
*/
template <class T> std::shared_ptr<T> load(const char* name);
template <class T> std::shared_ptr<T> load(const std::string& name){
return this->load<T>(name.c_str());
}
private:
};
/**
* @brief Base class for all resources.
*/
class resource : virtual public utki::shared{
friend class resource_loader;
protected:
const std::shared_ptr<morda::context> context;
// this can only be used as a base class
resource(std::shared_ptr<morda::context> c) :
context(std::move(c))
{
if(!this->context){
throw std::invalid_argument("ResImage::ResImage(): passed in context is null");
}
}
public:
virtual ~resource()noexcept{}
};
template <class T> std::shared_ptr<T> resource_loader::findResourceInResMap(const char* resName){
auto i = this->resMap.find(resName);
if(i != this->resMap.end()){
if(auto r = (*i).second.lock()){
return std::dynamic_pointer_cast<T>(std::move(r));
}
this->resMap.erase(i);
}
return nullptr;//no resource found with given name, return invalid reference
}
template <class T> std::shared_ptr<T> resource_loader::load(const char* resName){
// TRACE(<< "ResMan::Load(): enter" << std::endl)
if(auto r = this->findResourceInResMap<T>(resName)){
// TRACE(<< "ResManHGE::Load(): resource found in map" << std::endl)
return r;
}
// TRACE(<< "ResMan::Load(): searching for resource in script..." << std::endl)
FindInScriptRet ret = this->findResourceInScript(resName);
ASSERT(ret.rp.fi)
// TRACE(<< "ResMan::Load(): resource found in script" << std::endl)
auto resource = T::load(this->ctx, ret.e.children, *ret.rp.fi);
this->addResource(resource, ret.e.value.to_string());
// TRACE(<< "ResMan::LoadTexture(): exit" << std::endl)
return resource;
}
}
<|endoftext|> |
<commit_before>/**
* This file is part of the CernVM File System.
*/
#include "io_dispatcher.h"
#include <cassert>
#include <cerrno>
#include "file.h"
#include "processor.h"
#include "chunk.h"
#include "file_processor.h"
#include "../util_concurrency.h"
using namespace upload;
void IoDispatcher::ScheduleWrite(Chunk *chunk,
CharBuffer *buffer,
const bool delete_buffer) {
assert (chunk != NULL);
assert (chunk->IsInitialized());
assert (buffer != NULL);
assert (buffer->IsInitialized());
assert (buffer->used_bytes() > 0);
// Initialize a streamed upload in the AbstractUploader implementation if it
// has not been done before for this Chunk.
if (! chunk->HasUploadStreamHandle()) {
UploadStreamHandle *handle = uploader_->InitStreamedUpload(
// the closure passed here, is called by the AbstractUploader as soon as
// it successfully committed the complete chunk
AbstractUploader::MakeClosure(&IoDispatcher::ChunkUploadCompleteCallback,
this,
chunk));
assert (handle != NULL);
chunk->set_upload_stream_handle(handle);
}
// Schedule the upload of the provided data Block into the chunk
uploader_->ScheduleUpload(chunk->upload_stream_handle(), buffer,
AbstractUploader::MakeClosure(&IoDispatcher::BufferUploadCompleteCallback,
this,
BufferUploadCompleteParam(chunk,
buffer,
delete_buffer)));
}
void IoDispatcher::ScheduleCommit(Chunk* chunk) {
assert (chunk->IsFullyProcessed());
assert (chunk->HasUploadStreamHandle());
// Finalize the streamed upload for the committed Chunk
uploader_->ScheduleCommit(chunk->upload_stream_handle(),
chunk->content_hash(),
chunk->hash_suffix());
}
void IoDispatcher::BufferUploadCompleteCallback(
const UploaderResults &results,
BufferUploadCompleteParam buffer_info) {
Chunk *chunk = buffer_info.chunk;
CharBuffer *buffer = buffer_info.buffer;
const bool delete_buffer = buffer_info.delete_buffer;
assert (results.return_code == 0);
chunk->add_bytes_written(buffer->used_bytes());
if (delete_buffer) {
delete buffer;
}
}
void IoDispatcher::ChunkUploadCompleteCallback(const UploaderResults &results,
Chunk* chunk) {
assert (chunk->IsFullyProcessed());
assert (chunk->HasUploadStreamHandle());
assert (chunk->bytes_written() == chunk->compressed_size());
assert (results.return_code == 0);
chunk->file()->ChunkCommitted(chunk);
pthread_mutex_lock(&processing_done_mutex_);
if (--chunks_in_flight_ == 0) {
pthread_cond_signal(&processing_done_condition_);
}
pthread_mutex_unlock(&processing_done_mutex_);
}
void IoDispatcher::CommitFile(File *file) {
file_processor_->FileDone(file);
delete file;
}
<commit_msg>allow upload of empty CharBuffer<commit_after>/**
* This file is part of the CernVM File System.
*/
#include "io_dispatcher.h"
#include <cassert>
#include <cerrno>
#include "file.h"
#include "processor.h"
#include "chunk.h"
#include "file_processor.h"
#include "../util_concurrency.h"
using namespace upload;
void IoDispatcher::ScheduleWrite(Chunk *chunk,
CharBuffer *buffer,
const bool delete_buffer) {
assert (chunk != NULL);
assert (chunk->IsInitialized());
assert (buffer != NULL);
assert (buffer->IsInitialized());
// Initialize a streamed upload in the AbstractUploader implementation if it
// has not been done before for this Chunk.
if (! chunk->HasUploadStreamHandle()) {
UploadStreamHandle *handle = uploader_->InitStreamedUpload(
// the closure passed here, is called by the AbstractUploader as soon as
// it successfully committed the complete chunk
AbstractUploader::MakeClosure(&IoDispatcher::ChunkUploadCompleteCallback,
this,
chunk));
assert (handle != NULL);
chunk->set_upload_stream_handle(handle);
}
// Schedule the upload of the provided data Block into the chunk
uploader_->ScheduleUpload(chunk->upload_stream_handle(), buffer,
AbstractUploader::MakeClosure(&IoDispatcher::BufferUploadCompleteCallback,
this,
BufferUploadCompleteParam(chunk,
buffer,
delete_buffer)));
}
void IoDispatcher::ScheduleCommit(Chunk* chunk) {
assert (chunk->IsFullyProcessed());
assert (chunk->HasUploadStreamHandle());
// Finalize the streamed upload for the committed Chunk
uploader_->ScheduleCommit(chunk->upload_stream_handle(),
chunk->content_hash(),
chunk->hash_suffix());
}
void IoDispatcher::BufferUploadCompleteCallback(
const UploaderResults &results,
BufferUploadCompleteParam buffer_info) {
Chunk *chunk = buffer_info.chunk;
CharBuffer *buffer = buffer_info.buffer;
const bool delete_buffer = buffer_info.delete_buffer;
assert (results.return_code == 0);
chunk->add_bytes_written(buffer->used_bytes());
if (delete_buffer) {
delete buffer;
}
}
void IoDispatcher::ChunkUploadCompleteCallback(const UploaderResults &results,
Chunk* chunk) {
assert (chunk->IsFullyProcessed());
assert (chunk->HasUploadStreamHandle());
assert (chunk->bytes_written() == chunk->compressed_size());
assert (results.return_code == 0);
chunk->file()->ChunkCommitted(chunk);
pthread_mutex_lock(&processing_done_mutex_);
if (--chunks_in_flight_ == 0) {
pthread_cond_signal(&processing_done_condition_);
}
pthread_mutex_unlock(&processing_done_mutex_);
}
void IoDispatcher::CommitFile(File *file) {
file_processor_->FileDone(file);
delete file;
}
<|endoftext|> |
<commit_before>// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#include <opencv2/core.hpp>
#include <opencv2/calib3d.hpp>
#include <opencv2/cvconfig.h>
#include <opencv2/highgui.hpp>
#ifdef HAVE_OPENCV_ARUCO
#include <opencv2/aruco/charuco.hpp>
#endif
#include <string>
#include <vector>
#include <stdexcept>
#include <algorithm>
#include <iostream>
#include "calibCommon.hpp"
#include "calibPipeline.hpp"
#include "frameProcessor.hpp"
#include "calibController.hpp"
#include "parametersController.hpp"
#include "rotationConverters.hpp"
using namespace calib;
const std::string keys =
"{v | | Input from video file }"
"{ci | 0 | Default camera id }"
"{flip | false | Vertical flip of input frames }"
"{t | circles | Template for calibration (circles, chessboard, dualCircles, charuco) }"
"{sz | 16.3 | Distance between two nearest centers of circles or squares on calibration board}"
"{dst | 295 | Distance between white and black parts of daulCircles template}"
"{w | | Width of template (in corners or circles)}"
"{h | | Height of template (in corners or circles)}"
"{of | cameraParameters.xml | Output file name}"
"{ft | true | Auto tuning of calibration flags}"
"{vis | grid | Captured boards visualisation (grid, window)}"
"{d | 0.8 | Min delay between captures}"
"{pf | defaultConfig.xml| Advanced application parameters}"
"{help | | Print help}";
bool calib::showOverlayMessage(const std::string& message)
{
#ifdef HAVE_QT
cv::displayOverlay(mainWindowName, message, OVERLAY_DELAY);
return true;
#else
std::cout << message << std::endl;
return false;
#endif
}
static void deleteButton(int, void* data)
{
(static_cast<cv::Ptr<calibDataController>*>(data))->get()->deleteLastFrame();
calib::showOverlayMessage("Last frame deleted");
}
static void deleteAllButton(int, void* data)
{
(static_cast<cv::Ptr<calibDataController>*>(data))->get()->deleteAllData();
calib::showOverlayMessage("All frames deleted");
}
static void saveCurrentParamsButton(int, void* data)
{
if((static_cast<cv::Ptr<calibDataController>*>(data))->get()->saveCurrentCameraParameters())
calib::showOverlayMessage("Calibration parameters saved");
}
#ifdef HAVE_QT
static void switchVisualizationModeButton(int, void* data)
{
ShowProcessor* processor = static_cast<ShowProcessor*>(((cv::Ptr<FrameProcessor>*)data)->get());
processor->switchVisualizationMode();
}
static void undistortButton(int state, void* data)
{
ShowProcessor* processor = static_cast<ShowProcessor*>(((cv::Ptr<FrameProcessor>*)data)->get());
processor->setUndistort(static_cast<bool>(state));
calib::showOverlayMessage(std::string("Undistort is ") +
(static_cast<bool>(state) ? std::string("on") : std::string("off")));
}
#endif //HAVE_QT
int main(int argc, char** argv)
{
cv::CommandLineParser parser(argc, argv, keys);
if(parser.has("help")) {
parser.printMessage();
return 0;
}
std::cout << consoleHelp << std::endl;
parametersController paramsController;
if(!paramsController.loadFromParser(parser))
return 0;
captureParameters capParams = paramsController.getCaptureParameters();
internalParameters intParams = paramsController.getInternalParameters();
#ifndef HAVE_OPENCV_ARUCO
if(capParams.board == chAruco)
CV_Error(cv::Error::StsNotImplemented, "Aruco module is disabled in current build configuration."
" Consider usage of another calibration pattern\n");
#endif
cv::TermCriteria solverTermCrit = cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS,
intParams.solverMaxIters, intParams.solverEps);
cv::Ptr<calibrationData> globalData(new calibrationData);
if(!parser.has("v")) globalData->imageSize = capParams.cameraResolution;
int calibrationFlags = 0;
if(intParams.fastSolving) calibrationFlags |= cv::CALIB_USE_QR;
cv::Ptr<calibController> controller(new calibController(globalData, calibrationFlags,
parser.get<bool>("ft"), capParams.minFramesNum));
cv::Ptr<calibDataController> dataController(new calibDataController(globalData, capParams.maxFramesNum,
intParams.filterAlpha));
dataController->setParametersFileName(parser.get<std::string>("of"));
cv::Ptr<FrameProcessor> capProcessor, showProcessor;
capProcessor = cv::Ptr<FrameProcessor>(new CalibProcessor(globalData, capParams));
showProcessor = cv::Ptr<FrameProcessor>(new ShowProcessor(globalData, controller, capParams.board));
if(parser.get<std::string>("vis").find("window") == 0) {
static_cast<ShowProcessor*>(showProcessor.get())->setVisualizationMode(Window);
cv::namedWindow(gridWindowName);
cv::moveWindow(gridWindowName, 1280, 500);
}
cv::Ptr<CalibPipeline> pipeline(new CalibPipeline(capParams));
std::vector<cv::Ptr<FrameProcessor> > processors;
processors.push_back(capProcessor);
processors.push_back(showProcessor);
cv::namedWindow(mainWindowName);
cv::moveWindow(mainWindowName, 10, 10);
#ifdef HAVE_QT
cv::createButton("Delete last frame", deleteButton, &dataController,
cv::QT_PUSH_BUTTON | cv::QT_NEW_BUTTONBAR);
cv::createButton("Delete all frames", deleteAllButton, &dataController,
cv::QT_PUSH_BUTTON | cv::QT_NEW_BUTTONBAR);
cv::createButton("Undistort", undistortButton, &showProcessor,
cv::QT_CHECKBOX | cv::QT_NEW_BUTTONBAR, false);
cv::createButton("Save current parameters", saveCurrentParamsButton, &dataController,
cv::QT_PUSH_BUTTON | cv::QT_NEW_BUTTONBAR);
cv::createButton("Switch visualisation mode", switchVisualizationModeButton, &showProcessor,
cv::QT_PUSH_BUTTON | cv::QT_NEW_BUTTONBAR);
#endif //HAVE_QT
try {
bool pipelineFinished = false;
while(!pipelineFinished)
{
PipelineExitStatus exitStatus = pipeline->start(processors);
if (exitStatus == Finished) {
if(controller->getCommonCalibrationState())
saveCurrentParamsButton(0, &dataController);
pipelineFinished = true;
continue;
}
else if (exitStatus == Calibrate) {
dataController->rememberCurrentParameters();
globalData->imageSize = pipeline->getImageSize();
calibrationFlags = controller->getNewFlags();
if(capParams.board != chAruco) {
globalData->totalAvgErr =
cv::calibrateCamera(globalData->objectPoints, globalData->imagePoints,
globalData->imageSize, globalData->cameraMatrix,
globalData->distCoeffs, cv::noArray(), cv::noArray(),
globalData->stdDeviations, cv::noArray(), globalData->perViewErrors,
calibrationFlags, solverTermCrit);
}
else {
#ifdef HAVE_OPENCV_ARUCO
cv::Ptr<cv::aruco::Dictionary> dictionary =
cv::aruco::getPredefinedDictionary(cv::aruco::PREDEFINED_DICTIONARY_NAME(capParams.charucoDictName));
cv::Ptr<cv::aruco::CharucoBoard> charucoboard =
cv::aruco::CharucoBoard::create(capParams.boardSize.width, capParams.boardSize.height,
capParams.charucoSquareLenght, capParams.charucoMarkerSize, dictionary);
globalData->totalAvgErr =
cv::aruco::calibrateCameraCharuco(globalData->allCharucoCorners, globalData->allCharucoIds,
charucoboard, globalData->imageSize,
globalData->cameraMatrix, globalData->distCoeffs,
cv::noArray(), cv::noArray(), globalData->stdDeviations, cv::noArray(),
globalData->perViewErrors, calibrationFlags, solverTermCrit);
#endif
}
dataController->updateUndistortMap();
dataController->printParametersToConsole(std::cout);
controller->updateState();
for(int j = 0; j < capParams.calibrationStep; j++)
dataController->filterFrames();
static_cast<ShowProcessor*>(showProcessor.get())->updateBoardsView();
}
else if (exitStatus == DeleteLastFrame) {
deleteButton(0, &dataController);
static_cast<ShowProcessor*>(showProcessor.get())->updateBoardsView();
}
else if (exitStatus == DeleteAllFrames) {
deleteAllButton(0, &dataController);
static_cast<ShowProcessor*>(showProcessor.get())->updateBoardsView();
}
else if (exitStatus == SaveCurrentData) {
saveCurrentParamsButton(0, &dataController);
}
else if (exitStatus == SwitchUndistort)
static_cast<ShowProcessor*>(showProcessor.get())->switchUndistort();
else if (exitStatus == SwitchVisualisation)
static_cast<ShowProcessor*>(showProcessor.get())->switchVisualizationMode();
for (std::vector<cv::Ptr<FrameProcessor> >::iterator it = processors.begin(); it != processors.end(); ++it)
(*it)->resetState();
}
}
catch (std::runtime_error exp) {
std::cout << exp.what() << std::endl;
}
return 0;
}
<commit_msg>apps: catch() with "const reference"<commit_after>// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#include <opencv2/core.hpp>
#include <opencv2/calib3d.hpp>
#include <opencv2/cvconfig.h>
#include <opencv2/highgui.hpp>
#ifdef HAVE_OPENCV_ARUCO
#include <opencv2/aruco/charuco.hpp>
#endif
#include <string>
#include <vector>
#include <stdexcept>
#include <algorithm>
#include <iostream>
#include "calibCommon.hpp"
#include "calibPipeline.hpp"
#include "frameProcessor.hpp"
#include "calibController.hpp"
#include "parametersController.hpp"
#include "rotationConverters.hpp"
using namespace calib;
const std::string keys =
"{v | | Input from video file }"
"{ci | 0 | Default camera id }"
"{flip | false | Vertical flip of input frames }"
"{t | circles | Template for calibration (circles, chessboard, dualCircles, charuco) }"
"{sz | 16.3 | Distance between two nearest centers of circles or squares on calibration board}"
"{dst | 295 | Distance between white and black parts of daulCircles template}"
"{w | | Width of template (in corners or circles)}"
"{h | | Height of template (in corners or circles)}"
"{of | cameraParameters.xml | Output file name}"
"{ft | true | Auto tuning of calibration flags}"
"{vis | grid | Captured boards visualisation (grid, window)}"
"{d | 0.8 | Min delay between captures}"
"{pf | defaultConfig.xml| Advanced application parameters}"
"{help | | Print help}";
bool calib::showOverlayMessage(const std::string& message)
{
#ifdef HAVE_QT
cv::displayOverlay(mainWindowName, message, OVERLAY_DELAY);
return true;
#else
std::cout << message << std::endl;
return false;
#endif
}
static void deleteButton(int, void* data)
{
(static_cast<cv::Ptr<calibDataController>*>(data))->get()->deleteLastFrame();
calib::showOverlayMessage("Last frame deleted");
}
static void deleteAllButton(int, void* data)
{
(static_cast<cv::Ptr<calibDataController>*>(data))->get()->deleteAllData();
calib::showOverlayMessage("All frames deleted");
}
static void saveCurrentParamsButton(int, void* data)
{
if((static_cast<cv::Ptr<calibDataController>*>(data))->get()->saveCurrentCameraParameters())
calib::showOverlayMessage("Calibration parameters saved");
}
#ifdef HAVE_QT
static void switchVisualizationModeButton(int, void* data)
{
ShowProcessor* processor = static_cast<ShowProcessor*>(((cv::Ptr<FrameProcessor>*)data)->get());
processor->switchVisualizationMode();
}
static void undistortButton(int state, void* data)
{
ShowProcessor* processor = static_cast<ShowProcessor*>(((cv::Ptr<FrameProcessor>*)data)->get());
processor->setUndistort(static_cast<bool>(state));
calib::showOverlayMessage(std::string("Undistort is ") +
(static_cast<bool>(state) ? std::string("on") : std::string("off")));
}
#endif //HAVE_QT
int main(int argc, char** argv)
{
cv::CommandLineParser parser(argc, argv, keys);
if(parser.has("help")) {
parser.printMessage();
return 0;
}
std::cout << consoleHelp << std::endl;
parametersController paramsController;
if(!paramsController.loadFromParser(parser))
return 0;
captureParameters capParams = paramsController.getCaptureParameters();
internalParameters intParams = paramsController.getInternalParameters();
#ifndef HAVE_OPENCV_ARUCO
if(capParams.board == chAruco)
CV_Error(cv::Error::StsNotImplemented, "Aruco module is disabled in current build configuration."
" Consider usage of another calibration pattern\n");
#endif
cv::TermCriteria solverTermCrit = cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS,
intParams.solverMaxIters, intParams.solverEps);
cv::Ptr<calibrationData> globalData(new calibrationData);
if(!parser.has("v")) globalData->imageSize = capParams.cameraResolution;
int calibrationFlags = 0;
if(intParams.fastSolving) calibrationFlags |= cv::CALIB_USE_QR;
cv::Ptr<calibController> controller(new calibController(globalData, calibrationFlags,
parser.get<bool>("ft"), capParams.minFramesNum));
cv::Ptr<calibDataController> dataController(new calibDataController(globalData, capParams.maxFramesNum,
intParams.filterAlpha));
dataController->setParametersFileName(parser.get<std::string>("of"));
cv::Ptr<FrameProcessor> capProcessor, showProcessor;
capProcessor = cv::Ptr<FrameProcessor>(new CalibProcessor(globalData, capParams));
showProcessor = cv::Ptr<FrameProcessor>(new ShowProcessor(globalData, controller, capParams.board));
if(parser.get<std::string>("vis").find("window") == 0) {
static_cast<ShowProcessor*>(showProcessor.get())->setVisualizationMode(Window);
cv::namedWindow(gridWindowName);
cv::moveWindow(gridWindowName, 1280, 500);
}
cv::Ptr<CalibPipeline> pipeline(new CalibPipeline(capParams));
std::vector<cv::Ptr<FrameProcessor> > processors;
processors.push_back(capProcessor);
processors.push_back(showProcessor);
cv::namedWindow(mainWindowName);
cv::moveWindow(mainWindowName, 10, 10);
#ifdef HAVE_QT
cv::createButton("Delete last frame", deleteButton, &dataController,
cv::QT_PUSH_BUTTON | cv::QT_NEW_BUTTONBAR);
cv::createButton("Delete all frames", deleteAllButton, &dataController,
cv::QT_PUSH_BUTTON | cv::QT_NEW_BUTTONBAR);
cv::createButton("Undistort", undistortButton, &showProcessor,
cv::QT_CHECKBOX | cv::QT_NEW_BUTTONBAR, false);
cv::createButton("Save current parameters", saveCurrentParamsButton, &dataController,
cv::QT_PUSH_BUTTON | cv::QT_NEW_BUTTONBAR);
cv::createButton("Switch visualisation mode", switchVisualizationModeButton, &showProcessor,
cv::QT_PUSH_BUTTON | cv::QT_NEW_BUTTONBAR);
#endif //HAVE_QT
try {
bool pipelineFinished = false;
while(!pipelineFinished)
{
PipelineExitStatus exitStatus = pipeline->start(processors);
if (exitStatus == Finished) {
if(controller->getCommonCalibrationState())
saveCurrentParamsButton(0, &dataController);
pipelineFinished = true;
continue;
}
else if (exitStatus == Calibrate) {
dataController->rememberCurrentParameters();
globalData->imageSize = pipeline->getImageSize();
calibrationFlags = controller->getNewFlags();
if(capParams.board != chAruco) {
globalData->totalAvgErr =
cv::calibrateCamera(globalData->objectPoints, globalData->imagePoints,
globalData->imageSize, globalData->cameraMatrix,
globalData->distCoeffs, cv::noArray(), cv::noArray(),
globalData->stdDeviations, cv::noArray(), globalData->perViewErrors,
calibrationFlags, solverTermCrit);
}
else {
#ifdef HAVE_OPENCV_ARUCO
cv::Ptr<cv::aruco::Dictionary> dictionary =
cv::aruco::getPredefinedDictionary(cv::aruco::PREDEFINED_DICTIONARY_NAME(capParams.charucoDictName));
cv::Ptr<cv::aruco::CharucoBoard> charucoboard =
cv::aruco::CharucoBoard::create(capParams.boardSize.width, capParams.boardSize.height,
capParams.charucoSquareLenght, capParams.charucoMarkerSize, dictionary);
globalData->totalAvgErr =
cv::aruco::calibrateCameraCharuco(globalData->allCharucoCorners, globalData->allCharucoIds,
charucoboard, globalData->imageSize,
globalData->cameraMatrix, globalData->distCoeffs,
cv::noArray(), cv::noArray(), globalData->stdDeviations, cv::noArray(),
globalData->perViewErrors, calibrationFlags, solverTermCrit);
#endif
}
dataController->updateUndistortMap();
dataController->printParametersToConsole(std::cout);
controller->updateState();
for(int j = 0; j < capParams.calibrationStep; j++)
dataController->filterFrames();
static_cast<ShowProcessor*>(showProcessor.get())->updateBoardsView();
}
else if (exitStatus == DeleteLastFrame) {
deleteButton(0, &dataController);
static_cast<ShowProcessor*>(showProcessor.get())->updateBoardsView();
}
else if (exitStatus == DeleteAllFrames) {
deleteAllButton(0, &dataController);
static_cast<ShowProcessor*>(showProcessor.get())->updateBoardsView();
}
else if (exitStatus == SaveCurrentData) {
saveCurrentParamsButton(0, &dataController);
}
else if (exitStatus == SwitchUndistort)
static_cast<ShowProcessor*>(showProcessor.get())->switchUndistort();
else if (exitStatus == SwitchVisualisation)
static_cast<ShowProcessor*>(showProcessor.get())->switchVisualizationMode();
for (std::vector<cv::Ptr<FrameProcessor> >::iterator it = processors.begin(); it != processors.end(); ++it)
(*it)->resetState();
}
}
catch (const std::runtime_error& exp) {
std::cout << exp.what() << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright © 2017 Dmitriy Khaustov
//
// 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.
//
// Author: Dmitriy Khaustov aka xDimon
// Contacts: khaustov.dm@gmail.com
// File created on: 2017.03.09
// ConnectionManager.cpp
#include <cstring>
#include "ConnectionManager.hpp"
#include "../thread/ThreadPool.hpp"
#include "../utils/Daemon.hpp"
#include "../thread/RollbackStackAndRestoreContext.hpp"
#include "../thread/TaskManager.hpp"
ConnectionManager::ConnectionManager()
: _log("ConnectionManager")
{
_epfd = epoll_create(poolSize);
memset(_epev, 0, sizeof(_epev));
}
ConnectionManager::~ConnectionManager()
{
std::lock_guard<std::recursive_mutex> guard(_mutex);
std::vector<std::shared_ptr<Connection>> connections;
for (auto& i : _allConnections)
{
connections.emplace_back(i.second);
}
for (auto& connection : connections)
{
remove(connection);
}
close(_epfd);
_epfd = -1;
}
/// Зарегистрировать соединение
void ConnectionManager::add(const std::shared_ptr<Connection>& connection)
{
std::lock_guard<std::recursive_mutex> guard(getInstance()._mutex);
if (getInstance()._allConnections.find(connection.get()) != getInstance()._allConnections.end())
{
getInstance()._log.warn("%s already registered in manager", connection->name().c_str());
return;
}
getInstance()._allConnections.emplace(connection.get(), connection);
getInstance()._log.debug("%s registered in manager", connection->name().c_str());
epoll_event ev{};
connection->watch(ev);
// Включаем наблюдение
if (epoll_ctl(getInstance()._epfd, EPOLL_CTL_ADD, connection->fd(), &ev) == -1)
{
getInstance()._log.warn("Fail add %s for watching (error: '%s')", connection->name().c_str(), strerror(errno));
}
else
{
getInstance()._log.trace("Add %s for watching", connection->name().c_str());
}
}
/// Удалить регистрацию соединения
bool ConnectionManager::remove(const std::shared_ptr<Connection>& connection)
{
if (!connection)
{
return false;
}
// Удаляем из очереди событий
if (epoll_ctl(getInstance()._epfd, EPOLL_CTL_DEL, connection->fd(), nullptr) == -1)
{
getInstance()._log.warn("Fail remove %s from watching (error: '%s')", connection->name().c_str(), strerror(errno));
}
else
{
getInstance()._log.trace("Remove %s from watching", connection->name().c_str());
}
std::lock_guard<std::recursive_mutex> guard(getInstance()._mutex);
getInstance()._allConnections.erase(connection.get());
getInstance()._readyConnections.erase(connection);
getInstance()._capturedConnections.erase(connection);
getInstance()._log.debug("%s unregistered from manager", connection->name().c_str());
return true;
}
uint32_t ConnectionManager::rotateEvents(const std::shared_ptr<Connection>& connection)
{
std::lock_guard<std::recursive_mutex> guard(getInstance()._mutex);
uint32_t events = connection->rotateEvents();
return events;
}
void ConnectionManager::watch(const std::shared_ptr<Connection>& connection)
{
// Для известных соенинений проверяем состояние захваченности
std::lock_guard<std::recursive_mutex> guard(getInstance()._mutex);
// Те, что в обработке, не трогаем
if (connection->isCaptured())
{
// _log.trace("Skip watch for %s because already captured", connection->name().c_str());
return;
}
epoll_event ev{};
connection->watch(ev);
// Включаем наблюдение
if (epoll_ctl(getInstance()._epfd, EPOLL_CTL_MOD, connection->fd(), &ev) == -1)
{
getInstance()._log.warn("Fail modify watching on %s (error: '%s')", connection->name().c_str(), strerror(errno));
}
else
{
getInstance()._log.trace("Modify watching on %s", connection->name().c_str());
}
}
/// Ожидать события на соединениях
void ConnectionManager::wait()
{
// Если набор готовых соединений не пустой, то выходим
if (!_readyConnections.empty())
{
return;
}
_mutex.unlock();
_epool_mutex.lock();
int n = 0;
while ([&](){std::lock_guard<std::recursive_mutex> lockGuard(_mutex); return _readyConnections.empty();}())
{
if ([&](){std::lock_guard<std::recursive_mutex> lockGuard(_mutex); return _allConnections.empty();}())
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
break;
}
n = epoll_wait(_epfd, _epev, poolSize, 50);
if (n < 0)
{
if (errno != EINTR)
{
_log.warn("Error waiting events of connections: fail epoll_wait (%s)", strerror(errno));
break;
}
continue;
}
if (n > 0)
{
_log.trace("Catch events on %d connection(s)", n);
break;
}
if (Daemon::shutingdown())
{
// Закрываем оставшееся
_epool_mutex.unlock();
_mutex.lock();
if (_allConnections.empty())
{
_log.debug("Interrupt waiting");
return;
}
std::vector<std::shared_ptr<Connection>> connections;
for (auto& i : _allConnections)
{
connections.emplace_back(i.second);
}
for (auto& connection : connections)
{
remove(connection);
}
_mutex.unlock();
_epool_mutex.lock();
}
}
_mutex.lock();
// Перебираем полученые события
for (int i = 0; i < n; i++)
{
// Игнорируем незарегистрированные соединения
auto it = _allConnections.find(static_cast<const Connection *>(_epev[i].data.ptr));
if (it == _allConnections.end())
{
_log.trace("Skip catching of unregistered Connection %p", _epev[i].data.ptr);
continue;
}
auto connection = it->second;
uint32_t fdEvent = _epev[i].events;
uint32_t events = 0;
if (fdEvent & (EPOLLIN | EPOLLRDNORM))
{
events |= static_cast<uint32_t>(ConnectionEvent::READ);
}
if (fdEvent & (EPOLLOUT | EPOLLWRNORM))
{
events |= static_cast<uint32_t>(ConnectionEvent::WRITE);
}
if (fdEvent & EPOLLHUP)
{
events |= static_cast<uint32_t>(ConnectionEvent::HUP);
}
if (fdEvent & EPOLLRDHUP)
{
events |= static_cast<uint32_t>(ConnectionEvent::HALFHUP);
}
if (fdEvent & EPOLLERR)
{
events |= static_cast<uint32_t>(ConnectionEvent::ERROR);
}
_log.trace("Catch events `%s` (%04x) on %s", ConnectionEvent::code(events).c_str(), fdEvent, connection->name().c_str());
connection->appendEvents(events);
// Если не в списке захваченых...
if (_capturedConnections.find(connection) == _capturedConnections.end())
{
_log.trace("Insert %s into ready connection list and will be processed now (by events)", connection->name().c_str());
// ...добавляем в список готовых
_readyConnections.insert(connection);
}
}
_epool_mutex.unlock();
}
/// Зарегистрировать таймаут
void ConnectionManager::timeout(const std::shared_ptr<Connection>& connection)
{
auto& instance = getInstance();
std::lock_guard<std::recursive_mutex> lockGuard(instance._mutex);
// Игнорируем незарегистрированные соединения
auto it = instance._allConnections.find(connection.get());
if (it == instance._allConnections.end())
{
instance._log.trace("Skip timeout adding for noregistered Connection %p", connection.get());
return;
}
connection->appendEvents(static_cast<uint32_t>(ConnectionEvent::TIMEOUT));
instance._log.trace("Catch event `T` on %s", connection->name().c_str());
// Если не в списке захваченых...
if (instance._capturedConnections.find(connection) == instance._capturedConnections.end())
{
instance._log.trace("Insert %s into ready connection list and will be processed now (by timeout)", connection->name().c_str());
// ...добавляем в список готовых
instance._readyConnections.insert(connection);
}
}
/// Захватить соединение
std::shared_ptr<Connection> ConnectionManager::capture()
{
std::lock_guard<std::recursive_mutex> lockGuard(_mutex);
// Если нет готовых...
while (_readyConnections.empty())
{
// то выходим при остановке сервера
if (Daemon::shutingdown() && _allConnections.empty())
{
return nullptr;
}
_log.trace("Not found ready connection");
// а в штатном режиме ожидаем появления готового соединения
wait();
}
_log.trace("Found ready connection");
if (_readyConnections.empty())
{
return nullptr;
}
// Берем соединение из набора готовых к обработке
auto it = _readyConnections.begin();
auto connection = *it;
// Перемещаем соединение из набора готовых к обработке в набор захваченных
_readyConnections.erase(it);
_capturedConnections.insert(connection);
_log.trace("Capture %s", connection->name().c_str());
connection->setCaptured();
return std::move(connection);
}
/// Освободить соединение
void ConnectionManager::release(const std::shared_ptr<Connection>& connection)
{
std::lock_guard<std::recursive_mutex> guard(_mutex);
_log.trace("Release %s", connection->name().c_str());
_capturedConnections.erase(connection);
connection->setReleased();
if (!connection->isClosed())
{
watch(connection);
}
}
/// Обработка событий
void ConnectionManager::dispatch()
{
try
{
for (;;)
{
std::shared_ptr<Connection> connection = getInstance().capture();
if (!connection)
{
break;
}
getInstance()._log.debug("Enqueue %s for '%s' events processing", connection->name().c_str(), ConnectionEvent::code(connection->events()).c_str());
TaskManager::enqueue(
[wp = std::weak_ptr<Connection>(connection)]
{
auto connection = wp.lock();
if (!connection)
{
getInstance()._log.trace("Connection death");
return;
}
getInstance()._log.trace("Begin processing on %s", connection->name().c_str());
bool status;
try
{
status = connection->processing();
}
catch (const RollbackStackAndRestoreContext& exception)
{
getInstance().release(connection);
throw;
}
catch (const std::exception& exception)
{
status = false;
getInstance()._log.warn("Uncatched exception at processing on %s: %s", connection->name().c_str(), exception.what());
}
getInstance().release(connection);
getInstance()._log.trace("End processing on %s: %s", connection->name().c_str(), status ? "success" : "fail");
}
);
}
}
catch (const std::exception& exception)
{
throw;
}
}
<commit_msg>Cleanup ConnectionManager for Coroutines<commit_after>// Copyright © 2017 Dmitriy Khaustov
//
// 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.
//
// Author: Dmitriy Khaustov aka xDimon
// Contacts: khaustov.dm@gmail.com
// File created on: 2017.03.09
// ConnectionManager.cpp
#include <cstring>
#include "ConnectionManager.hpp"
#include "../thread/ThreadPool.hpp"
#include "../utils/Daemon.hpp"
#include "../thread/RollbackStackAndRestoreContext.hpp"
#include "../thread/TaskManager.hpp"
ConnectionManager::ConnectionManager()
: _log("ConnectionManager")
{
_epfd = epoll_create(poolSize);
memset(_epev, 0, sizeof(_epev));
}
ConnectionManager::~ConnectionManager()
{
std::lock_guard<std::recursive_mutex> guard(_mutex);
std::vector<std::shared_ptr<Connection>> connections;
for (auto& i : _allConnections)
{
connections.emplace_back(i.second);
}
for (auto& connection : connections)
{
remove(connection);
}
close(_epfd);
_epfd = -1;
}
/// Зарегистрировать соединение
void ConnectionManager::add(const std::shared_ptr<Connection>& connection)
{
std::lock_guard<std::recursive_mutex> guard(getInstance()._mutex);
if (getInstance()._allConnections.find(connection.get()) != getInstance()._allConnections.end())
{
getInstance()._log.warn("%s already registered in manager", connection->name().c_str());
return;
}
getInstance()._allConnections.emplace(connection.get(), connection);
getInstance()._log.debug("%s registered in manager", connection->name().c_str());
epoll_event ev{};
connection->watch(ev);
// Включаем наблюдение
if (epoll_ctl(getInstance()._epfd, EPOLL_CTL_ADD, connection->fd(), &ev) == -1)
{
getInstance()._log.warn("Fail add %s for watching (error: '%s')", connection->name().c_str(), strerror(errno));
}
else
{
getInstance()._log.trace("Add %s for watching", connection->name().c_str());
}
}
/// Удалить регистрацию соединения
bool ConnectionManager::remove(const std::shared_ptr<Connection>& connection)
{
if (!connection)
{
return false;
}
// Удаляем из очереди событий
if (epoll_ctl(getInstance()._epfd, EPOLL_CTL_DEL, connection->fd(), nullptr) == -1)
{
getInstance()._log.warn("Fail remove %s from watching (error: '%s')", connection->name().c_str(), strerror(errno));
}
else
{
getInstance()._log.trace("Remove %s from watching", connection->name().c_str());
}
std::lock_guard<std::recursive_mutex> guard(getInstance()._mutex);
getInstance()._allConnections.erase(connection.get());
getInstance()._readyConnections.erase(connection);
getInstance()._capturedConnections.erase(connection);
getInstance()._log.debug("%s unregistered from manager", connection->name().c_str());
return true;
}
uint32_t ConnectionManager::rotateEvents(const std::shared_ptr<Connection>& connection)
{
std::lock_guard<std::recursive_mutex> guard(getInstance()._mutex);
uint32_t events = connection->rotateEvents();
return events;
}
void ConnectionManager::watch(const std::shared_ptr<Connection>& connection)
{
// Для известных соенинений проверяем состояние захваченности
std::lock_guard<std::recursive_mutex> guard(getInstance()._mutex);
// Те, что в обработке, не трогаем
if (connection->isCaptured())
{
// _log.trace("Skip watch for %s because already captured", connection->name().c_str());
return;
}
epoll_event ev{};
connection->watch(ev);
// Включаем наблюдение
if (epoll_ctl(getInstance()._epfd, EPOLL_CTL_MOD, connection->fd(), &ev) == -1)
{
getInstance()._log.warn("Fail modify watching on %s (error: '%s')", connection->name().c_str(), strerror(errno));
}
else
{
getInstance()._log.trace("Modify watching on %s", connection->name().c_str());
}
}
/// Ожидать события на соединениях
void ConnectionManager::wait()
{
// Если набор готовых соединений не пустой, то выходим
if (!_readyConnections.empty())
{
return;
}
_mutex.unlock();
_epool_mutex.lock();
int n = 0;
while ([&](){std::lock_guard<std::recursive_mutex> lockGuard(_mutex); return _readyConnections.empty();}())
{
if ([&](){std::lock_guard<std::recursive_mutex> lockGuard(_mutex); return _allConnections.empty();}())
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
break;
}
n = epoll_wait(_epfd, _epev, poolSize, 50);
if (n < 0)
{
if (errno != EINTR)
{
_log.warn("Error waiting events of connections: fail epoll_wait (%s)", strerror(errno));
break;
}
continue;
}
if (n > 0)
{
_log.trace("Catch events on %d connection(s)", n);
break;
}
if (Daemon::shutingdown())
{
// Закрываем оставшееся
_epool_mutex.unlock();
_mutex.lock();
if (_allConnections.empty())
{
_log.debug("Interrupt waiting");
return;
}
std::vector<std::shared_ptr<Connection>> connections;
for (auto& i : _allConnections)
{
connections.emplace_back(i.second);
}
for (auto& connection : connections)
{
remove(connection);
}
_mutex.unlock();
_epool_mutex.lock();
}
}
_mutex.lock();
// Перебираем полученые события
for (int i = 0; i < n; i++)
{
// Игнорируем незарегистрированные соединения
auto it = _allConnections.find(static_cast<const Connection *>(_epev[i].data.ptr));
if (it == _allConnections.end())
{
_log.trace("Skip catching of unregistered Connection %p", _epev[i].data.ptr);
continue;
}
auto connection = it->second;
uint32_t fdEvent = _epev[i].events;
uint32_t events = 0;
if (fdEvent & (EPOLLIN | EPOLLRDNORM))
{
events |= static_cast<uint32_t>(ConnectionEvent::READ);
}
if (fdEvent & (EPOLLOUT | EPOLLWRNORM))
{
events |= static_cast<uint32_t>(ConnectionEvent::WRITE);
}
if (fdEvent & EPOLLHUP)
{
events |= static_cast<uint32_t>(ConnectionEvent::HUP);
}
if (fdEvent & EPOLLRDHUP)
{
events |= static_cast<uint32_t>(ConnectionEvent::HALFHUP);
}
if (fdEvent & EPOLLERR)
{
events |= static_cast<uint32_t>(ConnectionEvent::ERROR);
}
_log.trace("Catch events `%s` (%04x) on %s", ConnectionEvent::code(events).c_str(), fdEvent, connection->name().c_str());
connection->appendEvents(events);
// Если не в списке захваченых...
if (_capturedConnections.find(connection) == _capturedConnections.end())
{
_log.trace("Insert %s into ready connection list and will be processed now (by events)", connection->name().c_str());
// ...добавляем в список готовых
_readyConnections.insert(connection);
}
}
_epool_mutex.unlock();
}
/// Зарегистрировать таймаут
void ConnectionManager::timeout(const std::shared_ptr<Connection>& connection)
{
auto& instance = getInstance();
std::lock_guard<std::recursive_mutex> lockGuard(instance._mutex);
// Игнорируем незарегистрированные соединения
auto it = instance._allConnections.find(connection.get());
if (it == instance._allConnections.end())
{
instance._log.trace("Skip timeout adding for noregistered Connection %p", connection.get());
return;
}
connection->appendEvents(static_cast<uint32_t>(ConnectionEvent::TIMEOUT));
instance._log.trace("Catch event `T` on %s", connection->name().c_str());
// Если не в списке захваченых...
if (instance._capturedConnections.find(connection) == instance._capturedConnections.end())
{
instance._log.trace("Insert %s into ready connection list and will be processed now (by timeout)", connection->name().c_str());
// ...добавляем в список готовых
instance._readyConnections.insert(connection);
}
}
/// Захватить соединение
std::shared_ptr<Connection> ConnectionManager::capture()
{
std::lock_guard<std::recursive_mutex> lockGuard(_mutex);
// Если нет готовых...
while (_readyConnections.empty())
{
// то выходим при остановке сервера
if (Daemon::shutingdown() && _allConnections.empty())
{
return nullptr;
}
_log.trace("Not found ready connection");
// а в штатном режиме ожидаем появления готового соединения
wait();
}
_log.trace("Found ready connection");
if (_readyConnections.empty())
{
return nullptr;
}
// Берем соединение из набора готовых к обработке
auto it = _readyConnections.begin();
auto connection = *it;
// Перемещаем соединение из набора готовых к обработке в набор захваченных
_readyConnections.erase(it);
_capturedConnections.insert(connection);
_log.trace("Capture %s", connection->name().c_str());
connection->setCaptured();
return std::move(connection);
}
/// Освободить соединение
void ConnectionManager::release(const std::shared_ptr<Connection>& connection)
{
std::lock_guard<std::recursive_mutex> guard(_mutex);
_log.trace("Release %s", connection->name().c_str());
_capturedConnections.erase(connection);
connection->setReleased();
if (!connection->isClosed())
{
watch(connection);
}
}
/// Обработка событий
void ConnectionManager::dispatch()
{
for (;;)
{
std::shared_ptr<Connection> connection = getInstance().capture();
if (!connection)
{
break;
}
getInstance()._log.debug("Enqueue %s for '%s' events processing", connection->name().c_str(), ConnectionEvent::code(connection->events()).c_str());
TaskManager::enqueue(
[wp = std::weak_ptr<Connection>(connection)]
{
auto connection = wp.lock();
if (!connection)
{
getInstance()._log.trace("Connection death");
return;
}
getInstance()._log.trace("Begin processing on %s", connection->name().c_str());
bool status;
try
{
status = connection->processing();
}
catch (const RollbackStackAndRestoreContext& exception)
{
getInstance().release(connection);
throw;
}
catch (const std::exception& exception)
{
status = false;
getInstance()._log.warn("Uncatched exception at processing on %s: %s", connection->name().c_str(), exception.what());
}
getInstance().release(connection);
getInstance()._log.trace("End processing on %s: %s", connection->name().c_str(), status ? "success" : "fail");
}
);
}
}
<|endoftext|> |
<commit_before>#include "Toolchain.h"
#include "dtasm.h"
#include "dtemu.h"
#include <iostream>
#include <cstdlib>
#ifdef WIN32
#include <io.h>
#define mktemp _mktemp
#endif
void DCPUToolchain_CycleHook(vm_t* vm, uint16_t pos, void* ud)
{
}
void DCPUToolchain_WriteHook(vm_t* vm, uint16_t pos, void* ud)
{
DCPUToolchain* t = static_cast<DCPUToolchain*>(ud);
DebuggingMessage m;
MemoryMessage payload;
payload.pos = pos;
payload.value = vm->ram[pos];
m.type = MemoryType;
m.value = (MessageValue&) payload;
t->debuggingSession->AddMessage(m);
}
void DCPUToolchain_InterruptHook(vm_t* vm, uint16_t pos, void* ud)
{
DCPUToolchain* t = static_cast<DCPUToolchain*>(ud);
}
void DCPUToolchain_HardwareHook(vm_t* vm, uint16_t pos, void* ud)
{
DCPUToolchain* t = static_cast<DCPUToolchain*>(ud);
}
void DCPUToolchain_60HZHook(vm_t* vm, uint16_t pos, void* ud)
{
}
DCPUToolchainASM::DCPUToolchainASM()
{
}
std::string DCPUToolchainASM::GetName()
{
return "DCPU Toolchain Assembly";
}
std::string DCPUToolchainASM::GetDescription()
{
return "The DCPU Toolchain Assembly language";
}
std::list<std::string> DCPUToolchainASM::GetExtensions()
{
std::list<std::string> list;
list.push_back("dasm");
list.push_back("dasm16");
list.push_back("asm");
return list;
}
std::string DCPUToolchainASM::GetDefaultFileName()
{
return "untitled.dasm16";
}
void DCPUToolchainASM::Build(std::string filename, std::string outputDir, BuildAPI &api)
{
const char* cf = filename.c_str();
const char* t_ob = "dtcpu.XXXXXX";
const char* t_os = "dtsym.XXXXXX";
char* ob = (char*)malloc(strlen(t_ob) + 1);
char* os = (char*)malloc(strlen(t_os) + 1);
memcpy(ob, t_ob, strlen(t_ob) + 1);
memcpy(os, t_os, strlen(t_os) + 1);
// FIXME: Create a function in osutil for creating a temporary filename.
// FIXME: Create a global "temporary file" manager that cleans up files
// that were created during builds when the IDE exits.
mktemp(ob);
mktemp(os);
if (perform_assemble(cf, ob, os))
{
api.AddOutputFile(ob);
unlink(os);
std::cout << "Assembling success!" << std::endl;
}
else
{
unlink(ob);
unlink(os);
std::cout << "Assembling failed!" << std::endl;
}
api.End();
free(ob);
free(os);
}
CodeSyntax DCPUToolchainASM::GetCodeSyntax()
{
return DCPUAssembly;
}
std::list<std::string> DCPUToolchain::GetAuthors()
{
std::list<std::string> authors;
authors.push_back(std::string("The DCPU Toolchain Team"));
return authors;
}
std::string DCPUToolchain::GetLicense()
{
return std::string("MIT");
}
std::string DCPUToolchain::GetName()
{
return "DCPU-16 Toolchain";
}
std::string DCPUToolchain::GetDescription()
{
return "The DCPU Toolchain.";
}
std::list<Language*> DCPUToolchain::GetLanguages()
{
std::list<Language*> list;
DCPUToolchainASM* dasm = new DCPUToolchainASM();
list.insert(list.end(), dasm);
return list;
}
void DCPUToolchain::Start(std::string path, DebuggingSession* session)
{
// Tell the emulator to start.
debuggingSession = session;
paused = false;
start_emulation(
path.c_str(),
&DCPUToolchain_CycleHook,
&DCPUToolchain_WriteHook,
&DCPUToolchain_InterruptHook,
&DCPUToolchain_HardwareHook,
&DCPUToolchain_60HZHook,
static_cast<void*>(this));
}
void DCPUToolchain::AddStatusMessage(vm_t* vm)
{
DebuggingMessage m;
StatusMessage payload;
if(vm == 0)
return;
for(int i = 0; i < 8; i++)
payload.registers[i] = vm->registers[i];
payload.pc = vm->pc;
payload.sp = vm->sp;
payload.ia = vm->ia;
payload.ex = vm->ex;
m.type = StatusType;
m.value = (MessageValue&) payload;
debuggingSession->AddMessage(m);
}
void DCPUToolchain::SendStatus()
{
vm_t* vm = get_vm();
AddStatusMessage(vm);
}
void DCPUToolchain::Cycle()
{
if(!paused)
{
cycle_emulation();
}
}
void DCPUToolchain::Step()
{
cycle_emulation();
}
void DCPUToolchain::Stop(DebuggingSession* session)
{
stop_emulation();
}
void DCPUToolchain::Pause(DebuggingSession* session)
{
paused = true;
}
<commit_msg>Included unistd.h on non-WIN platforms<commit_after>#include "Toolchain.h"
#include "dtasm.h"
#include "dtemu.h"
#include <iostream>
#include <cstdlib>
#ifdef WIN32
#include <io.h>
#define mktemp _mktemp
#else
#include <unistd.h>
#endif
void DCPUToolchain_CycleHook(vm_t* vm, uint16_t pos, void* ud)
{
}
void DCPUToolchain_WriteHook(vm_t* vm, uint16_t pos, void* ud)
{
DCPUToolchain* t = static_cast<DCPUToolchain*>(ud);
DebuggingMessage m;
MemoryMessage payload;
payload.pos = pos;
payload.value = vm->ram[pos];
m.type = MemoryType;
m.value = (MessageValue&) payload;
t->debuggingSession->AddMessage(m);
}
void DCPUToolchain_InterruptHook(vm_t* vm, uint16_t pos, void* ud)
{
DCPUToolchain* t = static_cast<DCPUToolchain*>(ud);
}
void DCPUToolchain_HardwareHook(vm_t* vm, uint16_t pos, void* ud)
{
DCPUToolchain* t = static_cast<DCPUToolchain*>(ud);
}
void DCPUToolchain_60HZHook(vm_t* vm, uint16_t pos, void* ud)
{
}
DCPUToolchainASM::DCPUToolchainASM()
{
}
std::string DCPUToolchainASM::GetName()
{
return "DCPU Toolchain Assembly";
}
std::string DCPUToolchainASM::GetDescription()
{
return "The DCPU Toolchain Assembly language";
}
std::list<std::string> DCPUToolchainASM::GetExtensions()
{
std::list<std::string> list;
list.push_back("dasm");
list.push_back("dasm16");
list.push_back("asm");
return list;
}
std::string DCPUToolchainASM::GetDefaultFileName()
{
return "untitled.dasm16";
}
void DCPUToolchainASM::Build(std::string filename, std::string outputDir, BuildAPI &api)
{
const char* cf = filename.c_str();
const char* t_ob = "dtcpu.XXXXXX";
const char* t_os = "dtsym.XXXXXX";
char* ob = (char*)malloc(strlen(t_ob) + 1);
char* os = (char*)malloc(strlen(t_os) + 1);
memcpy(ob, t_ob, strlen(t_ob) + 1);
memcpy(os, t_os, strlen(t_os) + 1);
// FIXME: Create a function in osutil for creating a temporary filename.
// FIXME: Create a global "temporary file" manager that cleans up files
// that were created during builds when the IDE exits.
mktemp(ob);
mktemp(os);
if (perform_assemble(cf, ob, os))
{
api.AddOutputFile(ob);
unlink(os);
std::cout << "Assembling success!" << std::endl;
}
else
{
unlink(ob);
unlink(os);
std::cout << "Assembling failed!" << std::endl;
}
api.End();
free(ob);
free(os);
}
CodeSyntax DCPUToolchainASM::GetCodeSyntax()
{
return DCPUAssembly;
}
std::list<std::string> DCPUToolchain::GetAuthors()
{
std::list<std::string> authors;
authors.push_back(std::string("The DCPU Toolchain Team"));
return authors;
}
std::string DCPUToolchain::GetLicense()
{
return std::string("MIT");
}
std::string DCPUToolchain::GetName()
{
return "DCPU-16 Toolchain";
}
std::string DCPUToolchain::GetDescription()
{
return "The DCPU Toolchain.";
}
std::list<Language*> DCPUToolchain::GetLanguages()
{
std::list<Language*> list;
DCPUToolchainASM* dasm = new DCPUToolchainASM();
list.insert(list.end(), dasm);
return list;
}
void DCPUToolchain::Start(std::string path, DebuggingSession* session)
{
// Tell the emulator to start.
debuggingSession = session;
paused = false;
start_emulation(
path.c_str(),
&DCPUToolchain_CycleHook,
&DCPUToolchain_WriteHook,
&DCPUToolchain_InterruptHook,
&DCPUToolchain_HardwareHook,
&DCPUToolchain_60HZHook,
static_cast<void*>(this));
}
void DCPUToolchain::AddStatusMessage(vm_t* vm)
{
DebuggingMessage m;
StatusMessage payload;
if(vm == 0)
return;
for(int i = 0; i < 8; i++)
payload.registers[i] = vm->registers[i];
payload.pc = vm->pc;
payload.sp = vm->sp;
payload.ia = vm->ia;
payload.ex = vm->ex;
m.type = StatusType;
m.value = (MessageValue&) payload;
debuggingSession->AddMessage(m);
}
void DCPUToolchain::SendStatus()
{
vm_t* vm = get_vm();
AddStatusMessage(vm);
}
void DCPUToolchain::Cycle()
{
if(!paused)
{
cycle_emulation();
}
}
void DCPUToolchain::Step()
{
cycle_emulation();
}
void DCPUToolchain::Stop(DebuggingSession* session)
{
stop_emulation();
}
void DCPUToolchain::Pause(DebuggingSession* session)
{
paused = true;
}
<|endoftext|> |
<commit_before>#ifndef ITER_SLIDING_WINDOW_HPP_
#define ITER_SLIDING_WINDOW_HPP_
#include "iterbase.hpp"
#include <deque>
#include <utility>
#include <iterator>
namespace iter {
template <typename Container>
class SlidingWindow;
template <typename Container>
SlidingWindow<Container> sliding_window(Container&&, std::size_t);
template <typename T>
SlidingWindow<std::initializer_list<T>> sliding_window(
std::initializer_list<T>, std::size_t);
template <typename Container>
class SlidingWindow {
private: Container container;
std::size_t window_size;
friend SlidingWindow sliding_window<Container>(
Container&&, std::size_t);
template <typename T>
friend SlidingWindow<std::initializer_list<T>> sliding_window(
std::initializer_list<T>, std::size_t);
SlidingWindow(Container container, std::size_t win_sz)
: container(std::forward<Container>(container)),
window_size{win_sz}
{ }
public:
class Iterator {
private:
// TODO move defs outside and subclass std::iterator
using OpDerefElemType = collection_item_type<Container>;
using DerefVec = std::deque<OpDerefElemType>;
iterator_type<Container> sub_iter;
DerefVec window;
public:
Iterator(const iterator_type<Container>& in_iter,
const iterator_type<Container>& in_end,
std::size_t window_sz)
: sub_iter(in_iter)
{
std::size_t i{0};
while (i < window_sz && this->sub_iter != in_end) {
this->window.push_back(*this->sub_iter);
++i;
if (i != window_sz) ++this->sub_iter;
}
}
bool operator!=(const Iterator& other) const {
return this->sub_iter != other.sub_iter;
}
DerefVec& operator*() {
return this->window;
}
Iterator& operator++() {
++this->sub_iter;
this->window.pop_front();
this->window.push_back(*this->sub_iter);
return *this;
}
};
Iterator begin() {
return {std::begin(container),
std::end(container),
window_size};
}
Iterator end() {
return {std::end(container),
std::end(container),
window_size};
}
};
template <typename Container>
SlidingWindow<Container> sliding_window(
Container&& container, std::size_t window_size) {
return {std::forward<Container>(container), window_size};
}
template <typename T>
SlidingWindow<std::initializer_list<T>> sliding_window(
std::initializer_list<T> il, std::size_t window_size) {
return {il, window_size};
}
}
#endif
<commit_msg>sliding_window iter inherits from std::iterator<commit_after>#ifndef ITER_SLIDING_WINDOW_HPP_
#define ITER_SLIDING_WINDOW_HPP_
#include "iterbase.hpp"
#include <deque>
#include <utility>
#include <iterator>
namespace iter {
template <typename Container>
class SlidingWindow;
template <typename Container>
SlidingWindow<Container> sliding_window(Container&&, std::size_t);
template <typename T>
SlidingWindow<std::initializer_list<T>> sliding_window(
std::initializer_list<T>, std::size_t);
template <typename Container>
class SlidingWindow {
private: Container container;
std::size_t window_size;
friend SlidingWindow sliding_window<Container>(
Container&&, std::size_t);
template <typename T>
friend SlidingWindow<std::initializer_list<T>> sliding_window(
std::initializer_list<T>, std::size_t);
SlidingWindow(Container container, std::size_t win_sz)
: container(std::forward<Container>(container)),
window_size{win_sz}
{ }
using DerefVec = std::deque<collection_item_type<Container>>;
public:
class Iterator
: public std::iterator<std::input_iterator_tag, DerefVec>
{
private:
iterator_type<Container> sub_iter;
DerefVec window;
public:
Iterator(const iterator_type<Container>& in_iter,
const iterator_type<Container>& in_end,
std::size_t window_sz)
: sub_iter(in_iter)
{
std::size_t i{0};
while (i < window_sz && this->sub_iter != in_end) {
this->window.push_back(*this->sub_iter);
++i;
if (i != window_sz) ++this->sub_iter;
}
}
bool operator!=(const Iterator& other) const {
return this->sub_iter != other.sub_iter;
}
DerefVec& operator*() {
return this->window;
}
Iterator& operator++() {
++this->sub_iter;
this->window.pop_front();
this->window.push_back(*this->sub_iter);
return *this;
}
};
Iterator begin() {
return {std::begin(container),
std::end(container),
window_size};
}
Iterator end() {
return {std::end(container),
std::end(container),
window_size};
}
};
template <typename Container>
SlidingWindow<Container> sliding_window(
Container&& container, std::size_t window_size) {
return {std::forward<Container>(container), window_size};
}
template <typename T>
SlidingWindow<std::initializer_list<T>> sliding_window(
std::initializer_list<T> il, std::size_t window_size) {
return {il, window_size};
}
}
#endif
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2008 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/**
\file TextfileOut.cpp
\author Jens Krueger
SCI Institute
University of Utah
\date August 2008
*/
#include <fstream>
#include <stdarg.h>
#ifdef WIN32
#include <windows.h>
#endif
#include "TextfileOut.h"
#include <ctime>
using namespace std;
TextfileOut::TextfileOut(std::string strFilename) :
m_strFilename(strFilename)
{
this->printf("MESSAGE (TextfileOut::TextfileOut:): Starting up");
}
TextfileOut::~TextfileOut() {
this->printf("MESSAGE (TextfileOut::~TextfileOut:): Shutting down\n\n\n");
}
void TextfileOut::printf(const char* format, ...) const
{
if (!m_bShowOther) return;
char buff[16384];
char date [10];
char time [10];
va_list args;
va_start(args, format);
#ifdef WIN32
_vsnprintf_s( buff, 16384, sizeof(buff), format, args);
_strdate_s(date,10);
_strtime_s(time,10);
#else
vsnprintf( buff, sizeof(buff), format, args);
_strdate(date);
_strtime(time);
#endif
ofstream fs;
fs.open(m_strFilename.c_str(), ios_base::app);
if (fs.fail()) return;
fs << buff << " (" << date << " " << time << ")" << endl;
fs.flush();
fs.close();
}
void TextfileOut::_printf(const char* format, ...) const
{
char buff[16384];
char date [10];
char time [10];
va_list args;
va_start(args, format);
#ifdef WIN32
_vsnprintf_s( buff, 16384, sizeof(buff), format, args);
_strdate_s(date,10);
_strtime_s(time,10);
#else
vsnprintf( buff, sizeof(buff), format, args);
_strdate(date);
_strtime(time);
#endif
ofstream fs;
fs.open(m_strFilename.c_str(), ios_base::app);
if (fs.fail()) return;
fs << buff << " (" << date << " " << time << ")" << endl;
fs.flush();
fs.close();
}
void TextfileOut::Message(const char* source, const char* format, ...) {
if (!m_bShowMessages) return;
char buff[16384];
va_list args;
va_start(args, format);
#ifdef WIN32
_vsnprintf_s( buff, 16384, sizeof(buff), format, args);
#else
vsnprintf( buff, sizeof(buff), format, args);
#endif
this->_printf("MESSAGE (%s): %s",source, buff);
}
void TextfileOut::Warning(const char* source, const char* format, ...) {
if (!m_bShowWarnings) return;
char buff[16384];
va_list args;
va_start(args, format);
#ifdef WIN32
_vsnprintf_s( buff, 16384, sizeof(buff), format, args);
#else
vsnprintf( buff, sizeof(buff), format, args);
#endif
this->_printf("WARNING (%s): %s",source, buff);
}
void TextfileOut::Error(const char* source, const char* format, ...) {
if (!m_bShowErrors) return;
char buff[16384];
va_list args;
va_start(args, format);
#ifdef WIN32
_vsnprintf_s( buff, 16384, sizeof(buff), format, args);
#else
vsnprintf( buff, sizeof(buff), format, args);
#endif
this->_printf("ERROR (%s): %s",source, buff);
}
<commit_msg>Use POSIX date/time access.<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2008 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/**
\file TextfileOut.cpp
\author Jens Krueger
SCI Institute
University of Utah
\date August 2008
*/
#include <fstream>
#include <stdarg.h>
#ifdef WIN32
#include <windows.h>
#endif
#include "TextfileOut.h"
#include <ctime>
using namespace std;
TextfileOut::TextfileOut(std::string strFilename) :
m_strFilename(strFilename)
{
this->printf("MESSAGE (TextfileOut::TextfileOut:): Starting up");
}
TextfileOut::~TextfileOut() {
this->printf("MESSAGE (TextfileOut::~TextfileOut:): Shutting down\n\n\n");
}
void TextfileOut::printf(const char* format, ...) const
{
if (!m_bShowOther) return;
char buff[16384];
va_list args;
va_start(args, format);
#ifdef WIN32
_vsnprintf_s( buff, 16384, sizeof(buff), format, args);
#else
vsnprintf( buff, sizeof(buff), format, args);
#endif
time_t epoch_time;
struct tm now;
char datetime[64];
time(&epoch_time);
localtime_r(&epoch_time, &now);
ofstream fs;
fs.open(m_strFilename.c_str(), ios_base::app);
if (fs.fail()) return;
if(strftime(datetime, 64, "(%F %T)", &now) > 0) {
fs << datetime << " " << buff << std::endl;
} else {
fs << buff << std::endl;
}
fs.flush();
fs.close();
}
void TextfileOut::_printf(const char* format, ...) const
{
char buff[16384];
va_list args;
va_start(args, format);
#ifdef WIN32
_vsnprintf_s( buff, 16384, sizeof(buff), format, args);
#else
vsnprintf( buff, sizeof(buff), format, args);
#endif
time_t epoch_time;
struct tm now;
char datetime[64];
time(&epoch_time);
localtime_r(&epoch_time, &now);
ofstream fs;
fs.open(m_strFilename.c_str(), ios_base::app);
if (fs.fail()) return;
if(strftime(datetime, 64, "(%F %T)", &now) > 0) {
fs << datetime << " " << buff << std::endl;
} else {
fs << buff << std::endl;
}
fs.flush();
fs.close();
}
void TextfileOut::Message(const char* source, const char* format, ...) {
if (!m_bShowMessages) return;
char buff[16384];
va_list args;
va_start(args, format);
#ifdef WIN32
_vsnprintf_s( buff, 16384, sizeof(buff), format, args);
#else
vsnprintf( buff, sizeof(buff), format, args);
#endif
this->_printf("MESSAGE (%s): %s",source, buff);
}
void TextfileOut::Warning(const char* source, const char* format, ...) {
if (!m_bShowWarnings) return;
char buff[16384];
va_list args;
va_start(args, format);
#ifdef WIN32
_vsnprintf_s( buff, 16384, sizeof(buff), format, args);
#else
vsnprintf( buff, sizeof(buff), format, args);
#endif
this->_printf("WARNING (%s): %s",source, buff);
}
void TextfileOut::Error(const char* source, const char* format, ...) {
if (!m_bShowErrors) return;
char buff[16384];
va_list args;
va_start(args, format);
#ifdef WIN32
_vsnprintf_s( buff, 16384, sizeof(buff), format, args);
#else
vsnprintf( buff, sizeof(buff), format, args);
#endif
this->_printf("ERROR (%s): %s",source, buff);
}
<|endoftext|> |
<commit_before>#pragma once
#include "boilerplate.hpp"
struct DiophantineSolution {
int x;
int y;
int dx;
int dy;
};
void assign(Z& a, Z& b, Z aval, Z bval) {
a = aval;
b = bval;
}
/// Solve linear diophantine equation ax + by = c. If there is no solution
/// (iff gcd(a, b) does not divide c), fails. Returns structure containing
/// a solution (x, y), all solutions are (x + t * dx, y + t * dy), for all
/// integers t. a and b must be nonzero.
DiophantineSolution solveLinearDiophantine(Z a, Z b, Z c) {
if(a == 0 || b == 0) fail();
Z A = a;
Z B = b;
// NOTE: the following chunk only if you need negative a,b,c.
Z as = 1;
Z bs = 1;
if(a < 0) {
a = -a;
as = -as;
}
if(b < 0) {
b = -b;
bs = -bs;
}
if(c < 0) {
c = -c;
as = -as;
bs = -bs;
}
Z x = 0, y = 1, lx = 1, ly = 0;
while(b != 0) {
Z q = a / b;
assign(a, b, b, a % b);
assign(x, lx, lx - q * x, x);
assign(y, ly, ly - q * y, y);
}
if(c % a != 0) fail();
Z coef = c / a;
DiophantineSolution ret = {as * coef * lx, bs * coef * ly, B / a, -A / a};
return ret;
}
<commit_msg>Fixed bug in linear diophantine solver.<commit_after>#pragma once
#include "boilerplate.hpp"
struct DiophantineSolution {
Z x;
Z y;
Z dx;
Z dy;
};
void assign(Z& a, Z& b, Z aval, Z bval) {
a = aval;
b = bval;
}
/// Solve linear diophantine equation ax + by = c. If there is no solution
/// (iff gcd(a, b) does not divide c), fails. Returns structure containing
/// a solution (x, y), all solutions are (x + t * dx, y + t * dy), for all
/// integers t. a and b must be nonzero.
DiophantineSolution solveLinearDiophantine(Z a, Z b, Z c) {
if(a == 0 || b == 0) fail();
Z A = a;
Z B = b;
// NOTE: the following chunk only if you need negative a,b,c.
Z as = 1;
Z bs = 1;
if(a < 0) {
a = -a;
as = -as;
}
if(b < 0) {
b = -b;
bs = -bs;
}
if(c < 0) {
c = -c;
as = -as;
bs = -bs;
}
Z x = 0, y = 1, lx = 1, ly = 0;
while(b != 0) {
Z q = a / b;
assign(a, b, b, a % b);
assign(x, lx, lx - q * x, x);
assign(y, ly, ly - q * y, y);
}
if(c % a != 0) fail();
Z coef = c / a;
DiophantineSolution ret = {as * coef * lx, bs * coef * ly, B / a, -A / a};
return ret;
}
<|endoftext|> |
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Rice 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 Rice 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.
*********************************************************************/
/* Author: Ioan Sucan */
#include "ompl/base/Planner.h"
#include "ompl/util/Exception.h"
#include "ompl/base/GoalSampleableRegion.h"
#include "ompl/base/GoalLazySamples.h"
#include <boost/thread.hpp>
#include <utility>
ompl::base::Planner::Planner(const SpaceInformationPtr &si, const std::string &name) :
si_(si), pis_(this), name_(name), type_(PLAN_UNKNOWN), setup_(false), msg_(name)
{
if (!si_)
throw Exception(name_, "Invalid space information instance for planner");
}
ompl::base::PlannerType ompl::base::Planner::getType(void) const
{
return type_;
}
const std::string& ompl::base::Planner::getName(void) const
{
return name_;
}
void ompl::base::Planner::setName(const std::string &name)
{
name_ = name;
}
const ompl::base::SpaceInformationPtr& ompl::base::Planner::getSpaceInformation(void) const
{
return si_;
}
const ompl::base::ProblemDefinitionPtr& ompl::base::Planner::getProblemDefinition(void) const
{
return pdef_;
}
void ompl::base::Planner::setProblemDefinition(const ProblemDefinitionPtr &pdef)
{
pdef_ = pdef;
pis_.update();
}
const ompl::base::PlannerInputStates& ompl::base::Planner::getPlannerInputStates(void) const
{
return pis_;
}
void ompl::base::Planner::setup(void)
{
if (!si_->isSetup())
{
msg_.inform("Space information setup was not yet called. Calling now.");
si_->setup();
}
if (setup_)
msg_.warn("Planner setup called multiple times");
else
setup_ = true;
}
void ompl::base::Planner::checkValidity(void)
{
if (!isSetup())
setup();
pis_.checkValidity();
}
bool ompl::base::Planner::isSetup(void) const
{
return setup_;
}
void ompl::base::Planner::clear(void)
{
pis_.clear();
pis_.update();
}
void ompl::base::Planner::getPlannerData(PlannerData &data) const
{
data.si = si_;
}
namespace ompl
{
// return true if a certain point in time has passed
static bool timePassed(const time::point &endTime)
{
return time::now() > endTime;
}
// return if an externally passed flag is true
static bool evaluateFlag(const bool *flag)
{
return *flag;
}
// periodically evaluate a termination condition and store the result at an indicated location
static void periodicConditionEvaluator(const base::PlannerTerminationCondition &ptc, double checkInterval, bool *flag)
{
time::duration s = time::seconds(checkInterval);
do
{
bool shouldTerminate = ptc();
if (shouldTerminate)
*flag = true;
if (*flag == false)
boost::this_thread::sleep(s);
} while (*flag == false);
}
static bool alwaysTrue(void)
{
return true;
}
}
bool ompl::base::Planner::solve(const PlannerTerminationCondition &ptc, double checkInterval)
{
bool flag = false;
boost::thread condEvaluator(boost::bind(&periodicConditionEvaluator, ptc, checkInterval, &flag));
bool result = solve(boost::bind(&evaluateFlag, &flag));
flag = true;
condEvaluator.interrupt();
condEvaluator.join();
return result;
}
bool ompl::base::Planner::solve(double solveTime)
{
if (solveTime < 1.0)
return solve(boost::bind(&timePassed, time::now() + time::seconds(solveTime)));
else
return solve(boost::bind(&timePassed, time::now() + time::seconds(solveTime)), std::min(solveTime / 100.0, 0.1));
}
void ompl::base::PlannerData::clear(void)
{
stateIndex.clear();
states.clear();
edges.clear();
properties.clear();
si.reset();
}
void ompl::base::PlannerData::recordEdge(const State *s1, const State *s2)
{
if (s1 == NULL || s2 == NULL)
{
const State *s = s1 == NULL ? s2 : s1;
if (s != NULL)
{
std::map<const State*, unsigned int>::iterator it = stateIndex.find(s);
if (it == stateIndex.end())
{
unsigned int p = states.size();
states.push_back(s);
stateIndex[s] = p;
edges.resize(states.size());
}
}
}
else
{
std::map<const State*, unsigned int>::iterator it1 = stateIndex.find(s1);
std::map<const State*, unsigned int>::iterator it2 = stateIndex.find(s2);
bool newEdge = false;
unsigned int p1;
if (it1 == stateIndex.end())
{
p1 = states.size();
states.push_back(s1);
stateIndex[s1] = p1;
edges.resize(states.size());
newEdge = true;
}
else
p1 = it1->second;
unsigned int p2;
if (it2 == stateIndex.end())
{
p2 = states.size();
states.push_back(s2);
stateIndex[s2] = p2;
edges.resize(states.size());
newEdge = true;
}
else
p2 = it2->second;
// if we are not yet sure this is a new edge, we check indeed if this edge exists
if (!newEdge)
{
newEdge = true;
for (unsigned int i = 0 ; i < edges[p1].size() ; ++i)
if (edges[p1][i] == p2)
{
newEdge = false;
break;
}
}
if (newEdge)
edges[p1].push_back(p2);
}
}
void ompl::base::PlannerData::print(std::ostream &out) const
{
out << states.size() << std::endl;
for (unsigned int i = 0 ; i < states.size() ; ++i)
{
out << i << ": ";
if (si)
si->printState(states[i], out);
else
out << states[i] << std::endl;
}
for (unsigned int i = 0 ; i < edges.size() ; ++i)
{
if (edges[i].empty())
continue;
out << i << ": ";
for (unsigned int j = 0 ; j < edges[i].size() ; ++j)
out << edges[i][j] << ' ';
out << std::endl;
}
}
void ompl::base::PlannerInputStates::clear(void)
{
if (tempState_)
{
si_->freeState(tempState_);
tempState_ = NULL;
}
addedStartStates_ = 0;
sampledGoalsCount_ = 0;
pdef_ = NULL;
si_ = NULL;
}
bool ompl::base::PlannerInputStates::update(void)
{
if (!planner_)
throw Exception("No planner set for PlannerInputStates");
return use(planner_->getSpaceInformation(), planner_->getProblemDefinition());
}
void ompl::base::PlannerInputStates::checkValidity(void) const
{
std::string error;
if (!pdef_)
error = "Problem definition not specified";
else
{
if (pdef_->getStartStateCount() <= 0)
error = "No start states specified";
else
if (!pdef_->getGoal())
error = "No goal specified";
}
if (!error.empty())
{
if (planner_)
throw Exception(planner_->getName(), error);
else
throw Exception(error);
}
}
bool ompl::base::PlannerInputStates::use(const SpaceInformationPtr &si, const ProblemDefinitionPtr &pdef)
{
if (si && pdef)
return use(si.get(), pdef.get());
else
{
clear();
return true;
}
}
bool ompl::base::PlannerInputStates::use(const SpaceInformation *si, const ProblemDefinition *pdef)
{
if (pdef_ != pdef || si_ != si)
{
clear();
pdef_ = pdef;
si_ = si;
return true;
}
return false;
}
const ompl::base::State* ompl::base::PlannerInputStates::nextStart(void)
{
if (pdef_ == NULL || si_ == NULL)
{
std::string error = "Missing space information or problem definition";
if (planner_)
throw Exception(planner_->getName(), error);
else
throw Exception(error);
}
while (addedStartStates_ < pdef_->getStartStateCount())
{
const base::State *st = pdef_->getStartState(addedStartStates_);
addedStartStates_++;
bool bounds = si_->satisfiesBounds(st);
bool valid = bounds ? si_->isValid(st) : false;
if (bounds && valid)
return st;
else
{
msg::Interface msg(planner_ ? planner_->getName() : "");
msg.warn("Skipping invalid start state (invalid %s)", bounds ? "bounds" : "state");
}
}
return NULL;
}
const ompl::base::State* ompl::base::PlannerInputStates::nextGoal(void)
{
static PlannerTerminationCondition ptc = boost::bind(&alwaysTrue);
return nextGoal(ptc);
}
const ompl::base::State* ompl::base::PlannerInputStates::nextGoal(const PlannerTerminationCondition &ptc)
{
if (pdef_ == NULL || si_ == NULL)
{
std::string error = "Missing space information or problem definition";
if (planner_)
throw Exception(planner_->getName(), error);
else
throw Exception(error);
}
const GoalSampleableRegion *goal = dynamic_cast<const GoalSampleableRegion*>(pdef_->getGoal().get());
if (goal)
{
const GoalLazySamples *gls = dynamic_cast<const GoalLazySamples*>(goal);
bool first = true;
bool attempt = true;
while (attempt)
{
attempt = false;
if (sampledGoalsCount_ < goal->maxSampleCount())
{
if (tempState_ == NULL)
tempState_ = si_->allocState();
do
{
goal->sampleGoal(tempState_);
sampledGoalsCount_++;
bool bounds = si_->satisfiesBounds(tempState_);
bool valid = bounds ? si_->isValid(tempState_) : false;
if (bounds && valid)
return tempState_;
else
{
msg::Interface msg(planner_ ? planner_->getName() : "");
msg.warn("Skipping invalid goal state (invalid %s)", bounds ? "bounds" : "state");
}
}
while (sampledGoalsCount_ < goal->maxSampleCount() && !ptc());
}
if (gls && goal->canSample() && !ptc())
{
if (first)
{
first = false;
msg::Interface msg(planner_ ? planner_->getName() : "");
msg.debug("Waiting for goal region samples ...");
}
boost::this_thread::sleep(time::seconds(0.01));
attempt = !ptc();
}
}
}
return NULL;
}
bool ompl::base::PlannerInputStates::haveMoreStartStates(void) const
{
if (pdef_)
return addedStartStates_ < pdef_->getStartStateCount();
return false;
}
bool ompl::base::PlannerInputStates::haveMoreGoalStates(void) const
{
if (pdef_ && pdef_->getGoal())
{
const GoalSampleableRegion *goal = dynamic_cast<const GoalSampleableRegion*>(pdef_->getGoal().get());
if (goal)
return sampledGoalsCount_ < goal->maxSampleCount();
}
return false;
}
<commit_msg>correcting a message about skipped invalid input states<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Rice 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 Rice 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.
*********************************************************************/
/* Author: Ioan Sucan */
#include "ompl/base/Planner.h"
#include "ompl/util/Exception.h"
#include "ompl/base/GoalSampleableRegion.h"
#include "ompl/base/GoalLazySamples.h"
#include <boost/thread.hpp>
#include <utility>
ompl::base::Planner::Planner(const SpaceInformationPtr &si, const std::string &name) :
si_(si), pis_(this), name_(name), type_(PLAN_UNKNOWN), setup_(false), msg_(name)
{
if (!si_)
throw Exception(name_, "Invalid space information instance for planner");
}
ompl::base::PlannerType ompl::base::Planner::getType(void) const
{
return type_;
}
const std::string& ompl::base::Planner::getName(void) const
{
return name_;
}
void ompl::base::Planner::setName(const std::string &name)
{
name_ = name;
}
const ompl::base::SpaceInformationPtr& ompl::base::Planner::getSpaceInformation(void) const
{
return si_;
}
const ompl::base::ProblemDefinitionPtr& ompl::base::Planner::getProblemDefinition(void) const
{
return pdef_;
}
void ompl::base::Planner::setProblemDefinition(const ProblemDefinitionPtr &pdef)
{
pdef_ = pdef;
pis_.update();
}
const ompl::base::PlannerInputStates& ompl::base::Planner::getPlannerInputStates(void) const
{
return pis_;
}
void ompl::base::Planner::setup(void)
{
if (!si_->isSetup())
{
msg_.inform("Space information setup was not yet called. Calling now.");
si_->setup();
}
if (setup_)
msg_.warn("Planner setup called multiple times");
else
setup_ = true;
}
void ompl::base::Planner::checkValidity(void)
{
if (!isSetup())
setup();
pis_.checkValidity();
}
bool ompl::base::Planner::isSetup(void) const
{
return setup_;
}
void ompl::base::Planner::clear(void)
{
pis_.clear();
pis_.update();
}
void ompl::base::Planner::getPlannerData(PlannerData &data) const
{
data.si = si_;
}
namespace ompl
{
// return true if a certain point in time has passed
static bool timePassed(const time::point &endTime)
{
return time::now() > endTime;
}
// return if an externally passed flag is true
static bool evaluateFlag(const bool *flag)
{
return *flag;
}
// periodically evaluate a termination condition and store the result at an indicated location
static void periodicConditionEvaluator(const base::PlannerTerminationCondition &ptc, double checkInterval, bool *flag)
{
time::duration s = time::seconds(checkInterval);
do
{
bool shouldTerminate = ptc();
if (shouldTerminate)
*flag = true;
if (*flag == false)
boost::this_thread::sleep(s);
} while (*flag == false);
}
static bool alwaysTrue(void)
{
return true;
}
}
bool ompl::base::Planner::solve(const PlannerTerminationCondition &ptc, double checkInterval)
{
bool flag = false;
boost::thread condEvaluator(boost::bind(&periodicConditionEvaluator, ptc, checkInterval, &flag));
bool result = solve(boost::bind(&evaluateFlag, &flag));
flag = true;
condEvaluator.interrupt();
condEvaluator.join();
return result;
}
bool ompl::base::Planner::solve(double solveTime)
{
if (solveTime < 1.0)
return solve(boost::bind(&timePassed, time::now() + time::seconds(solveTime)));
else
return solve(boost::bind(&timePassed, time::now() + time::seconds(solveTime)), std::min(solveTime / 100.0, 0.1));
}
void ompl::base::PlannerData::clear(void)
{
stateIndex.clear();
states.clear();
edges.clear();
properties.clear();
si.reset();
}
void ompl::base::PlannerData::recordEdge(const State *s1, const State *s2)
{
if (s1 == NULL || s2 == NULL)
{
const State *s = s1 == NULL ? s2 : s1;
if (s != NULL)
{
std::map<const State*, unsigned int>::iterator it = stateIndex.find(s);
if (it == stateIndex.end())
{
unsigned int p = states.size();
states.push_back(s);
stateIndex[s] = p;
edges.resize(states.size());
}
}
}
else
{
std::map<const State*, unsigned int>::iterator it1 = stateIndex.find(s1);
std::map<const State*, unsigned int>::iterator it2 = stateIndex.find(s2);
bool newEdge = false;
unsigned int p1;
if (it1 == stateIndex.end())
{
p1 = states.size();
states.push_back(s1);
stateIndex[s1] = p1;
edges.resize(states.size());
newEdge = true;
}
else
p1 = it1->second;
unsigned int p2;
if (it2 == stateIndex.end())
{
p2 = states.size();
states.push_back(s2);
stateIndex[s2] = p2;
edges.resize(states.size());
newEdge = true;
}
else
p2 = it2->second;
// if we are not yet sure this is a new edge, we check indeed if this edge exists
if (!newEdge)
{
newEdge = true;
for (unsigned int i = 0 ; i < edges[p1].size() ; ++i)
if (edges[p1][i] == p2)
{
newEdge = false;
break;
}
}
if (newEdge)
edges[p1].push_back(p2);
}
}
void ompl::base::PlannerData::print(std::ostream &out) const
{
out << states.size() << std::endl;
for (unsigned int i = 0 ; i < states.size() ; ++i)
{
out << i << ": ";
if (si)
si->printState(states[i], out);
else
out << states[i] << std::endl;
}
for (unsigned int i = 0 ; i < edges.size() ; ++i)
{
if (edges[i].empty())
continue;
out << i << ": ";
for (unsigned int j = 0 ; j < edges[i].size() ; ++j)
out << edges[i][j] << ' ';
out << std::endl;
}
}
void ompl::base::PlannerInputStates::clear(void)
{
if (tempState_)
{
si_->freeState(tempState_);
tempState_ = NULL;
}
addedStartStates_ = 0;
sampledGoalsCount_ = 0;
pdef_ = NULL;
si_ = NULL;
}
bool ompl::base::PlannerInputStates::update(void)
{
if (!planner_)
throw Exception("No planner set for PlannerInputStates");
return use(planner_->getSpaceInformation(), planner_->getProblemDefinition());
}
void ompl::base::PlannerInputStates::checkValidity(void) const
{
std::string error;
if (!pdef_)
error = "Problem definition not specified";
else
{
if (pdef_->getStartStateCount() <= 0)
error = "No start states specified";
else
if (!pdef_->getGoal())
error = "No goal specified";
}
if (!error.empty())
{
if (planner_)
throw Exception(planner_->getName(), error);
else
throw Exception(error);
}
}
bool ompl::base::PlannerInputStates::use(const SpaceInformationPtr &si, const ProblemDefinitionPtr &pdef)
{
if (si && pdef)
return use(si.get(), pdef.get());
else
{
clear();
return true;
}
}
bool ompl::base::PlannerInputStates::use(const SpaceInformation *si, const ProblemDefinition *pdef)
{
if (pdef_ != pdef || si_ != si)
{
clear();
pdef_ = pdef;
si_ = si;
return true;
}
return false;
}
const ompl::base::State* ompl::base::PlannerInputStates::nextStart(void)
{
if (pdef_ == NULL || si_ == NULL)
{
std::string error = "Missing space information or problem definition";
if (planner_)
throw Exception(planner_->getName(), error);
else
throw Exception(error);
}
while (addedStartStates_ < pdef_->getStartStateCount())
{
const base::State *st = pdef_->getStartState(addedStartStates_);
addedStartStates_++;
bool bounds = si_->satisfiesBounds(st);
bool valid = bounds ? si_->isValid(st) : false;
if (bounds && valid)
return st;
else
{
msg::Interface msg(planner_ ? planner_->getName() : "");
msg.warn("Skipping invalid start state (invalid %s)", bounds ? "state": "bounds");
}
}
return NULL;
}
const ompl::base::State* ompl::base::PlannerInputStates::nextGoal(void)
{
static PlannerTerminationCondition ptc = boost::bind(&alwaysTrue);
return nextGoal(ptc);
}
const ompl::base::State* ompl::base::PlannerInputStates::nextGoal(const PlannerTerminationCondition &ptc)
{
if (pdef_ == NULL || si_ == NULL)
{
std::string error = "Missing space information or problem definition";
if (planner_)
throw Exception(planner_->getName(), error);
else
throw Exception(error);
}
const GoalSampleableRegion *goal = dynamic_cast<const GoalSampleableRegion*>(pdef_->getGoal().get());
if (goal)
{
const GoalLazySamples *gls = dynamic_cast<const GoalLazySamples*>(goal);
bool first = true;
bool attempt = true;
while (attempt)
{
attempt = false;
if (sampledGoalsCount_ < goal->maxSampleCount())
{
if (tempState_ == NULL)
tempState_ = si_->allocState();
do
{
goal->sampleGoal(tempState_);
sampledGoalsCount_++;
bool bounds = si_->satisfiesBounds(tempState_);
bool valid = bounds ? si_->isValid(tempState_) : false;
if (bounds && valid)
return tempState_;
else
{
msg::Interface msg(planner_ ? planner_->getName() : "");
msg.warn("Skipping invalid goal state (invalid %s)", bounds ? "state": "bounds");
}
}
while (sampledGoalsCount_ < goal->maxSampleCount() && !ptc());
}
if (gls && goal->canSample() && !ptc())
{
if (first)
{
first = false;
msg::Interface msg(planner_ ? planner_->getName() : "");
msg.debug("Waiting for goal region samples ...");
}
boost::this_thread::sleep(time::seconds(0.01));
attempt = !ptc();
}
}
}
return NULL;
}
bool ompl::base::PlannerInputStates::haveMoreStartStates(void) const
{
if (pdef_)
return addedStartStates_ < pdef_->getStartStateCount();
return false;
}
bool ompl::base::PlannerInputStates::haveMoreGoalStates(void) const
{
if (pdef_ && pdef_->getGoal())
{
const GoalSampleableRegion *goal = dynamic_cast<const GoalSampleableRegion*>(pdef_->getGoal().get());
if (goal)
return sampledGoalsCount_ < goal->maxSampleCount();
}
return false;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pe_vari.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2006-06-19 12:05:39 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <precomp.h>
#include "pe_vari.hxx"
// NOT FULLY DEFINED SERVICES
#include <cosv/template/tpltools.hxx>
#include "pe_expr.hxx"
namespace cpp {
PE_Variable::PE_Variable( Cpp_PE * i_pParent )
: Cpp_PE(i_pParent),
pStati( new PeStatusArray<PE_Variable> )
// pSpExpression,
// pSpuArraySizeExpression,
// pSpuInitExpression,
// sResultSizeExpression,
// sResultInitExpression
{
Setup_StatusFunctions();
pSpExpression = new SP_Expression(*this);
pSpuArraySizeExpression = new SPU_Expression(*pSpExpression, 0, &PE_Variable::SpReturn_ArraySizeExpression);
pSpuInitExpression = new SPU_Expression(*pSpExpression, 0, &PE_Variable::SpReturn_InitExpression);
}
PE_Variable::~PE_Variable()
{
}
void
PE_Variable::Call_Handler( const cpp::Token & i_rTok )
{
pStati->Cur().Call_Handler(i_rTok.TypeId(), i_rTok.Text());
}
void
PE_Variable::Setup_StatusFunctions()
{
typedef CallFunction<PE_Variable>::F_Tok F_Tok;
static F_Tok stateF_afterName[] = { &PE_Variable::On_afterName_ArrayBracket_Left,
&PE_Variable::On_afterName_Semicolon,
&PE_Variable::On_afterName_Comma,
&PE_Variable::On_afterName_Assign };
static INT16 stateT_afterName[] = { Tid_ArrayBracket_Left,
Tid_Semicolon,
Tid_Comma,
Tid_Assign };
static F_Tok stateF_afterSize[] = { &PE_Variable::On_afterSize_ArrayBracket_Right };
static INT16 stateT_afterSize[] = { Tid_ArrayBracket_Right };
static F_Tok stateF_expectFinish[] = { &PE_Variable::On_expectFinish_Bracket_Right,
&PE_Variable::On_expectFinish_Semicolon,
&PE_Variable::On_expectFinish_Comma };
static INT16 stateT_expectFinish[] = { Tid_Bracket_Right,
Tid_Semicolon,
Tid_Comma };
SEMPARSE_CREATE_STATUS(PE_Variable, afterName, Hdl_SyntaxError);
SEMPARSE_CREATE_STATUS(PE_Variable, afterSize, Hdl_SyntaxError);
SEMPARSE_CREATE_STATUS(PE_Variable, expectFinish, Hdl_SyntaxError);
}
void
PE_Variable::InitData()
{
pStati->SetCur(afterName);
sResultSizeExpression.clear();
sResultInitExpression.clear();
}
void
PE_Variable::TransferData()
{
pStati->SetCur(size_of_states);
}
void
PE_Variable::Hdl_SyntaxError( const char * i_sText)
{
StdHandlingOfSyntaxError(i_sText);
}
void
PE_Variable::SpReturn_ArraySizeExpression()
{
pStati->SetCur(afterSize);
sResultSizeExpression = pSpuArraySizeExpression->Child().Result_Text();
}
void
PE_Variable::SpReturn_InitExpression()
{
pStati->SetCur(expectFinish);
sResultInitExpression = pSpuInitExpression->Child().Result_Text();
}
void
PE_Variable::On_afterName_ArrayBracket_Left(const char *)
{
pSpuArraySizeExpression->Push(done);
}
void
PE_Variable::On_afterName_Semicolon(const char *)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Variable::On_afterName_Comma(const char *)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Variable::On_afterName_Assign(const char *)
{
pSpuInitExpression->Push(done);
}
void
PE_Variable::On_afterSize_ArrayBracket_Right(const char *)
{
SetTokenResult(done, stay);
pStati->SetCur(afterName);
}
void
PE_Variable::On_expectFinish_Semicolon(const char *)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Variable::On_expectFinish_Comma(const char *)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Variable::On_expectFinish_Bracket_Right(const char *)
{
SetTokenResult(not_done, pop_success);
}
} // namespace cpp
<commit_msg>INTEGRATION: CWS pchfix02 (1.5.6); FILE MERGED 2006/09/01 17:15:44 kaib 1.5.6.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pe_vari.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-09-16 17:04:14 $
*
* 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_autodoc.hxx"
#include <precomp.h>
#include "pe_vari.hxx"
// NOT FULLY DEFINED SERVICES
#include <cosv/template/tpltools.hxx>
#include "pe_expr.hxx"
namespace cpp {
PE_Variable::PE_Variable( Cpp_PE * i_pParent )
: Cpp_PE(i_pParent),
pStati( new PeStatusArray<PE_Variable> )
// pSpExpression,
// pSpuArraySizeExpression,
// pSpuInitExpression,
// sResultSizeExpression,
// sResultInitExpression
{
Setup_StatusFunctions();
pSpExpression = new SP_Expression(*this);
pSpuArraySizeExpression = new SPU_Expression(*pSpExpression, 0, &PE_Variable::SpReturn_ArraySizeExpression);
pSpuInitExpression = new SPU_Expression(*pSpExpression, 0, &PE_Variable::SpReturn_InitExpression);
}
PE_Variable::~PE_Variable()
{
}
void
PE_Variable::Call_Handler( const cpp::Token & i_rTok )
{
pStati->Cur().Call_Handler(i_rTok.TypeId(), i_rTok.Text());
}
void
PE_Variable::Setup_StatusFunctions()
{
typedef CallFunction<PE_Variable>::F_Tok F_Tok;
static F_Tok stateF_afterName[] = { &PE_Variable::On_afterName_ArrayBracket_Left,
&PE_Variable::On_afterName_Semicolon,
&PE_Variable::On_afterName_Comma,
&PE_Variable::On_afterName_Assign };
static INT16 stateT_afterName[] = { Tid_ArrayBracket_Left,
Tid_Semicolon,
Tid_Comma,
Tid_Assign };
static F_Tok stateF_afterSize[] = { &PE_Variable::On_afterSize_ArrayBracket_Right };
static INT16 stateT_afterSize[] = { Tid_ArrayBracket_Right };
static F_Tok stateF_expectFinish[] = { &PE_Variable::On_expectFinish_Bracket_Right,
&PE_Variable::On_expectFinish_Semicolon,
&PE_Variable::On_expectFinish_Comma };
static INT16 stateT_expectFinish[] = { Tid_Bracket_Right,
Tid_Semicolon,
Tid_Comma };
SEMPARSE_CREATE_STATUS(PE_Variable, afterName, Hdl_SyntaxError);
SEMPARSE_CREATE_STATUS(PE_Variable, afterSize, Hdl_SyntaxError);
SEMPARSE_CREATE_STATUS(PE_Variable, expectFinish, Hdl_SyntaxError);
}
void
PE_Variable::InitData()
{
pStati->SetCur(afterName);
sResultSizeExpression.clear();
sResultInitExpression.clear();
}
void
PE_Variable::TransferData()
{
pStati->SetCur(size_of_states);
}
void
PE_Variable::Hdl_SyntaxError( const char * i_sText)
{
StdHandlingOfSyntaxError(i_sText);
}
void
PE_Variable::SpReturn_ArraySizeExpression()
{
pStati->SetCur(afterSize);
sResultSizeExpression = pSpuArraySizeExpression->Child().Result_Text();
}
void
PE_Variable::SpReturn_InitExpression()
{
pStati->SetCur(expectFinish);
sResultInitExpression = pSpuInitExpression->Child().Result_Text();
}
void
PE_Variable::On_afterName_ArrayBracket_Left(const char *)
{
pSpuArraySizeExpression->Push(done);
}
void
PE_Variable::On_afterName_Semicolon(const char *)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Variable::On_afterName_Comma(const char *)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Variable::On_afterName_Assign(const char *)
{
pSpuInitExpression->Push(done);
}
void
PE_Variable::On_afterSize_ArrayBracket_Right(const char *)
{
SetTokenResult(done, stay);
pStati->SetCur(afterName);
}
void
PE_Variable::On_expectFinish_Semicolon(const char *)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Variable::On_expectFinish_Comma(const char *)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Variable::On_expectFinish_Bracket_Right(const char *)
{
SetTokenResult(not_done, pop_success);
}
} // namespace cpp
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pe_vari.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-07 18:30:58 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <precomp.h>
#include "pe_vari.hxx"
// NOT FULLY DEFINED SERVICES
#include <cosv/template/tpltools.hxx>
#include "pe_expr.hxx"
namespace cpp {
PE_Variable::PE_Variable( Cpp_PE * i_pParent )
: Cpp_PE(i_pParent),
pStati( new PeStatusArray<PE_Variable> )
// pSpExpression,
// pSpuArraySizeExpression,
// pSpuInitExpression,
// sResultSizeExpression,
// sResultInitExpression
{
Setup_StatusFunctions();
pSpExpression = new SP_Expression(*this);
pSpuArraySizeExpression = new SPU_Expression(*pSpExpression, 0, &PE_Variable::SpReturn_ArraySizeExpression);
pSpuInitExpression = new SPU_Expression(*pSpExpression, 0, &PE_Variable::SpReturn_InitExpression);
}
PE_Variable::~PE_Variable()
{
}
void
PE_Variable::Call_Handler( const cpp::Token & i_rTok )
{
pStati->Cur().Call_Handler(i_rTok.TypeId(), i_rTok.Text());
}
void
PE_Variable::Setup_StatusFunctions()
{
typedef CallFunction<PE_Variable>::F_Tok F_Tok;
static F_Tok stateF_afterName[] = { &PE_Variable::On_afterName_ArrayBracket_Left,
&PE_Variable::On_afterName_Semicolon,
&PE_Variable::On_afterName_Comma,
&PE_Variable::On_afterName_Assign };
static INT16 stateT_afterName[] = { Tid_ArrayBracket_Left,
Tid_Semicolon,
Tid_Comma,
Tid_Assign };
static F_Tok stateF_afterSize[] = { &PE_Variable::On_afterSize_ArrayBracket_Right };
static INT16 stateT_afterSize[] = { Tid_ArrayBracket_Right };
static F_Tok stateF_expectFinish[] = { &PE_Variable::On_expectFinish_Bracket_Right,
&PE_Variable::On_expectFinish_Semicolon,
&PE_Variable::On_expectFinish_Comma };
static INT16 stateT_expectFinish[] = { Tid_Bracket_Right,
Tid_Semicolon,
Tid_Comma };
SEMPARSE_CREATE_STATUS(PE_Variable, afterName, Hdl_SyntaxError);
SEMPARSE_CREATE_STATUS(PE_Variable, afterSize, Hdl_SyntaxError);
SEMPARSE_CREATE_STATUS(PE_Variable, expectFinish, Hdl_SyntaxError);
}
void
PE_Variable::InitData()
{
pStati->SetCur(afterName);
sResultSizeExpression.clear();
sResultInitExpression.clear();
}
void
PE_Variable::TransferData()
{
pStati->SetCur(size_of_states);
}
void
PE_Variable::Hdl_SyntaxError( const char * i_sText)
{
StdHandlingOfSyntaxError(i_sText);
}
void
PE_Variable::SpReturn_ArraySizeExpression()
{
pStati->SetCur(afterSize);
sResultSizeExpression = pSpuArraySizeExpression->Child().Result_Text();
}
void
PE_Variable::SpReturn_InitExpression()
{
pStati->SetCur(expectFinish);
sResultInitExpression = pSpuInitExpression->Child().Result_Text();
}
void
PE_Variable::On_afterName_ArrayBracket_Left(const char * i_sText)
{
pSpuArraySizeExpression->Push(done);
}
void
PE_Variable::On_afterName_Semicolon(const char * i_sText)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Variable::On_afterName_Comma(const char * i_sText)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Variable::On_afterName_Assign(const char * i_sText)
{
pSpuInitExpression->Push(done);
}
void
PE_Variable::On_afterSize_ArrayBracket_Right(const char * i_sText)
{
SetTokenResult(done, stay);
pStati->SetCur(afterName);
}
void
PE_Variable::On_expectFinish_Semicolon(const char * i_sText)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Variable::On_expectFinish_Comma(const char * i_sText)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Variable::On_expectFinish_Bracket_Right(const char * i_sText)
{
SetTokenResult(not_done, pop_success);
}
} // namespace cpp
<commit_msg>INTEGRATION: CWS warnings01 (1.4.4); FILE MERGED 2005/10/18 08:36:15 np 1.4.4.1: #i53898#<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pe_vari.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2006-06-19 12:05:39 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <precomp.h>
#include "pe_vari.hxx"
// NOT FULLY DEFINED SERVICES
#include <cosv/template/tpltools.hxx>
#include "pe_expr.hxx"
namespace cpp {
PE_Variable::PE_Variable( Cpp_PE * i_pParent )
: Cpp_PE(i_pParent),
pStati( new PeStatusArray<PE_Variable> )
// pSpExpression,
// pSpuArraySizeExpression,
// pSpuInitExpression,
// sResultSizeExpression,
// sResultInitExpression
{
Setup_StatusFunctions();
pSpExpression = new SP_Expression(*this);
pSpuArraySizeExpression = new SPU_Expression(*pSpExpression, 0, &PE_Variable::SpReturn_ArraySizeExpression);
pSpuInitExpression = new SPU_Expression(*pSpExpression, 0, &PE_Variable::SpReturn_InitExpression);
}
PE_Variable::~PE_Variable()
{
}
void
PE_Variable::Call_Handler( const cpp::Token & i_rTok )
{
pStati->Cur().Call_Handler(i_rTok.TypeId(), i_rTok.Text());
}
void
PE_Variable::Setup_StatusFunctions()
{
typedef CallFunction<PE_Variable>::F_Tok F_Tok;
static F_Tok stateF_afterName[] = { &PE_Variable::On_afterName_ArrayBracket_Left,
&PE_Variable::On_afterName_Semicolon,
&PE_Variable::On_afterName_Comma,
&PE_Variable::On_afterName_Assign };
static INT16 stateT_afterName[] = { Tid_ArrayBracket_Left,
Tid_Semicolon,
Tid_Comma,
Tid_Assign };
static F_Tok stateF_afterSize[] = { &PE_Variable::On_afterSize_ArrayBracket_Right };
static INT16 stateT_afterSize[] = { Tid_ArrayBracket_Right };
static F_Tok stateF_expectFinish[] = { &PE_Variable::On_expectFinish_Bracket_Right,
&PE_Variable::On_expectFinish_Semicolon,
&PE_Variable::On_expectFinish_Comma };
static INT16 stateT_expectFinish[] = { Tid_Bracket_Right,
Tid_Semicolon,
Tid_Comma };
SEMPARSE_CREATE_STATUS(PE_Variable, afterName, Hdl_SyntaxError);
SEMPARSE_CREATE_STATUS(PE_Variable, afterSize, Hdl_SyntaxError);
SEMPARSE_CREATE_STATUS(PE_Variable, expectFinish, Hdl_SyntaxError);
}
void
PE_Variable::InitData()
{
pStati->SetCur(afterName);
sResultSizeExpression.clear();
sResultInitExpression.clear();
}
void
PE_Variable::TransferData()
{
pStati->SetCur(size_of_states);
}
void
PE_Variable::Hdl_SyntaxError( const char * i_sText)
{
StdHandlingOfSyntaxError(i_sText);
}
void
PE_Variable::SpReturn_ArraySizeExpression()
{
pStati->SetCur(afterSize);
sResultSizeExpression = pSpuArraySizeExpression->Child().Result_Text();
}
void
PE_Variable::SpReturn_InitExpression()
{
pStati->SetCur(expectFinish);
sResultInitExpression = pSpuInitExpression->Child().Result_Text();
}
void
PE_Variable::On_afterName_ArrayBracket_Left(const char *)
{
pSpuArraySizeExpression->Push(done);
}
void
PE_Variable::On_afterName_Semicolon(const char *)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Variable::On_afterName_Comma(const char *)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Variable::On_afterName_Assign(const char *)
{
pSpuInitExpression->Push(done);
}
void
PE_Variable::On_afterSize_ArrayBracket_Right(const char *)
{
SetTokenResult(done, stay);
pStati->SetCur(afterName);
}
void
PE_Variable::On_expectFinish_Semicolon(const char *)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Variable::On_expectFinish_Comma(const char *)
{
SetTokenResult(not_done, pop_success);
}
void
PE_Variable::On_expectFinish_Bracket_Right(const char *)
{
SetTokenResult(not_done, pop_success);
}
} // namespace cpp
<|endoftext|> |
<commit_before>#include "output_ts_base.h"
#include <mist/bitfields.h>
namespace Mist{
TSOutput::TSOutput(Socket::Connection &conn) : TS_BASECLASS(conn){
packCounter = 0;
ts_from = 0;
setBlocking(true);
sendRepeatingHeaders = 0;
lastHeaderTime = 0;
}
void TSOutput::fillPacket(char const *data, size_t dataLen, bool &firstPack, bool video,
bool keyframe, size_t pkgPid, uint16_t &contPkg){
do{
if (!packData.getBytesFree()){
if ((sendRepeatingHeaders && thisPacket.getTime() - lastHeaderTime > sendRepeatingHeaders) || !packCounter){
std::set<size_t> selectedTracks;
for (std::map<size_t, Comms::Users>::iterator it = userSelect.begin(); it != userSelect.end(); it++){
selectedTracks.insert(it->first);
}
lastHeaderTime = thisPacket.getTime();
TS::Packet tmpPack;
tmpPack.FromPointer(TS::PAT);
tmpPack.setContinuityCounter(++contPAT);
sendTS(tmpPack.checkAndGetBuffer());
sendTS(TS::createPMT(selectedTracks, M, ++contPMT));
sendTS(TS::createSDT(streamName, ++contSDT));
packCounter += 3;
}
sendTS(packData.checkAndGetBuffer());
packCounter++;
packData.clear();
}
if (!dataLen){return;}
if (packData.getBytesFree() == 184){
packData.clear();
packData.setPID(pkgPid);
packData.setContinuityCounter(++contPkg);
if (firstPack){
packData.setUnitStart(1);
if (video){
if (keyframe){
packData.setRandomAccess(true);
packData.setESPriority(true);
}
packData.setPCR(thisPacket.getTime() * 27000);
}
firstPack = false;
}
}
size_t tmp = packData.fillFree(data, dataLen);
data += tmp;
dataLen -= tmp;
}while (dataLen);
}
void TSOutput::sendNext(){
// Get ready some data to speed up accesses
std::string type = M.getType(thisIdx);
std::string codec = M.getCodec(thisIdx);
bool video = (type == "video");
size_t pkgPid = TS::getUniqTrackID(M, thisIdx);
bool &firstPack = first[thisIdx];
uint16_t &contPkg = contCounters[pkgPid];
uint64_t packTime = thisPacket.getTime();
bool keyframe = thisPacket.getInt("keyframe");
firstPack = true;
char *dataPointer = 0;
size_t dataLen = 0;
thisPacket.getString("data", dataPointer, dataLen); // data
packTime *= 90;
std::string bs;
// prepare bufferstring
if (video){
if (codec == "H264" || codec == "HEVC"){
uint32_t extraSize = 0;
// dataPointer[4] & 0x1f is used to check if this should be done later:
// fillPacket("\000\000\000\001\011\360", 6);
if (codec == "H264" && (dataPointer[4] & 0x1f) != 0x09){extraSize += 6;}
if (keyframe){
if (codec == "H264"){
MP4::AVCC avccbox;
avccbox.setPayload(M.getInit(thisIdx));
bs = avccbox.asAnnexB();
extraSize += bs.size();
}
/*LTS-START*/
if (codec == "HEVC"){
MP4::HVCC hvccbox;
hvccbox.setPayload(M.getInit(thisIdx));
bs = hvccbox.asAnnexB();
extraSize += bs.size();
}
/*LTS-END*/
}
const uint32_t MAX_PES_SIZE = 65490 - 13;
uint32_t ThisNaluSize = 0;
uint32_t i = 0;
uint64_t offset = thisPacket.getInt("offset") * 90;
bs.clear();
TS::Packet::getPESVideoLeadIn(bs,
(((dataLen + extraSize) > MAX_PES_SIZE) ? 0 : dataLen + extraSize),
packTime, offset, true, M.getBps(thisIdx));
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
if (codec == "H264" && (dataPointer[4] & 0x1f) != 0x09){
// End of previous nal unit, if not already present
fillPacket("\000\000\000\001\011\360", 6, firstPack, video, keyframe, pkgPid, contPkg);
}
if (keyframe){
if (codec == "H264"){
MP4::AVCC avccbox;
avccbox.setPayload(M.getInit(thisIdx));
bs = avccbox.asAnnexB();
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
}
/*LTS-START*/
if (codec == "HEVC"){
MP4::HVCC hvccbox;
hvccbox.setPayload(M.getInit(thisIdx));
bs = hvccbox.asAnnexB();
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
}
/*LTS-END*/
}
while (i + 4 < (unsigned int)dataLen){
ThisNaluSize = Bit::btohl(dataPointer + i);
if (ThisNaluSize + i + 4 > dataLen){
WARN_MSG("Too big NALU detected (%" PRIu32 " > %zu) - skipping!",
ThisNaluSize + i + 4, dataLen);
break;
}
fillPacket("\000\000\000\001", 4, firstPack, video, keyframe, pkgPid, contPkg);
fillPacket(dataPointer + i + 4, ThisNaluSize, firstPack, video, keyframe, pkgPid, contPkg);
i += ThisNaluSize + 4;
}
}else{
uint64_t offset = thisPacket.getInt("offset") * 90;
bs.clear();
TS::Packet::getPESVideoLeadIn(bs, 0, packTime, offset, true, M.getBps(thisIdx));
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg);
}
}else if (type == "audio"){
size_t tempLen = dataLen;
if (codec == "AAC"){
tempLen += 7;
// Make sure TS timestamp is sample-aligned, if possible
uint32_t freq = M.getRate(thisIdx);
if (freq){
uint64_t aacSamples = packTime * freq / 90000;
//round to nearest packet, assuming all 1024 samples (probably wrong, but meh)
aacSamples += 256;//Add a quarter frame of offset to encourage correct rounding
aacSamples &= ~0x3FF;
//Get closest 90kHz clock time to perfect sample alignment
packTime = aacSamples * 90000 / freq;
}
}
if (codec == "opus"){
tempLen += 3 + (dataLen/255);
bs = TS::Packet::getPESPS1LeadIn(tempLen, packTime, M.getBps(thisIdx));
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
bs = "\177\340";
bs.append(dataLen/255, (char)255);
bs.append(1, (char)(dataLen-255*(dataLen/255)));
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
}else{
bs.clear();
TS::Packet::getPESAudioLeadIn(bs, tempLen, packTime, M.getBps(thisIdx));
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
if (codec == "AAC"){
bs = TS::getAudioHeader(dataLen, M.getInit(thisIdx));
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
}
}
fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg);
}else if (type == "meta"){
long unsigned int tempLen = dataLen;
bs = TS::Packet::getPESMetaLeadIn(tempLen, packTime, M.getBps(thisIdx));
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg);
}
if (packData.getBytesFree() < 184){
packData.addStuffing();
fillPacket(0, 0, firstPack, video, keyframe, pkgPid, contPkg);
}
}
}// namespace Mist
<commit_msg>Fixed TS-based outputs injecting extra init/nalend data when not needed<commit_after>#include "output_ts_base.h"
#include <mist/bitfields.h>
namespace Mist{
TSOutput::TSOutput(Socket::Connection &conn) : TS_BASECLASS(conn){
packCounter = 0;
ts_from = 0;
setBlocking(true);
sendRepeatingHeaders = 0;
lastHeaderTime = 0;
}
void TSOutput::fillPacket(char const *data, size_t dataLen, bool &firstPack, bool video,
bool keyframe, size_t pkgPid, uint16_t &contPkg){
do{
if (!packData.getBytesFree()){
if ((sendRepeatingHeaders && thisPacket.getTime() - lastHeaderTime > sendRepeatingHeaders) || !packCounter){
std::set<size_t> selectedTracks;
for (std::map<size_t, Comms::Users>::iterator it = userSelect.begin(); it != userSelect.end(); it++){
selectedTracks.insert(it->first);
}
lastHeaderTime = thisPacket.getTime();
TS::Packet tmpPack;
tmpPack.FromPointer(TS::PAT);
tmpPack.setContinuityCounter(++contPAT);
sendTS(tmpPack.checkAndGetBuffer());
sendTS(TS::createPMT(selectedTracks, M, ++contPMT));
sendTS(TS::createSDT(streamName, ++contSDT));
packCounter += 3;
}
sendTS(packData.checkAndGetBuffer());
packCounter++;
packData.clear();
}
if (!dataLen){return;}
if (packData.getBytesFree() == 184){
packData.clear();
packData.setPID(pkgPid);
packData.setContinuityCounter(++contPkg);
if (firstPack){
packData.setUnitStart(1);
if (video){
if (keyframe){
packData.setRandomAccess(true);
packData.setESPriority(true);
}
packData.setPCR(thisPacket.getTime() * 27000);
}
firstPack = false;
}
}
size_t tmp = packData.fillFree(data, dataLen);
data += tmp;
dataLen -= tmp;
}while (dataLen);
}
void TSOutput::sendNext(){
// Get ready some data to speed up accesses
std::string type = M.getType(thisIdx);
std::string codec = M.getCodec(thisIdx);
bool video = (type == "video");
size_t pkgPid = TS::getUniqTrackID(M, thisIdx);
bool &firstPack = first[thisIdx];
uint16_t &contPkg = contCounters[pkgPid];
uint64_t packTime = thisPacket.getTime();
bool keyframe = thisPacket.getInt("keyframe");
firstPack = true;
char *dataPointer = 0;
size_t dataLen = 0;
thisPacket.getString("data", dataPointer, dataLen); // data
packTime *= 90;
std::string bs;
// prepare bufferstring
if (video){
bool addInit = keyframe;
bool addEndNal = true;
if (codec == "H264" || codec == "HEVC"){
uint32_t extraSize = 0;
//Check if we need to skip sending some things
if (codec == "H264"){
size_t ctr = 0;
char * ptr = dataPointer;
while (ptr+4 < dataPointer+dataLen && ++ctr <= 5){
switch (ptr[4] & 0x1f){
case 0x07://init
case 0x08://init
addInit = false;
break;
case 0x09://new nal
addEndNal = false;
break;
default: break;
}
ptr += Bit::btohl(ptr);
}
}
if (addEndNal && codec == "H264"){extraSize += 6;}
if (addInit){
if (codec == "H264"){
MP4::AVCC avccbox;
avccbox.setPayload(M.getInit(thisIdx));
bs = avccbox.asAnnexB();
extraSize += bs.size();
}
if (codec == "HEVC"){
MP4::HVCC hvccbox;
hvccbox.setPayload(M.getInit(thisIdx));
bs = hvccbox.asAnnexB();
extraSize += bs.size();
}
}
const uint32_t MAX_PES_SIZE = 65490 - 13;
uint32_t ThisNaluSize = 0;
uint32_t i = 0;
uint64_t offset = thisPacket.getInt("offset") * 90;
bs.clear();
TS::Packet::getPESVideoLeadIn(bs,
(((dataLen + extraSize) > MAX_PES_SIZE) ? 0 : dataLen + extraSize),
packTime, offset, true, M.getBps(thisIdx));
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
// End of previous nal unit, if not already present
if (addEndNal && codec == "H264"){
fillPacket("\000\000\000\001\011\360", 6, firstPack, video, keyframe, pkgPid, contPkg);
}
// Init data, if keyframe and not already present
if (addInit){
if (codec == "H264"){
MP4::AVCC avccbox;
avccbox.setPayload(M.getInit(thisIdx));
bs = avccbox.asAnnexB();
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
}
/*LTS-START*/
if (codec == "HEVC"){
MP4::HVCC hvccbox;
hvccbox.setPayload(M.getInit(thisIdx));
bs = hvccbox.asAnnexB();
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
}
/*LTS-END*/
}
while (i + 4 < (unsigned int)dataLen){
ThisNaluSize = Bit::btohl(dataPointer + i);
if (ThisNaluSize + i + 4 > dataLen){
WARN_MSG("Too big NALU detected (%" PRIu32 " > %zu) - skipping!",
ThisNaluSize + i + 4, dataLen);
break;
}
fillPacket("\000\000\000\001", 4, firstPack, video, keyframe, pkgPid, contPkg);
fillPacket(dataPointer + i + 4, ThisNaluSize, firstPack, video, keyframe, pkgPid, contPkg);
i += ThisNaluSize + 4;
}
}else{
uint64_t offset = thisPacket.getInt("offset") * 90;
bs.clear();
TS::Packet::getPESVideoLeadIn(bs, 0, packTime, offset, true, M.getBps(thisIdx));
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg);
}
}else if (type == "audio"){
size_t tempLen = dataLen;
if (codec == "AAC"){
tempLen += 7;
// Make sure TS timestamp is sample-aligned, if possible
uint32_t freq = M.getRate(thisIdx);
if (freq){
uint64_t aacSamples = packTime * freq / 90000;
//round to nearest packet, assuming all 1024 samples (probably wrong, but meh)
aacSamples += 256;//Add a quarter frame of offset to encourage correct rounding
aacSamples &= ~0x3FF;
//Get closest 90kHz clock time to perfect sample alignment
packTime = aacSamples * 90000 / freq;
}
}
if (codec == "opus"){
tempLen += 3 + (dataLen/255);
bs = TS::Packet::getPESPS1LeadIn(tempLen, packTime, M.getBps(thisIdx));
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
bs = "\177\340";
bs.append(dataLen/255, (char)255);
bs.append(1, (char)(dataLen-255*(dataLen/255)));
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
}else{
bs.clear();
TS::Packet::getPESAudioLeadIn(bs, tempLen, packTime, M.getBps(thisIdx));
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
if (codec == "AAC"){
bs = TS::getAudioHeader(dataLen, M.getInit(thisIdx));
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
}
}
fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg);
}else if (type == "meta"){
long unsigned int tempLen = dataLen;
bs = TS::Packet::getPESMetaLeadIn(tempLen, packTime, M.getBps(thisIdx));
fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);
fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg);
}
if (packData.getBytesFree() < 184){
packData.addStuffing();
fillPacket(0, 0, firstPack, video, keyframe, pkgPid, contPkg);
}
}
}// namespace Mist
<|endoftext|> |
<commit_before>// Copyright (C) 2010, Vaclav Haisman. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modifica-
// tion, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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
// APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
// DING, 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 <log4cplus/helpers/stringhelper.h>
#ifdef LOG4CPLUS_HAVE_ICONV_H
#include <iconv.h>
#endif
#include <stdexcept>
#include <iostream>
#include <sstream>
#include <cassert>
#include <cerrno>
#include <cstring>
namespace log4cplus
{
namespace helpers
{
#if defined (LOG4CPLUS_WITH_ICONV)
namespace
{
static iconv_t const iconv_error_handle = reinterpret_cast<iconv_t>(-1);
struct iconv_handle
{
iconv_handle (char const * to, char const * from)
: handle (iconv_open (to, from))
{
if (handle == iconv_error_handle)
{
std::ostringstream oss;
oss << "iconv_open failed: " << errno;
std::cerr << oss.str () << std::endl;
throw std::runtime_error (oss.str ().c_str ());
}
}
~iconv_handle ()
{
if (handle != iconv_error_handle)
{
int ret = iconv_close (handle);
if (ret == -1)
{
std::ostringstream oss;
oss << "iconv_close failed: " << errno;
std::cerr << oss.str () << std::endl;
throw std::runtime_error (oss.str ().c_str ());
}
}
}
//! SUSv3 iconv() type.
typedef size_t (& iconv_func_type_1) (iconv_t cd, char * * inbuf,
size_t * inbytesleft, char * * outbuf, size_t * outbytesleft);
size_t
call_iconv (iconv_func_type_1 iconv_func, char * * inbuf,
size_t * inbytesleft, char * * outbuf, size_t * outbytesleft)
{
return iconv_func (handle, inbuf, inbytesleft, outbuf, outbytesleft);
}
//! GNU iconv() type.
typedef size_t (& iconv_func_type_2) (iconv_t cd, const char * * inbuf,
size_t * inbytesleft, char * * outbuf, size_t * outbytesleft);
size_t
call_iconv (iconv_func_type_2 iconv_func, char * * inbuf,
size_t * inbytesleft, char * * outbuf, size_t * outbytesleft)
{
return iconv_func (handle, const_cast<const char * *>(inbuf),
inbytesleft, outbuf, outbytesleft);
}
size_t
do_iconv (char * * inbuf, size_t * inbytesleft, char * * outbuf,
size_t * outbytesleft)
{
return call_iconv (iconv, inbuf, inbytesleft, outbuf, outbytesleft);
}
iconv_t handle;
};
template <typename T>
struct question_mark;
template <>
struct question_mark<char>
{
static char const value = '?';
};
template <>
struct question_mark<wchar_t>
{
static wchar_t const value = L'?';
};
char const question_mark<char>::value;
wchar_t const question_mark<wchar_t>::value;
template <typename DestType, typename SrcType>
static
void
iconv_conv (std::basic_string<DestType> & result, char const * destenc,
SrcType const * src, std::size_t size, char const * srcenc)
{
iconv_handle cvt (destenc, srcenc);
if (cvt.handle == iconv_error_handle)
{
// TODO: Better error handling.
result.resize (0);
return;
}
typedef DestType outbuf_type;
typedef SrcType inbuf_type;
std::size_t result_size = size + size / 3 + 1;
result.resize (result_size);
char * inbuf = const_cast<char *>(reinterpret_cast<char const *>(src));
std::size_t inbytesleft = size * sizeof (inbuf_type);
char * outbuf = reinterpret_cast<char *>(&result[0]);
std::size_t outbytesleft = result_size * sizeof (outbuf_type);
std::size_t res;
std::size_t const error_retval = static_cast<std::size_t>(-1);
while (inbytesleft != 0)
{
res = cvt.do_iconv (&inbuf, &inbytesleft, &outbuf, &outbytesleft);
if (res == error_retval)
{
switch (errno)
{
case EILSEQ:
case EINVAL:
if (outbytesleft >= sizeof (outbuf_type))
{
if (inbytesleft > 0)
{
++inbuf;
inbytesleft -= sizeof (inbuf_type);
}
*outbuf = question_mark<outbuf_type>::value;
++outbuf;
outbytesleft -= sizeof (outbuf_type);
continue;
}
// Fall through.
case E2BIG:;
// Fall through.
}
std::size_t const outbuf_index = result_size;
result_size *= 2;
result.resize (result_size);
outbuf = reinterpret_cast<char *>(&result[0] + outbuf_index);
outbytesleft = (result_size - outbuf_index) * sizeof (outbuf_type);
}
else
result.resize (result_size - outbytesleft / sizeof (outbuf_type));
}
}
} // namespace
std::string
tostring (const std::wstring & src)
{
std::string ret;
iconv_conv (ret, "UTF-8", src.c_str (), src.size (), "WCHAR_T");
return ret;
}
std::string
tostring (wchar_t const * src)
{
assert (src);
std::string ret;
iconv_conv (ret, "UTF-8", src, std::wcslen (src), "WCHAR_T");
return ret;
}
std::wstring
towstring (const std::string& src)
{
std::wstring ret;
iconv_conv (ret, "WCHAR_T", src.c_str (), src.size (), "UTF-8");
return ret;
}
std::wstring
towstring (char const * src)
{
assert (src);
std::wstring ret;
iconv_conv (ret, "WCHAR_T", src, std::strlen (src), "UTF-8");
return ret;
}
#endif // LOG4CPLUS_WITH_ICONV
} // namespace helpers
} // namespace log4cplus
<commit_msg>stringhelper-iconv.cxx: Fix compilation with Sun CC on Solaris.<commit_after>// Copyright (C) 2010, Vaclav Haisman. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modifica-
// tion, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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
// APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
// DING, 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 <log4cplus/helpers/stringhelper.h>
#ifdef LOG4CPLUS_HAVE_ICONV_H
#include <iconv.h>
#endif
#include <stdexcept>
#include <iostream>
#include <sstream>
#include <cassert>
#include <cerrno>
#include <cstring>
// This is here because some compilers (Sun CC) think that there is a
// difference if the typedefs are not in an extern "C" block.
extern "C"
{
//! SUSv3 iconv() type.
typedef size_t (& iconv_func_type_1) (iconv_t cd, char * * inbuf,
size_t * inbytesleft, char * * outbuf, size_t * outbytesleft);
//! GNU iconv() type.
typedef size_t (& iconv_func_type_2) (iconv_t cd, const char * * inbuf,
size_t * inbytesleft, char * * outbuf, size_t * outbytesleft);
} // extern "C"
namespace log4cplus
{
namespace helpers
{
#if defined (LOG4CPLUS_WITH_ICONV)
namespace
{
static iconv_t const iconv_error_handle = reinterpret_cast<iconv_t>(-1);
struct iconv_handle
{
iconv_handle (char const * to, char const * from)
: handle (iconv_open (to, from))
{
if (handle == iconv_error_handle)
{
std::ostringstream oss;
oss << "iconv_open failed: " << errno;
std::cerr << oss.str () << std::endl;
throw std::runtime_error (oss.str ().c_str ());
}
}
~iconv_handle ()
{
if (handle != iconv_error_handle)
{
int ret = iconv_close (handle);
if (ret == -1)
{
std::ostringstream oss;
oss << "iconv_close failed: " << errno;
std::cerr << oss.str () << std::endl;
throw std::runtime_error (oss.str ().c_str ());
}
}
}
size_t
call_iconv (iconv_func_type_1 iconv_func, char * * inbuf,
size_t * inbytesleft, char * * outbuf, size_t * outbytesleft)
{
return iconv_func (handle, inbuf, inbytesleft, outbuf, outbytesleft);
}
size_t
call_iconv (iconv_func_type_2 iconv_func, char * * inbuf,
size_t * inbytesleft, char * * outbuf, size_t * outbytesleft)
{
return iconv_func (handle, const_cast<const char * *>(inbuf),
inbytesleft, outbuf, outbytesleft);
}
size_t
do_iconv (char * * inbuf, size_t * inbytesleft, char * * outbuf,
size_t * outbytesleft)
{
return call_iconv (iconv, inbuf, inbytesleft, outbuf, outbytesleft);
}
iconv_t handle;
};
template <typename T>
struct question_mark;
template <>
struct question_mark<char>
{
static char const value = '?';
};
template <>
struct question_mark<wchar_t>
{
static wchar_t const value = L'?';
};
char const question_mark<char>::value;
wchar_t const question_mark<wchar_t>::value;
template <typename DestType, typename SrcType>
static
void
iconv_conv (std::basic_string<DestType> & result, char const * destenc,
SrcType const * src, std::size_t size, char const * srcenc)
{
iconv_handle cvt (destenc, srcenc);
if (cvt.handle == iconv_error_handle)
{
// TODO: Better error handling.
result.resize (0);
return;
}
typedef DestType outbuf_type;
typedef SrcType inbuf_type;
std::size_t result_size = size + size / 3 + 1;
result.resize (result_size);
char * inbuf = const_cast<char *>(reinterpret_cast<char const *>(src));
std::size_t inbytesleft = size * sizeof (inbuf_type);
char * outbuf = reinterpret_cast<char *>(&result[0]);
std::size_t outbytesleft = result_size * sizeof (outbuf_type);
std::size_t res;
std::size_t const error_retval = static_cast<std::size_t>(-1);
while (inbytesleft != 0)
{
res = cvt.do_iconv (&inbuf, &inbytesleft, &outbuf, &outbytesleft);
if (res == error_retval)
{
switch (errno)
{
case EILSEQ:
case EINVAL:
if (outbytesleft >= sizeof (outbuf_type))
{
if (inbytesleft > 0)
{
++inbuf;
inbytesleft -= sizeof (inbuf_type);
}
*outbuf = question_mark<outbuf_type>::value;
++outbuf;
outbytesleft -= sizeof (outbuf_type);
continue;
}
// Fall through.
case E2BIG:;
// Fall through.
}
std::size_t const outbuf_index = result_size;
result_size *= 2;
result.resize (result_size);
outbuf = reinterpret_cast<char *>(&result[0] + outbuf_index);
outbytesleft = (result_size - outbuf_index) * sizeof (outbuf_type);
}
else
result.resize (result_size - outbytesleft / sizeof (outbuf_type));
}
}
} // namespace
std::string
tostring (const std::wstring & src)
{
std::string ret;
iconv_conv (ret, "UTF-8", src.c_str (), src.size (), "WCHAR_T");
return ret;
}
std::string
tostring (wchar_t const * src)
{
assert (src);
std::string ret;
iconv_conv (ret, "UTF-8", src, std::wcslen (src), "WCHAR_T");
return ret;
}
std::wstring
towstring (const std::string& src)
{
std::wstring ret;
iconv_conv (ret, "WCHAR_T", src.c_str (), src.size (), "UTF-8");
return ret;
}
std::wstring
towstring (char const * src)
{
assert (src);
std::wstring ret;
iconv_conv (ret, "WCHAR_T", src, std::strlen (src), "UTF-8");
return ret;
}
#endif // LOG4CPLUS_WITH_ICONV
} // namespace helpers
} // namespace log4cplus
<|endoftext|> |
<commit_before>// moderngpu copyright (c) 2016, Sean Baxter http://www.moderngpu.com
#pragma once
#include <random>
#include <algorithm>
#include <cuda.h>
#include "launch_box.hxx"
BEGIN_MGPU_NAMESPACE
////////////////////////////////////////////////////////////////////////////////
// Launch a grid given a number of CTAs.
template<typename launch_box, typename func_t, typename... args_t>
void cta_launch(func_t f, int num_ctas, context_t& context, args_t... args) {
cta_dim_t cta = launch_box::cta_dim(context.ptx_version());
dim3 grid_dim(num_ctas);
if(context.ptx_version() < 30 && num_ctas > 65535)
grid_dim = dim3(256, div_up(num_ctas, 256));
launch_box_cta_k<launch_box, func_t>
<<<grid_dim, cta.nt, 0, context.stream()>>>(f, num_ctas, args...);
}
template<int nt, int vt = 1, typename func_t, typename... args_t>
void cta_launch(func_t f, int num_ctas, context_t& context, args_t... args) {
cta_launch<launch_params_t<nt, vt> >(f, num_ctas, context, args...);
}
////////////////////////////////////////////////////////////////////////////////
// Launch a grid given a number of work-items.
template<typename launch_box, typename func_t, typename... args_t>
void cta_transform(func_t f, int count, context_t& context, args_t... args) {
cta_dim_t cta = launch_box::cta_dim(context.ptx_version());
int num_ctas = div_up(count, cta.nv());
cta_launch<launch_box>(f, num_ctas, context, args...);
}
template<int nt, int vt = 1, typename func_t, typename... args_t>
void cta_transform(func_t f, int count, context_t& context, args_t... args) {
cta_transform<launch_params_t<nt, vt> >(f, count, context, args...);
}
////////////////////////////////////////////////////////////////////////////////
// Launch persistent CTAs and loop through num_ctas values.
template<typename launch_box, typename func_t, typename... args_t>
void cta_launch(func_t f, const int* num_tiles, context_t& context,
args_t... args) {
// Over-subscribe the device by a factor of 8.
// This reduces the penalty if we can't schedule all the CTAs to run
// concurrently.
int num_ctas = 8 * occupancy<launch_box>(f, context);
auto k = [=] MGPU_DEVICE(int tid, int cta, args_t... args) {
int count = *num_tiles;
while(cta < count) {
f(tid, cta, args...);
cta += num_ctas;
}
};
cta_launch<launch_box>(k, num_ctas, context, args...);
}
////////////////////////////////////////////////////////////////////////////////
// Ordinary transform launch. This uses the standard launch box mechanism
// so we can query its occupancy and other things.
namespace detail {
template<typename launch_t>
struct transform_f {
template<typename func_t, typename... args_t>
MGPU_DEVICE void operator()(int tid, int cta, func_t f,
size_t count, args_t... args) {
typedef typename launch_t::sm_ptx params_t;
enum { nt = params_t::nt, vt = params_t::vt, vt0 = params_t::vt0 };
range_t range = get_tile(cta, nt * vt, count);
strided_iterate<nt, vt, vt0>([=](int i, int j) {
f(range.begin + j, args...);
}, tid, range.count());
}
};
}
template<typename launch_t, typename func_t, typename... args_t>
void transform(func_t f, size_t count, context_t& context, args_t... args) {
cta_transform<launch_t>(detail::transform_f<launch_t>(), count,
context, f, count, args...);
}
template<size_t nt = 128, int vt = 1, typename func_t, typename... args_t>
void transform(func_t f, size_t count, context_t& context, args_t... args) {
transform<launch_params_t<nt, vt> >(f, count, context, args...);
}
END_MGPU_NAMESPACE
<commit_msg>Prevent cta-launch on 0 CTAs.<commit_after>// moderngpu copyright (c) 2016, Sean Baxter http://www.moderngpu.com
#pragma once
#include <random>
#include <algorithm>
#include <cuda.h>
#include "launch_box.hxx"
BEGIN_MGPU_NAMESPACE
////////////////////////////////////////////////////////////////////////////////
// Launch a grid given a number of CTAs.
template<typename launch_box, typename func_t, typename... args_t>
void cta_launch(func_t f, int num_ctas, context_t& context, args_t... args) {
cta_dim_t cta = launch_box::cta_dim(context.ptx_version());
dim3 grid_dim(num_ctas);
if(context.ptx_version() < 30 && num_ctas > 65535)
grid_dim = dim3(256, div_up(num_ctas, 256));
if(num_ctas)
launch_box_cta_k<launch_box, func_t>
<<<grid_dim, cta.nt, 0, context.stream()>>>(f, num_ctas, args...);
}
template<int nt, int vt = 1, typename func_t, typename... args_t>
void cta_launch(func_t f, int num_ctas, context_t& context, args_t... args) {
cta_launch<launch_params_t<nt, vt> >(f, num_ctas, context, args...);
}
////////////////////////////////////////////////////////////////////////////////
// Launch a grid given a number of work-items.
template<typename launch_box, typename func_t, typename... args_t>
void cta_transform(func_t f, int count, context_t& context, args_t... args) {
cta_dim_t cta = launch_box::cta_dim(context.ptx_version());
int num_ctas = div_up(count, cta.nv());
cta_launch<launch_box>(f, num_ctas, context, args...);
}
template<int nt, int vt = 1, typename func_t, typename... args_t>
void cta_transform(func_t f, int count, context_t& context, args_t... args) {
cta_transform<launch_params_t<nt, vt> >(f, count, context, args...);
}
////////////////////////////////////////////////////////////////////////////////
// Launch persistent CTAs and loop through num_ctas values.
template<typename launch_box, typename func_t, typename... args_t>
void cta_launch(func_t f, const int* num_tiles, context_t& context,
args_t... args) {
// Over-subscribe the device by a factor of 8.
// This reduces the penalty if we can't schedule all the CTAs to run
// concurrently.
int num_ctas = 8 * occupancy<launch_box>(f, context);
auto k = [=] MGPU_DEVICE(int tid, int cta, args_t... args) {
int count = *num_tiles;
while(cta < count) {
f(tid, cta, args...);
cta += num_ctas;
}
};
cta_launch<launch_box>(k, num_ctas, context, args...);
}
////////////////////////////////////////////////////////////////////////////////
// Ordinary transform launch. This uses the standard launch box mechanism
// so we can query its occupancy and other things.
namespace detail {
template<typename launch_t>
struct transform_f {
template<typename func_t, typename... args_t>
MGPU_DEVICE void operator()(int tid, int cta, func_t f,
size_t count, args_t... args) {
typedef typename launch_t::sm_ptx params_t;
enum { nt = params_t::nt, vt = params_t::vt, vt0 = params_t::vt0 };
range_t range = get_tile(cta, nt * vt, count);
strided_iterate<nt, vt, vt0>([=](int i, int j) {
f(range.begin + j, args...);
}, tid, range.count());
}
};
}
template<typename launch_t, typename func_t, typename... args_t>
void transform(func_t f, size_t count, context_t& context, args_t... args) {
cta_transform<launch_t>(detail::transform_f<launch_t>(), count,
context, f, count, args...);
}
template<size_t nt = 128, int vt = 1, typename func_t, typename... args_t>
void transform(func_t f, size_t count, context_t& context, args_t... args) {
transform<launch_params_t<nt, vt> >(f, count, context, args...);
}
END_MGPU_NAMESPACE
<|endoftext|> |
<commit_before>#include <GLFW/glfw3.h>
#include "imgui3D.h"
#include "cameraManipulator.h"
namespace ospray {
//! dedicated namespace for 3D glut viewer widget
namespace imgui3D {
// ------------------------------------------------------------------
// base manipulator
// ------------------------------------------------------------------
void Manipulator::motion(ImGui3DWidget *widget)
{
auto &state = widget->currButton;
if (state[GLFW_MOUSE_BUTTON_RIGHT] == GLFW_PRESS) {
dragRight(widget,widget->currMousePos,widget->lastMousePos);
} else if (state[GLFW_MOUSE_BUTTON_MIDDLE] == GLFW_PRESS) {
dragMiddle(widget,widget->currMousePos,widget->lastMousePos);
} else if (state[GLFW_MOUSE_BUTTON_LEFT] == GLFW_PRESS) {
dragLeft(widget,widget->currMousePos,widget->lastMousePos);
}
}
// ------------------------------------------------------------------
// INSPECT_CENTER manipulator
// ------------------------------------------------------------------
InspectCenter::InspectCenter(ImGui3DWidget *widget)
: Manipulator(widget)
, pivot(ospcommon::center(widget->worldBounds))
{}
void InspectCenter::rotate(float du, float dv)
{
ImGui3DWidget::ViewPort &cam = widget->viewPort;
const vec3f pivot = widget->viewPort.at;//center(widget->worldBounds);
AffineSpace3fa xfm
= AffineSpace3fa::translate(pivot)
* AffineSpace3fa::rotate(cam.frame.l.vx,-dv)
* AffineSpace3fa::rotate(cam.frame.l.vz,-du)
* AffineSpace3fa::translate(-pivot);
cam.frame = xfm * cam.frame;
cam.from = xfmPoint(xfm,cam.from);
cam.at = xfmPoint(xfm,cam.at);
cam.snapFrameUp();
cam.modified = true;
}
/*! INSPECT_CENTER::RightButton: move lookfrom/viewPort positoin
forward/backward on right mouse button */
void InspectCenter::dragRight(ImGui3DWidget *widget,
const vec2i &to, const vec2i &from)
{
ImGui3DWidget::ViewPort &cam = widget->viewPort;
float fwd =
#ifdef INVERT_RMB
#else
-
#endif
(to.y - from.y) * 4 * widget->motionSpeed;
// * length(widget->worldBounds.size());
float oldDist = length(cam.at - cam.from);
float newDist = oldDist - fwd;
if (newDist < 1e-3f)
return;
cam.from = cam.at - newDist * cam.frame.l.vy;
cam.frame.p = cam.from;
cam.modified = true;
}
/*! INSPECT_CENTER::MiddleButton: move lookat/center of interest
forward/backward on middle mouse button */
void InspectCenter::dragMiddle(ImGui3DWidget *widget,
const vec2i &to, const vec2i &from)
{
ImGui3DWidget::ViewPort &cam = widget->viewPort;
float du = (to.x - from.x);
float dv = (to.y - from.y);
AffineSpace3fa xfm =
AffineSpace3fa::translate(widget->motionSpeed * dv * cam.frame.l.vz )
* AffineSpace3fa::translate(-1.0f * widget->motionSpeed
* du * cam.frame.l.vx);
cam.frame = xfm * cam.frame;
cam.from = xfmPoint(xfm, cam.from);
cam.at = xfmPoint(xfm, cam.at);
cam.modified = true;
}
void InspectCenter::dragLeft(ImGui3DWidget *widget,
const vec2i &to, const vec2i &from)
{
ImGui3DWidget::ViewPort &cam = widget->viewPort;
float du = (to.x - from.x) * widget->rotateSpeed;
float dv = (to.y - from.y) * widget->rotateSpeed;
const vec3f pivot = cam.at;
AffineSpace3fa xfm
= AffineSpace3fa::translate(pivot)
* AffineSpace3fa::rotate(cam.frame.l.vx,-dv)
* AffineSpace3fa::rotate(cam.frame.l.vz,-du)
* AffineSpace3fa::translate(-pivot);
cam.frame = xfm * cam.frame;
cam.from = xfmPoint(xfm,cam.from);
cam.at = xfmPoint(xfm,cam.at);
if (!widget->upAnchored)
cam.snapViewUp();
cam.snapFrameUp();
cam.modified = true;
}
// ------------------------------------------------------------------
// MOVE_MOVE manipulator - TODO.
// ------------------------------------------------------------------
void MoveMode::dragRight(ImGui3DWidget *widget,
const vec2i &to, const vec2i &from)
{
ImGui3DWidget::ViewPort &cam = widget->viewPort;
float fwd =
#ifdef INVERT_RMB
#else
-
#endif
(to.y - from.y) * 4 * widget->motionSpeed;
cam.from = cam.from + fwd * cam.frame.l.vy;
cam.at = cam.at + fwd * cam.frame.l.vy;
cam.frame.p = cam.from;
cam.modified = true;
}
/*! todo */
void MoveMode::dragMiddle(ImGui3DWidget *widget,
const vec2i &to, const vec2i &from)
{
ImGui3DWidget::ViewPort &cam = widget->viewPort;
float du = (to.x - from.x);
float dv = (to.y - from.y);
auto xfm =
AffineSpace3fa::translate(widget->motionSpeed * dv * cam.frame.l.vz ) *
AffineSpace3fa::translate(-1.0f * widget->motionSpeed * du * cam.frame.l.vx);
cam.frame = xfm * cam.frame;
cam.from = xfmPoint(xfm, cam.from);
cam.at = xfmPoint(xfm, cam.at);
cam.modified = true;
}
void MoveMode::dragLeft(ImGui3DWidget *widget,
const vec2i &to, const vec2i &from)
{
ImGui3DWidget::ViewPort &cam = widget->viewPort;
float du = (to.x - from.x) * widget->rotateSpeed;
float dv = (to.y - from.y) * widget->rotateSpeed;
const vec3f pivot = cam.from; //center(widget->worldBounds);
AffineSpace3fa xfm
= AffineSpace3fa::translate(pivot)
* AffineSpace3fa::rotate(cam.frame.l.vx,-dv)
* AffineSpace3fa::rotate(cam.frame.l.vz,-du)
* AffineSpace3fa::translate(-pivot);
cam.frame = xfm * cam.frame;
cam.from = xfmPoint(xfm,cam.from);
cam.at = xfmPoint(xfm,cam.at);
cam.snapFrameUp();
cam.modified = true;
}
}
}
<commit_msg>example viewer camera: prevent instabilities at the poles<commit_after>#include <GLFW/glfw3.h>
#include "imgui3D.h"
#include "cameraManipulator.h"
namespace ospray {
//! dedicated namespace for 3D glut viewer widget
namespace imgui3D {
// ------------------------------------------------------------------
// base manipulator
// ------------------------------------------------------------------
void Manipulator::motion(ImGui3DWidget *widget)
{
auto &state = widget->currButton;
if (state[GLFW_MOUSE_BUTTON_RIGHT] == GLFW_PRESS) {
dragRight(widget,widget->currMousePos,widget->lastMousePos);
} else if (state[GLFW_MOUSE_BUTTON_MIDDLE] == GLFW_PRESS) {
dragMiddle(widget,widget->currMousePos,widget->lastMousePos);
} else if (state[GLFW_MOUSE_BUTTON_LEFT] == GLFW_PRESS) {
dragLeft(widget,widget->currMousePos,widget->lastMousePos);
}
}
// ------------------------------------------------------------------
// INSPECT_CENTER manipulator
// ------------------------------------------------------------------
InspectCenter::InspectCenter(ImGui3DWidget *widget)
: Manipulator(widget)
, pivot(ospcommon::center(widget->worldBounds))
{}
void InspectCenter::rotate(float du, float dv)
{
ImGui3DWidget::ViewPort &cam = widget->viewPort;
const vec3f pivot = widget->viewPort.at;//center(widget->worldBounds);
AffineSpace3fa xfm
= AffineSpace3fa::translate(pivot)
* AffineSpace3fa::rotate(cam.frame.l.vx,-dv)
* AffineSpace3fa::rotate(cam.frame.l.vz,-du)
* AffineSpace3fa::translate(-pivot);
cam.frame = xfm * cam.frame;
cam.from = xfmPoint(xfm,cam.from);
cam.at = xfmPoint(xfm,cam.at);
cam.snapFrameUp();
cam.modified = true;
}
/*! INSPECT_CENTER::RightButton: move lookfrom/viewPort positoin
forward/backward on right mouse button */
void InspectCenter::dragRight(ImGui3DWidget *widget,
const vec2i &to, const vec2i &from)
{
ImGui3DWidget::ViewPort &cam = widget->viewPort;
float fwd =
#ifdef INVERT_RMB
#else
-
#endif
(to.y - from.y) * 4 * widget->motionSpeed;
// * length(widget->worldBounds.size());
float oldDist = length(cam.at - cam.from);
float newDist = oldDist - fwd;
if (newDist < 1e-3f)
return;
cam.from = cam.at - newDist * cam.frame.l.vy;
cam.frame.p = cam.from;
cam.modified = true;
}
/*! INSPECT_CENTER::MiddleButton: move lookat/center of interest
forward/backward on middle mouse button */
void InspectCenter::dragMiddle(ImGui3DWidget *widget,
const vec2i &to, const vec2i &from)
{
ImGui3DWidget::ViewPort &cam = widget->viewPort;
float du = (to.x - from.x);
float dv = (to.y - from.y);
AffineSpace3fa xfm =
AffineSpace3fa::translate(widget->motionSpeed * dv * cam.frame.l.vz )
* AffineSpace3fa::translate(-1.0f * widget->motionSpeed
* du * cam.frame.l.vx);
cam.frame = xfm * cam.frame;
cam.from = xfmPoint(xfm, cam.from);
cam.at = xfmPoint(xfm, cam.at);
cam.modified = true;
}
void InspectCenter::dragLeft(ImGui3DWidget *widget,
const vec2i &to, const vec2i &from)
{
ImGui3DWidget::ViewPort &cam = widget->viewPort;
float du = (to.x - from.x) * widget->rotateSpeed;
float dv = (to.y - from.y) * widget->rotateSpeed;
if (widget->upAnchored) {
const float theta = std::acos(dot(cam.up, normalize(cam.from-cam.at)));
// prevent instabilities at the poles by enforcing a minimum angle to up
dv = clamp(dv, theta-float(pi)+0.05f, theta-0.05f);
}
const vec3f pivot = cam.at;
AffineSpace3fa xfm
= AffineSpace3fa::translate(pivot)
* AffineSpace3fa::rotate(cam.frame.l.vx,-dv)
* AffineSpace3fa::rotate(cam.frame.l.vz,-du)
* AffineSpace3fa::translate(-pivot);
cam.frame = xfm * cam.frame;
cam.from = xfmPoint(xfm,cam.from);
cam.at = xfmPoint(xfm,cam.at);
if (!widget->upAnchored)
cam.snapViewUp();
cam.snapFrameUp();
cam.modified = true;
}
// ------------------------------------------------------------------
// MOVE_MOVE manipulator - TODO.
// ------------------------------------------------------------------
void MoveMode::dragRight(ImGui3DWidget *widget,
const vec2i &to, const vec2i &from)
{
ImGui3DWidget::ViewPort &cam = widget->viewPort;
float fwd =
#ifdef INVERT_RMB
#else
-
#endif
(to.y - from.y) * 4 * widget->motionSpeed;
cam.from = cam.from + fwd * cam.frame.l.vy;
cam.at = cam.at + fwd * cam.frame.l.vy;
cam.frame.p = cam.from;
cam.modified = true;
}
/*! todo */
void MoveMode::dragMiddle(ImGui3DWidget *widget,
const vec2i &to, const vec2i &from)
{
ImGui3DWidget::ViewPort &cam = widget->viewPort;
float du = (to.x - from.x);
float dv = (to.y - from.y);
auto xfm =
AffineSpace3fa::translate(widget->motionSpeed * dv * cam.frame.l.vz ) *
AffineSpace3fa::translate(-1.0f * widget->motionSpeed * du * cam.frame.l.vx);
cam.frame = xfm * cam.frame;
cam.from = xfmPoint(xfm, cam.from);
cam.at = xfmPoint(xfm, cam.at);
cam.modified = true;
}
void MoveMode::dragLeft(ImGui3DWidget *widget,
const vec2i &to, const vec2i &from)
{
ImGui3DWidget::ViewPort &cam = widget->viewPort;
float du = (to.x - from.x) * widget->rotateSpeed;
float dv = (to.y - from.y) * widget->rotateSpeed;
const vec3f pivot = cam.from; //center(widget->worldBounds);
AffineSpace3fa xfm
= AffineSpace3fa::translate(pivot)
* AffineSpace3fa::rotate(cam.frame.l.vx,-dv)
* AffineSpace3fa::rotate(cam.frame.l.vz,-du)
* AffineSpace3fa::translate(-pivot);
cam.frame = xfm * cam.frame;
cam.from = xfmPoint(xfm,cam.from);
cam.at = xfmPoint(xfm,cam.at);
cam.snapFrameUp();
cam.modified = true;
}
}
}
<|endoftext|> |
<commit_before>// -*-c++-*-
#include <osgProducer/Viewer>
#include <osgDB/ReadFile>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/StateSet>
#include <osg/Material>
#include <osg/Texture2D>
#include <osg/TextureRectangle>
#include <osg/TexMat>
#include <osg/CullFace>
#include <osg/ImageStream>
#include <osgGA/TrackballManipulator>
osg::ImageStream* s_imageStream = 0;
class PostSwapFinishCallback : public Producer::Camera::Callback
{
public:
PostSwapFinishCallback() {}
virtual void operator()(const Producer::Camera& camera)
{
// osg::Timer_t start_tick = osg::Timer::instance()->tick();
osgProducer::OsgSceneHandler* sh = const_cast<osgProducer::OsgSceneHandler*>(dynamic_cast<const osgProducer::OsgSceneHandler*>(camera.getSceneHandler()));
if (s_imageStream && s_imageStream->getPixelBufferObject()) s_imageStream->getPixelBufferObject()->compileBuffer(*(sh->getSceneView()->getState()));
// glFinish();
//osg::notify(osg::NOTICE)<<"callback after PBO "<<osg::Timer::instance()->delta_m(start_tick,osg::Timer::instance()->tick())<<"ms"<<std::endl;
}
};
class MovieEventHandler : public osgGA::GUIEventHandler
{
public:
MovieEventHandler() {}
void set(osg::Node* node);
virtual void accept(osgGA::GUIEventHandlerVisitor& v) { v.visit(*this); }
virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&);
virtual void getUsage(osg::ApplicationUsage& usage) const;
typedef std::vector< osg::ref_ptr<osg::ImageStream> > ImageStreamList;
protected:
virtual ~MovieEventHandler() {}
class FindImageStreamsVisitor : public osg::NodeVisitor
{
public:
FindImageStreamsVisitor(ImageStreamList& imageStreamList):
_imageStreamList(imageStreamList) {}
virtual void apply(osg::Geode& geode)
{
apply(geode.getStateSet());
for(unsigned int i=0;i<geode.getNumDrawables();++i)
{
apply(geode.getDrawable(i)->getStateSet());
}
traverse(geode);
}
virtual void apply(osg::Node& node)
{
apply(node.getStateSet());
traverse(node);
}
inline void apply(osg::StateSet* stateset)
{
if (!stateset) return;
osg::StateAttribute* attr = stateset->getTextureAttribute(0,osg::StateAttribute::TEXTURE);
if (attr)
{
osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(attr);
if (texture2D) apply(dynamic_cast<osg::ImageStream*>(texture2D->getImage()));
osg::TextureRectangle* textureRec = dynamic_cast<osg::TextureRectangle*>(attr);
if (textureRec) apply(dynamic_cast<osg::ImageStream*>(textureRec->getImage()));
}
}
inline void apply(osg::ImageStream* imagestream)
{
if (imagestream)
{
_imageStreamList.push_back(imagestream);
s_imageStream = imagestream;
}
}
ImageStreamList& _imageStreamList;
};
ImageStreamList _imageStreamList;
};
void MovieEventHandler::set(osg::Node* node)
{
_imageStreamList.clear();
if (node)
{
FindImageStreamsVisitor fisv(_imageStreamList);
node->accept(fisv);
}
}
bool MovieEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
{
switch(ea.getEventType())
{
case(osgGA::GUIEventAdapter::KEYDOWN):
{
if (ea.getKey()=='s')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Play"<<std::endl;
(*itr)->play();
}
return true;
}
else if (ea.getKey()=='p')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Pause"<<std::endl;
(*itr)->pause();
}
return true;
}
else if (ea.getKey()=='r')
{
return true;
}
else if (ea.getKey()=='l')
{
return true;
}
return false;
}
default:
return false;
}
}
void MovieEventHandler::getUsage(osg::ApplicationUsage& usage) const
{
usage.addKeyboardMouseBinding("p","Pause movie");
usage.addKeyboardMouseBinding("s","Play movie");
usage.addKeyboardMouseBinding("r","Start movie");
usage.addKeyboardMouseBinding("l","Toggle looping of movie");
}
osg::Geometry* createTexturedQuadGeometry(const osg::Vec3& pos,float width,float height, osg::Image* image)
{
bool useTextureRectangle = true;
if (useTextureRectangle)
{
osg::Geometry* pictureQuad = createTexturedQuadGeometry(pos,
osg::Vec3(width,0.0f,0.0f),
osg::Vec3(0.0f,0.0f,height),
0.0f,image->t(), image->s(),0.0f);
pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,
new osg::TextureRectangle(image),
osg::StateAttribute::ON);
return pictureQuad;
}
else
{
osg::Geometry* pictureQuad = createTexturedQuadGeometry(pos,
osg::Vec3(width,0.0f,0.0f),
osg::Vec3(0.0f,0.0f,height),
0.0f,0.0f, 1.0f,1.0f);
pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,
new osg::Texture2D(image),
osg::StateAttribute::ON);
return pictureQuad;
}
}
int main(int argc, char** argv)
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// register the handler to add keyboard and mosue handling.
MovieEventHandler* meh = new MovieEventHandler();
viewer.getEventHandlerList().push_front(meh);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
osg::Geode* geode = new osg::Geode;
osg::Vec3 pos(0.0f,0.0f,0.0f);
for(int i=1;i<arguments.argc();++i)
{
if (arguments.isString(i))
{
osg::Image* image = osgDB::readImageFile(arguments[i]);
osg::ImageStream* imagestream = dynamic_cast<osg::ImageStream*>(image);
if (imagestream) imagestream->play();
geode->addDrawable(createTexturedQuadGeometry(pos,image->s(),image->t(),image));
geode->getOrCreateStateSet()->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
pos.z() += image->t()*1.5f;
}
}
// pass the model to the MovieEventHandler so it can pick out ImageStream's to manipulate.
meh->set(geode);
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
if (arguments.argc()<=1)
{
arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
}
// set up a post swap callback to flush deleted GL objects and compile new GL objects
for(unsigned int cameraNum=0;cameraNum<viewer.getNumberOfCameras();++cameraNum)
{
Producer::Camera* camera=viewer.getCamera(cameraNum);
camera->addPostSwapCallback(new PostSwapFinishCallback());
}
// set the scene to render
viewer.setSceneData(geode);
// create the windows and run the threads.
viewer.realize();
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
return 0;
}
<commit_msg>Improved handling of unsupported formats<commit_after>// -*-c++-*-
#include <osgProducer/Viewer>
#include <osgDB/ReadFile>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/StateSet>
#include <osg/Material>
#include <osg/Texture2D>
#include <osg/TextureRectangle>
#include <osg/TexMat>
#include <osg/CullFace>
#include <osg/ImageStream>
#include <osgGA/TrackballManipulator>
osg::ImageStream* s_imageStream = 0;
class PostSwapFinishCallback : public Producer::Camera::Callback
{
public:
PostSwapFinishCallback() {}
virtual void operator()(const Producer::Camera& camera)
{
// osg::Timer_t start_tick = osg::Timer::instance()->tick();
osgProducer::OsgSceneHandler* sh = const_cast<osgProducer::OsgSceneHandler*>(dynamic_cast<const osgProducer::OsgSceneHandler*>(camera.getSceneHandler()));
if (s_imageStream && s_imageStream->getPixelBufferObject()) s_imageStream->getPixelBufferObject()->compileBuffer(*(sh->getSceneView()->getState()));
// glFinish();
//osg::notify(osg::NOTICE)<<"callback after PBO "<<osg::Timer::instance()->delta_m(start_tick,osg::Timer::instance()->tick())<<"ms"<<std::endl;
}
};
class MovieEventHandler : public osgGA::GUIEventHandler
{
public:
MovieEventHandler() {}
void set(osg::Node* node);
virtual void accept(osgGA::GUIEventHandlerVisitor& v) { v.visit(*this); }
virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&);
virtual void getUsage(osg::ApplicationUsage& usage) const;
typedef std::vector< osg::ref_ptr<osg::ImageStream> > ImageStreamList;
protected:
virtual ~MovieEventHandler() {}
class FindImageStreamsVisitor : public osg::NodeVisitor
{
public:
FindImageStreamsVisitor(ImageStreamList& imageStreamList):
_imageStreamList(imageStreamList) {}
virtual void apply(osg::Geode& geode)
{
apply(geode.getStateSet());
for(unsigned int i=0;i<geode.getNumDrawables();++i)
{
apply(geode.getDrawable(i)->getStateSet());
}
traverse(geode);
}
virtual void apply(osg::Node& node)
{
apply(node.getStateSet());
traverse(node);
}
inline void apply(osg::StateSet* stateset)
{
if (!stateset) return;
osg::StateAttribute* attr = stateset->getTextureAttribute(0,osg::StateAttribute::TEXTURE);
if (attr)
{
osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(attr);
if (texture2D) apply(dynamic_cast<osg::ImageStream*>(texture2D->getImage()));
osg::TextureRectangle* textureRec = dynamic_cast<osg::TextureRectangle*>(attr);
if (textureRec) apply(dynamic_cast<osg::ImageStream*>(textureRec->getImage()));
}
}
inline void apply(osg::ImageStream* imagestream)
{
if (imagestream)
{
_imageStreamList.push_back(imagestream);
s_imageStream = imagestream;
}
}
ImageStreamList& _imageStreamList;
};
ImageStreamList _imageStreamList;
};
void MovieEventHandler::set(osg::Node* node)
{
_imageStreamList.clear();
if (node)
{
FindImageStreamsVisitor fisv(_imageStreamList);
node->accept(fisv);
}
}
bool MovieEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
{
switch(ea.getEventType())
{
case(osgGA::GUIEventAdapter::KEYDOWN):
{
if (ea.getKey()=='s')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Play"<<std::endl;
(*itr)->play();
}
return true;
}
else if (ea.getKey()=='p')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Pause"<<std::endl;
(*itr)->pause();
}
return true;
}
else if (ea.getKey()=='r')
{
return true;
}
else if (ea.getKey()=='l')
{
return true;
}
return false;
}
default:
return false;
}
}
void MovieEventHandler::getUsage(osg::ApplicationUsage& usage) const
{
usage.addKeyboardMouseBinding("p","Pause movie");
usage.addKeyboardMouseBinding("s","Play movie");
usage.addKeyboardMouseBinding("r","Start movie");
usage.addKeyboardMouseBinding("l","Toggle looping of movie");
}
osg::Geometry* createTexturedQuadGeometry(const osg::Vec3& pos,float width,float height, osg::Image* image)
{
bool useTextureRectangle = true;
if (useTextureRectangle)
{
osg::Geometry* pictureQuad = createTexturedQuadGeometry(pos,
osg::Vec3(width,0.0f,0.0f),
osg::Vec3(0.0f,0.0f,height),
0.0f,image->t(), image->s(),0.0f);
pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,
new osg::TextureRectangle(image),
osg::StateAttribute::ON);
return pictureQuad;
}
else
{
osg::Geometry* pictureQuad = createTexturedQuadGeometry(pos,
osg::Vec3(width,0.0f,0.0f),
osg::Vec3(0.0f,0.0f,height),
0.0f,0.0f, 1.0f,1.0f);
pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,
new osg::Texture2D(image),
osg::StateAttribute::ON);
return pictureQuad;
}
}
int main(int argc, char** argv)
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// register the handler to add keyboard and mosue handling.
MovieEventHandler* meh = new MovieEventHandler();
viewer.getEventHandlerList().push_front(meh);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
osg::ref_ptr<osg::Geode> geode = new osg::Geode;
osg::Vec3 pos(0.0f,0.0f,0.0f);
for(int i=1;i<arguments.argc();++i)
{
if (arguments.isString(i))
{
osg::Image* image = osgDB::readImageFile(arguments[i]);
osg::ImageStream* imagestream = dynamic_cast<osg::ImageStream*>(image);
if (imagestream) imagestream->play();
if (image)
{
geode->addDrawable(createTexturedQuadGeometry(pos,image->s(),image->t(),image));
geode->getOrCreateStateSet()->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
pos.z() += image->t()*1.5f;
}
else
{
std::cout<<"Unable to read file "<<arguments[i]<<std::endl;
}
}
}
if (geode->getNumDrawables()==0)
{
// nothing loaded.
return 1;
}
// pass the model to the MovieEventHandler so it can pick out ImageStream's to manipulate.
meh->set(geode.get());
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
if (arguments.argc()<=1)
{
arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
}
// set up a post swap callback to flush deleted GL objects and compile new GL objects
for(unsigned int cameraNum=0;cameraNum<viewer.getNumberOfCameras();++cameraNum)
{
Producer::Camera* camera=viewer.getCamera(cameraNum);
camera->addPostSwapCallback(new PostSwapFinishCallback());
}
// set the scene to render
viewer.setSceneData(geode.get());
// create the windows and run the threads.
viewer.realize();
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
return 0;
}
<|endoftext|> |
<commit_before>#include "APSEthernetPacket.h"
APSEthernetPacket::APSEthernetPacket() : header{{}, {}, APS_PROTO, 0, {0}, 0}, payload(0){};
APSEthernetPacket::APSEthernetPacket(const MACAddr & destMAC, const MACAddr & srcMAC, APSCommand_t command, const uint32_t & addr) :
header{destMAC, srcMAC, APS_PROTO, 0, command, addr}, payload(0){};
APSEthernetPacket::APSEthernetPacket(const u_char * packet, size_t packetLength){
/*
Create a packet from a byte array returned by pcap.
*/
//Helper function to turn two network bytes into a uint16_t assuming big-endian network byte order
auto bytes2uint16 = [&packet](size_t offset) -> uint16_t {return (packet[offset] << 8) + packet[offset+1];};
auto bytes2uint32 = [&packet](size_t offset) -> uint32_t {return (packet[offset] << 24) + (packet[offset+1] << 16) + (packet[offset+2] << 8) + packet[offset+3] ;};
std::copy(packet, packet+6, header.dest.addr.begin());
std::copy(packet+6, packet+12, header.src.addr.begin());
header.frameType = bytes2uint16(12);
header.seqNum = bytes2uint16(14);
header.command.packed = bytes2uint32(16);
//TODO: not all packets have an address; if-block on command type
header.addr = bytes2uint32(20);
payload.resize(packetLength - NUM_HEADER_BYTES,0);
std::copy(packet+24, packet+packetLength, payload.begin());
}
vector<uint8_t> APSEthernetPacket::serialize() const {
/*
* Serialize a packet to a vector of bytes for transmission.
* Handle host to network byte ordering here
*/
vector<uint8_t> outVec;
outVec.resize(NUM_HEADER_BYTES + payload.size());
//Push on the destination and source mac address
auto insertPt = outVec.begin();
std::copy(header.dest.addr.begin(), header.dest.addr.end(), insertPt); insertPt += 6;
std::copy(header.src.addr.begin(), header.src.addr.end(), insertPt); insertPt += 6;
//Push on ethernet protocol
uint16_t myuint16;
uint8_t * start;
start = reinterpret_cast<uint8_t*>(&myuint16);
myuint16 = htons(header.frameType);
std::copy(start, start+2, insertPt); insertPt += 2;
//Sequence number
myuint16 = htons(header.seqNum);
std::copy(start, start+2, insertPt); insertPt += 2;
//Command
uint32_t myuint32;
start = reinterpret_cast<uint8_t*>(&myuint32);
myuint32 = htonl(header.command.packed);
std::copy(start, start+4, insertPt); insertPt += 4;
//Address
if (needs_address(APS_COMMANDS(header.command.cmd))){
myuint32 = htonl(header.addr);
std::copy(start, start+4, insertPt); insertPt += 4;
}
else{
outVec.resize(outVec.size()-4);
}
//Data
std::copy(payload.begin(), payload.end(), insertPt);
return outVec;
}
size_t APSEthernetPacket::numBytes() const{
return needs_address(APS_COMMANDS(header.command.cmd)) ? NUM_HEADER_BYTES + payload.size() : NUM_HEADER_BYTES - 4 + payload.size() ;
}
APSEthernetPacket APSEthernetPacket::create_broadcast_packet(){
/*
* Helper function to put together a broadcast status packet that all APS units should respond to.
*/
APSEthernetPacket myPacket;
//Put the broadcast FF:FF:FF:FF:FF:FF in the MAC destination address
std::fill(myPacket.header.dest.addr.begin(), myPacket.header.dest.addr.end(), 0xFF);
//Fill out the host register status command
myPacket.header.command.ack = 0;
myPacket.header.command.r_w = 1;
myPacket.header.command.cmd = static_cast<uint32_t>(APS_COMMANDS::STATUS);
myPacket.header.command.mode_stat = APS_STATUS_HOST;
myPacket.header.command.cnt = 0x10; //minimum length packet
return myPacket;
}
<commit_msg>Fix missing address in packet deserialization.<commit_after>#include "APSEthernetPacket.h"
APSEthernetPacket::APSEthernetPacket() : header{{}, {}, APS_PROTO, 0, {0}, 0}, payload(0){};
APSEthernetPacket::APSEthernetPacket(const MACAddr & destMAC, const MACAddr & srcMAC, APSCommand_t command, const uint32_t & addr) :
header{destMAC, srcMAC, APS_PROTO, 0, command, addr}, payload(0){};
APSEthernetPacket::APSEthernetPacket(const u_char * packet, size_t packetLength){
/*
Create a packet from a byte array returned by pcap.
*/
//Helper function to turn two network bytes into a uint16_t assuming big-endian network byte order
auto bytes2uint16 = [&packet](size_t offset) -> uint16_t {return (packet[offset] << 8) + packet[offset+1];};
auto bytes2uint32 = [&packet](size_t offset) -> uint32_t {return (packet[offset] << 24) + (packet[offset+1] << 16) + (packet[offset+2] << 8) + packet[offset+3] ;};
std::copy(packet, packet+6, header.dest.addr.begin());
std::copy(packet+6, packet+12, header.src.addr.begin());
header.frameType = bytes2uint16(12);
header.seqNum = bytes2uint16(14);
header.command.packed = bytes2uint32(16);
//not all return packets have an address; if-block on command type
if (needs_address(APS_COMMANDS(header.command.cmd))){
header.addr = bytes2uint32(20);
payload.resize(packetLength - NUM_HEADER_BYTES, 0);
std::copy(packet+24, packet+packetLength, payload.begin());
}
else{
payload.resize(packetLength - (NUM_HEADER_BYTES-4), 0);
std::copy(packet+2, packet+packetLength, payload.begin());
}
}
vector<uint8_t> APSEthernetPacket::serialize() const {
/*
* Serialize a packet to a vector of bytes for transmission.
* Handle host to network byte ordering here
*/
vector<uint8_t> outVec;
outVec.resize(NUM_HEADER_BYTES + payload.size());
//Push on the destination and source mac address
auto insertPt = outVec.begin();
std::copy(header.dest.addr.begin(), header.dest.addr.end(), insertPt); insertPt += 6;
std::copy(header.src.addr.begin(), header.src.addr.end(), insertPt); insertPt += 6;
//Push on ethernet protocol
uint16_t myuint16;
uint8_t * start;
start = reinterpret_cast<uint8_t*>(&myuint16);
myuint16 = htons(header.frameType);
std::copy(start, start+2, insertPt); insertPt += 2;
//Sequence number
myuint16 = htons(header.seqNum);
std::copy(start, start+2, insertPt); insertPt += 2;
//Command
uint32_t myuint32;
start = reinterpret_cast<uint8_t*>(&myuint32);
myuint32 = htonl(header.command.packed);
std::copy(start, start+4, insertPt); insertPt += 4;
//Address
if (needs_address(APS_COMMANDS(header.command.cmd))){
myuint32 = htonl(header.addr);
std::copy(start, start+4, insertPt); insertPt += 4;
}
else{
outVec.resize(outVec.size()-4);
}
//Data
std::copy(payload.begin(), payload.end(), insertPt);
return outVec;
}
size_t APSEthernetPacket::numBytes() const{
return needs_address(APS_COMMANDS(header.command.cmd)) ? NUM_HEADER_BYTES + payload.size() : NUM_HEADER_BYTES - 4 + payload.size() ;
}
APSEthernetPacket APSEthernetPacket::create_broadcast_packet(){
/*
* Helper function to put together a broadcast status packet that all APS units should respond to.
*/
APSEthernetPacket myPacket;
//Put the broadcast FF:FF:FF:FF:FF:FF in the MAC destination address
std::fill(myPacket.header.dest.addr.begin(), myPacket.header.dest.addr.end(), 0xFF);
//Fill out the host register status command
myPacket.header.command.ack = 0;
myPacket.header.command.r_w = 1;
myPacket.header.command.cmd = static_cast<uint32_t>(APS_COMMANDS::STATUS);
myPacket.header.command.mode_stat = APS_STATUS_HOST;
myPacket.header.command.cnt = 0x10; //minimum length packet
return myPacket;
}
<|endoftext|> |
<commit_before>/* Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// This file contains the hard-coded parameters from the training workflow. If
// you update the binary model, you may need to update the variables below as
// well.
#include "task_context_params.h"
#include "task_context.h"
namespace chrome_lang_id {
void TaskContextParams::ToTaskContext(TaskContext *context) {
context->SetParameter("language_identifier_features",
kLanguageIdentifierFeatures);
context->SetParameter("language_identifier_embedding_names",
kLanguageIdentifierEmbeddingNames);
context->SetParameter("language_identifier_embedding_dims",
kLanguageIdentifierEmbeddingDims);
}
int TaskContextParams::GetNumLanguages() {
int i = 0;
while (kLanguageNames[i] != nullptr) {
i++;
}
return i;
}
const char *const TaskContextParams::kLanguageNames[] = {
"eo", "co", "eu", "ta", "de", "mt", "ps", "te", "su", "uz", "zh-Latn", "ne",
"nl", "sw", "sq", "hmn", "ja", "no", "mn", "so", "ko", "kk", "sl", "ig",
"mr", "th", "zu", "ml", "hr", "bs", "lo", "sd", "cy", "hy", "uk", "pt",
"lv", "iw", "cs", "vi", "jv", "be", "km", "mk", "tr", "fy", "am", "zh",
"da", "sv", "fi", "ht", "af", "la", "id", "fil", "sm", "ca", "el", "ka",
"sr", "it", "sk", "ru", "ru-Latn", "bg", "ny", "fa", "haw", "gl", "et",
"ms", "gd", "bg-Latn", "ha", "is", "ur", "mi", "hi", "bn", "hi-Latn", "fr",
"yi", "hu", "xh", "my", "tg", "ro", "ar", "lb", "el-Latn", "st", "ceb",
"kn", "az", "si", "ky", "mg", "en", "gu", "es", "pl", "ja-Latn", "ga", "lt",
"sn", "yo", "pa", "ku",
// last element must be nullptr
nullptr,
};
const char TaskContextParams::kLanguageIdentifierFeatures[] = R"(
continuous-bag-of-ngrams(include_terminators=true,include_spaces=false,
use_equal_weight=false,id_dim=1000,size=2);continuous-bag-of-ngrams(
include_terminators=true,include_spaces=false,use_equal_weight=false,
id_dim=5000,size=4);continuous-bag-of-relevant-scripts;script;
continuous-bag-of-ngrams(include_terminators=true,include_spaces=false,
use_equal_weight=false,id_dim=5000,size=3);continuous-bag-of-ngrams(
include_terminators=true,include_spaces=false,use_equal_weight=false,
id_dim=100,size=1)
)";
const char TaskContextParams::kLanguageIdentifierEmbeddingNames[] =
"bigrams;quadgrams;relevant-scripts;text-script;trigrams;unigrams";
const char TaskContextParams::kLanguageIdentifierEmbeddingDims[] =
"16;16;8;8;16;16";
} // namespace chrome_lang_id
<commit_msg>Formatting feature specifications<commit_after>/* Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// This file contains the hard-coded parameters from the training workflow. If
// you update the binary model, you may need to update the variables below as
// well.
#include "task_context_params.h"
#include "task_context.h"
namespace chrome_lang_id {
void TaskContextParams::ToTaskContext(TaskContext *context) {
context->SetParameter("language_identifier_features",
kLanguageIdentifierFeatures);
context->SetParameter("language_identifier_embedding_names",
kLanguageIdentifierEmbeddingNames);
context->SetParameter("language_identifier_embedding_dims",
kLanguageIdentifierEmbeddingDims);
}
int TaskContextParams::GetNumLanguages() {
int i = 0;
while (kLanguageNames[i] != nullptr) {
i++;
}
return i;
}
const char *const TaskContextParams::kLanguageNames[] = {
"eo", "co", "eu", "ta", "de", "mt", "ps", "te", "su", "uz", "zh-Latn", "ne",
"nl", "sw", "sq", "hmn", "ja", "no", "mn", "so", "ko", "kk", "sl", "ig",
"mr", "th", "zu", "ml", "hr", "bs", "lo", "sd", "cy", "hy", "uk", "pt",
"lv", "iw", "cs", "vi", "jv", "be", "km", "mk", "tr", "fy", "am", "zh",
"da", "sv", "fi", "ht", "af", "la", "id", "fil", "sm", "ca", "el", "ka",
"sr", "it", "sk", "ru", "ru-Latn", "bg", "ny", "fa", "haw", "gl", "et",
"ms", "gd", "bg-Latn", "ha", "is", "ur", "mi", "hi", "bn", "hi-Latn", "fr",
"yi", "hu", "xh", "my", "tg", "ro", "ar", "lb", "el-Latn", "st", "ceb",
"kn", "az", "si", "ky", "mg", "en", "gu", "es", "pl", "ja-Latn", "ga", "lt",
"sn", "yo", "pa", "ku",
// last element must be nullptr
nullptr,
};
const char TaskContextParams::kLanguageIdentifierFeatures[] =
"continuous-bag-of-ngrams(include_terminators=true,include_spaces=false,"
"use_equal_weight=false,id_dim=1000,size=2);continuous-bag-of-ngrams("
"include_terminators=true,include_spaces=false,use_equal_weight=false,id_"
"dim=5000,size=4);continuous-bag-of-relevant-scripts;script;continuous-bag-"
"of-ngrams(include_terminators=true,include_spaces=false,use_equal_weight="
"false,id_dim=5000,size=3);continuous-bag-of-ngrams(include_terminators="
"true,include_spaces=false,use_equal_weight=false,id_dim=100,size=1)";
const char TaskContextParams::kLanguageIdentifierEmbeddingNames[] =
"bigrams;quadgrams;relevant-scripts;text-script;trigrams;unigrams";
const char TaskContextParams::kLanguageIdentifierEmbeddingDims[] =
"16;16;8;8;16;16";
} // namespace chrome_lang_id
<|endoftext|> |
<commit_before>#include <iostream>
#include <apiai/query/VoiceRequest.h>
#include <portaudio.h>
static int MyPaStreamCallback(
const void *input, void *output,
unsigned long frameCount,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData )
{
std::cout << "Hello!" << std::endl;
return paContinue;
}
int main(int argc, char *argv[]) {
Pa_Initialize();
auto default_input_device = Pa_GetDefaultInputDevice();
auto device_info = Pa_GetDeviceInfo(default_input_device);
PaStreamParameters stream_parameters = {
.device = default_input_device,
.channelCount = 1,
.sampleFormat = paInt16,
.suggestedLatency = 0.0,
.hostApiSpecificStreamInfo = NULL
};
auto error = Pa_IsFormatSupported(&stream_parameters, NULL, 16000.0);
if (error != paNoError) {
return -1;
}
PaStream* stream = NULL;
auto open_error =
Pa_OpenStream(&stream,
&stream_parameters,
NULL,
16000.0,
512,
paNoFlag,
MyPaStreamCallback,
NULL);
auto start_error = Pa_StartStream(stream);
PaError err = paNoError;
while( ( err = Pa_IsStreamActive( stream ) ) == 1 )
{
Pa_Sleep(1000);
}
Pa_Terminate();
return 0;
}
<commit_msg>portaudio example implemented<commit_after>#include <iostream>
#include <apiai/AI.h>
#include <apiai/query/VoiceRequest.h>
#include <portaudio.h>
using namespace ai::query::request;
using namespace ai::query::response;
typedef struct _RecordInfo {
PaTime start_record_time;
VoiceRecorder *recorder;
} RecordInfo;
static int MyPaStreamCallback(
const void *input, void *output,
unsigned long frameCount,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData )
{
RecordInfo* info = (RecordInfo *)userData;
if (info->start_record_time < 0.0) {
info->start_record_time = timeInfo->currentTime;
}
info->recorder->write((const char *)input, frameCount *sizeof(short));
if (timeInfo->currentTime - info->start_record_time > 3) {
return paComplete;
}
return paContinue;
}
int main(int argc, char *argv[]) {
Pa_Initialize();
ai::AI::global_init();
auto default_input_device = Pa_GetDefaultInputDevice();
auto device_info = Pa_GetDeviceInfo(default_input_device);
PaStreamParameters stream_parameters = {
.device = default_input_device,
.channelCount = 1,
.sampleFormat = paInt16,
.suggestedLatency = 0.0,
.hostApiSpecificStreamInfo = NULL
};
auto error = Pa_IsFormatSupported(&stream_parameters, NULL, 16000.0);
if (error != paNoError) {
return -1;
}
auto credentials = ai::Credentials("ff98c090685f484caaffada53cdce7b3", "4c91a8e5-275f-4bf0-8f94-befa78ef92cd");
auto params = Parameters("<session id unique for every user>");
VoiceRequest request("en", credentials, params);
request.setVoiceSource([stream_parameters](ai::query::request::VoiceRecorder *recorder){
PaStream* stream = NULL;
RecordInfo info = {0};
info.start_record_time = -1;
info.recorder = recorder;
auto open_error =
Pa_OpenStream(&stream,
&stream_parameters,
NULL,
16000.0,
512,
paNoFlag,
MyPaStreamCallback,
&info);
auto start_error = Pa_StartStream(stream);
PaError err = paNoError;
while( ( err = Pa_IsStreamActive( stream ) ) == 1 )
{
Pa_Sleep(1000);
}
delete recorder;
});
auto response = request.perform();
std::cout << response << std::endl;
ai::AI::global_clean();
Pa_Terminate();
return 0;
}
<|endoftext|> |
<commit_before>#include <plasp/sas/Description.h>
#include <iostream>
#include <boost/filesystem.hpp>
#include <plasp/sas/ParserException.h>
namespace plasp
{
namespace sas
{
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Description
//
////////////////////////////////////////////////////////////////////////////////////////////////////
Description::Description()
: m_usesActionCosts{false}
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
Description Description::fromFile(const boost::filesystem::path &path)
{
Description description;
setlocale(LC_NUMERIC, "C");
if (!boost::filesystem::is_regular_file(path))
{
std::cerr << "Error: File does not exist: " << path.string() << std::endl;
return description;
}
std::ifstream fileStream(path.string(), std::ios::in);
fileStream.exceptions(std::ifstream::failbit | std::ifstream::badbit);
description.parseVersionSection(fileStream);
description.parseMetricSection(fileStream);
description.parseVariablesSection(fileStream);
description.parseMutexSection(fileStream);
description.parseInitialStateSection(fileStream);
description.parseGoalSection(fileStream);
description.parseOperatorSection(fileStream);
description.parseAxiomSection(fileStream);
return description;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::print(std::ostream &ostream) const
{
// Metric section
ostream << "uses action costs: " << (m_usesActionCosts ? "yes" : "no") << std::endl;
// Variable section
ostream << "variables: " << m_variables.size() << std::endl;
std::for_each(m_variables.cbegin(), m_variables.cend(),
[&](const auto &variable)
{
ostream << "\t" << variable.name << std::endl;
ostream << "\t\tvalues: " << variable.values.size() << std::endl;
std::for_each(variable.values.cbegin(), variable.values.cend(),
[&](const auto &value)
{
ostream << "\t\t\t" << value.name << std::endl;
});
ostream << "\t\taxiom layer: " << variable.axiomLayer << std::endl;
});
// Mutex section
ostream << "mutex groups: " << m_mutexGroups.size() << std::endl;
std::for_each(m_mutexGroups.cbegin(), m_mutexGroups.cend(),
[&](const auto &mutexGroup)
{
ostream << "\tmutex group:" << std::endl;
std::for_each(mutexGroup.facts.cbegin(), mutexGroup.facts.cend(),
[&](const auto &fact)
{
ostream << "\t\t" << fact.variable.name << " = " << fact.value.name << std::endl;
});
});
// Initial state section
ostream << "initial state:" << std::endl;
std::for_each(m_initialStateFacts.cbegin(), m_initialStateFacts.cend(),
[&](const auto &initialStateFact)
{
ostream << "\t" << initialStateFact.variable.name << " = " << initialStateFact.value.name << std::endl;
});
// Goal section
ostream << "goal:" << std::endl;
std::for_each(m_goalFacts.cbegin(), m_goalFacts.cend(),
[&](const auto &goalFact)
{
ostream << "\t" << goalFact.variable.name << " = " << goalFact.value.name << std::endl;
});
// Operator section
ostream << "operators: " << m_operators.size() << std::endl;
std::for_each(m_operators.cbegin(), m_operators.cend(),
[&](const auto &operator_)
{
ostream << "\t" << operator_.name << std::endl;
ostream << "\t\tpreconditions: " << operator_.preconditions.size() << std::endl;
std::for_each(operator_.preconditions.cbegin(), operator_.preconditions.cend(),
[&](const auto &precondition)
{
std::cout << "\t\t\t" << precondition.variable.name << " = " << precondition.value.name << std::endl;
});
ostream << "\t\teffects: " << operator_.effects.size() << std::endl;
std::for_each(operator_.effects.cbegin(), operator_.effects.cend(),
[&](const auto &effect)
{
ostream << "\t\t\teffect:" << std::endl;
ostream << "\t\t\t\tconditions: " << effect.conditions.size() << std::endl;
std::for_each(effect.conditions.cbegin(), effect.conditions.cend(),
[&](const auto &condition)
{
ostream << "\t\t\t\t\t" << condition.variable.name << " = " << condition.value.name << std::endl;
});
ostream << "\t\t\t\tpostcondition:" << std::endl;
ostream << "\t\t\t\t\t" << effect.postcondition.variable.name << " = " << effect.postcondition.value.name << std::endl;
});
ostream << "\t\tcosts: " << operator_.costs << std::endl;
});
// Axiom section
ostream << "axiom rules: " << m_axiomRules.size() << std::endl;
std::for_each(m_axiomRules.cbegin(), m_axiomRules.cend(),
[&](const auto &axiomRule)
{
ostream << "\taxiom rule:" << std::endl;
ostream << "\t\tconditions: " << axiomRule.conditions.size() << std::endl;
std::for_each(axiomRule.conditions.cbegin(), axiomRule.conditions.cend(),
[&](const auto &condition)
{
ostream << "\t\t\t" << condition.variable.name << " = " << condition.value.name << std::endl;
});
ostream << "\t\tpostcondition:" << std::endl;
ostream << "\t\t\t" << axiomRule.postcondition.variable.name << " = " << axiomRule.postcondition.value.name << std::endl;
});
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseSectionIdentifier(std::istream &istream, const std::string &expectedSectionIdentifier) const
{
std::string sectionIdentifier;
istream >> sectionIdentifier;
if (sectionIdentifier != expectedSectionIdentifier)
throw ParserException("Invalid format, expected " + expectedSectionIdentifier + ", got " + sectionIdentifier);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
size_t Description::parseNumber(std::istream &istream) const
{
auto number = std::numeric_limits<size_t>::max();
istream >> number;
if (number == std::numeric_limits<size_t>::max())
throw ParserException("Invalid number");
return number;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const Variable &Description::parseVariable(std::istream &istream) const
{
auto variableID = std::numeric_limits<size_t>::max();
istream >> variableID;
if (variableID >= m_variables.size())
throw ParserException("Variable index out of range (index " + std::to_string(variableID) + ")");
return m_variables[variableID];
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const Value &Description::parseVariableValue(std::istream &istream, const Variable &variable) const
{
auto valueID = std::numeric_limits<int>::max();
istream >> valueID;
if (valueID == -1)
return Value::Any;
if (valueID < 0 || static_cast<size_t>(valueID) >= variable.values.size())
throw ParserException("Value index out of range (variable " + variable.name + ", index " + std::to_string(valueID) + ")");
return variable.values[valueID];
}
////////////////////////////////////////////////////////////////////////////////////////////////////
AssignedVariable Description::parseAssignedVariable(std::istream &istream) const
{
const auto &variable = parseVariable(istream);
const auto &value = parseVariableValue(istream, variable);
return {variable, value};
}
////////////////////////////////////////////////////////////////////////////////////////////////////
VariableTransition Description::parseVariableTransition(std::istream &istream) const
{
const auto &variable = parseVariable(istream);
const auto &valueBefore = parseVariableValue(istream, variable);
const auto &valueAfter = parseVariableValue(istream, variable);
return {variable, valueBefore, valueAfter};
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseVersionSection(std::istream &istream) const
{
// Version section
parseSectionIdentifier(istream, "begin_version");
const auto formatVersion = parseNumber(istream);
if (formatVersion != 3)
throw ParserException("Unsupported SAS format version (" + std::to_string(formatVersion) + ")");
std::cout << "SAS format version: " << formatVersion << std::endl;
parseSectionIdentifier(istream, "end_version");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseMetricSection(std::istream &istream)
{
parseSectionIdentifier(istream, "begin_metric");
istream >> m_usesActionCosts;
parseSectionIdentifier(istream, "end_metric");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseVariablesSection(std::istream &istream)
{
const auto numberOfVariables = parseNumber(istream);
m_variables.resize(numberOfVariables);
for (size_t i = 0; i < numberOfVariables; i++)
{
auto &variable = m_variables[i];
parseSectionIdentifier(istream, "begin_variable");
istream >> variable.name;
istream >> variable.axiomLayer;
const auto numberOfValues = parseNumber(istream);
variable.values.resize(numberOfValues);
istream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
for (size_t j = 0; j < numberOfValues; j++)
{
auto &value = variable.values[j];
std::getline(istream, value.name);
}
parseSectionIdentifier(istream, "end_variable");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseMutexSection(std::istream &istream)
{
const auto numberOfMutexGroups = parseNumber(istream);
m_mutexGroups.resize(numberOfMutexGroups);
for (size_t i = 0; i < numberOfMutexGroups; i++)
{
parseSectionIdentifier(istream, "begin_mutex_group");
auto &mutexGroup = m_mutexGroups[i];
const auto numberOfFacts = parseNumber(istream);
mutexGroup.facts.reserve(numberOfFacts);
for (size_t j = 0; j < numberOfFacts; j++)
{
const auto fact = parseAssignedVariable(istream);
mutexGroup.facts.push_back(std::move(fact));
}
parseSectionIdentifier(istream, "end_mutex_group");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseInitialStateSection(std::istream &istream)
{
parseSectionIdentifier(istream, "begin_state");
m_initialStateFacts.reserve(m_variables.size());
for (size_t i = 0; i < m_variables.size(); i++)
{
const auto &variable = m_variables[i];
const auto &value = parseVariableValue(istream, variable);
m_initialStateFacts.push_back({variable, value});
}
parseSectionIdentifier(istream, "end_state");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseGoalSection(std::istream &istream)
{
parseSectionIdentifier(istream, "begin_goal");
const auto numberOfGoalFacts = parseNumber(istream);
m_goalFacts.reserve(numberOfGoalFacts);
for (size_t i = 0; i < numberOfGoalFacts; i++)
{
const auto goalFact = parseAssignedVariable(istream);
m_goalFacts.push_back(std::move(goalFact));
}
parseSectionIdentifier(istream, "end_goal");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseOperatorSection(std::istream &istream)
{
const auto numberOfOperators = parseNumber(istream);
m_operators.resize(numberOfOperators);
for (size_t i = 0; i < numberOfOperators; i++)
{
parseSectionIdentifier(istream, "begin_operator");
istream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
auto &operator_ = m_operators[i];
std::getline(istream, operator_.name);
const auto numberOfPrevailConditions = parseNumber(istream);
operator_.preconditions.reserve(numberOfPrevailConditions);
for (size_t j = 0; j < numberOfPrevailConditions; j++)
{
const auto precondition = parseAssignedVariable(istream);
operator_.preconditions.push_back(std::move(precondition));
}
const auto numberOfEffects = parseNumber(istream);
operator_.effects.reserve(numberOfEffects);
for (size_t j = 0; j < numberOfEffects; j++)
{
Effect::Conditions conditions;
const auto numberOfEffectConditions = parseNumber(istream);
conditions.reserve(numberOfEffectConditions);
for (size_t k = 0; k < numberOfEffectConditions; k++)
{
const auto condition = parseAssignedVariable(istream);
conditions.push_back(std::move(condition));
}
const auto variableTransition = parseVariableTransition(istream);
if (&variableTransition.valueBefore != &Value::Any)
operator_.preconditions.push_back({variableTransition.variable, variableTransition.valueBefore});
const Effect::Condition postcondition = {variableTransition.variable, variableTransition.valueAfter};
const Effect effect = {std::move(conditions), std::move(postcondition)};
operator_.effects.push_back(std::move(effect));
}
operator_.costs = parseNumber(istream);
parseSectionIdentifier(istream, "end_operator");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseAxiomSection(std::istream &istream)
{
const auto numberOfAxiomRules = parseNumber(istream);
m_axiomRules.reserve(numberOfAxiomRules);
std::cout << "Axiom rules: " << numberOfAxiomRules << std::endl;
for (size_t i = 0; i < numberOfAxiomRules; i++)
{
parseSectionIdentifier(istream, "begin_rule");
const auto numberOfConditions = parseNumber(istream);
AxiomRule::Conditions conditions;
conditions.reserve(numberOfConditions);
for (size_t j = 0; j < numberOfConditions; j++)
{
const auto condition = parseAssignedVariable(istream);
conditions.push_back(std::move(condition));
}
const auto variableTransition = parseVariableTransition(istream);
if (&variableTransition.valueBefore != &Value::Any)
conditions.push_back({variableTransition.variable, variableTransition.valueBefore});
const AxiomRule::Condition postcondition = {variableTransition.variable, variableTransition.valueAfter};
const AxiomRule axiomRule = {std::move(conditions), std::move(postcondition)};
m_axiomRules.push_back(std::move(axiomRule));
parseSectionIdentifier(istream, "end_rule");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
<commit_msg>Better handling of number parsing exceptions.<commit_after>#include <plasp/sas/Description.h>
#include <iostream>
#include <boost/filesystem.hpp>
#include <plasp/sas/ParserException.h>
namespace plasp
{
namespace sas
{
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Description
//
////////////////////////////////////////////////////////////////////////////////////////////////////
Description::Description()
: m_usesActionCosts{false}
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
Description Description::fromFile(const boost::filesystem::path &path)
{
Description description;
setlocale(LC_NUMERIC, "C");
if (!boost::filesystem::is_regular_file(path))
{
std::cerr << "Error: File does not exist: " << path.string() << std::endl;
return description;
}
std::ifstream fileStream(path.string(), std::ios::in);
fileStream.exceptions(std::ifstream::failbit | std::ifstream::badbit);
description.parseVersionSection(fileStream);
description.parseMetricSection(fileStream);
description.parseVariablesSection(fileStream);
description.parseMutexSection(fileStream);
description.parseInitialStateSection(fileStream);
description.parseGoalSection(fileStream);
description.parseOperatorSection(fileStream);
description.parseAxiomSection(fileStream);
return description;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::print(std::ostream &ostream) const
{
// Metric section
ostream << "uses action costs: " << (m_usesActionCosts ? "yes" : "no") << std::endl;
// Variable section
ostream << "variables: " << m_variables.size() << std::endl;
std::for_each(m_variables.cbegin(), m_variables.cend(),
[&](const auto &variable)
{
ostream << "\t" << variable.name << std::endl;
ostream << "\t\tvalues: " << variable.values.size() << std::endl;
std::for_each(variable.values.cbegin(), variable.values.cend(),
[&](const auto &value)
{
ostream << "\t\t\t" << value.name << std::endl;
});
ostream << "\t\taxiom layer: " << variable.axiomLayer << std::endl;
});
// Mutex section
ostream << "mutex groups: " << m_mutexGroups.size() << std::endl;
std::for_each(m_mutexGroups.cbegin(), m_mutexGroups.cend(),
[&](const auto &mutexGroup)
{
ostream << "\tmutex group:" << std::endl;
std::for_each(mutexGroup.facts.cbegin(), mutexGroup.facts.cend(),
[&](const auto &fact)
{
ostream << "\t\t" << fact.variable.name << " = " << fact.value.name << std::endl;
});
});
// Initial state section
ostream << "initial state:" << std::endl;
std::for_each(m_initialStateFacts.cbegin(), m_initialStateFacts.cend(),
[&](const auto &initialStateFact)
{
ostream << "\t" << initialStateFact.variable.name << " = " << initialStateFact.value.name << std::endl;
});
// Goal section
ostream << "goal:" << std::endl;
std::for_each(m_goalFacts.cbegin(), m_goalFacts.cend(),
[&](const auto &goalFact)
{
ostream << "\t" << goalFact.variable.name << " = " << goalFact.value.name << std::endl;
});
// Operator section
ostream << "operators: " << m_operators.size() << std::endl;
std::for_each(m_operators.cbegin(), m_operators.cend(),
[&](const auto &operator_)
{
ostream << "\t" << operator_.name << std::endl;
ostream << "\t\tpreconditions: " << operator_.preconditions.size() << std::endl;
std::for_each(operator_.preconditions.cbegin(), operator_.preconditions.cend(),
[&](const auto &precondition)
{
std::cout << "\t\t\t" << precondition.variable.name << " = " << precondition.value.name << std::endl;
});
ostream << "\t\teffects: " << operator_.effects.size() << std::endl;
std::for_each(operator_.effects.cbegin(), operator_.effects.cend(),
[&](const auto &effect)
{
ostream << "\t\t\teffect:" << std::endl;
ostream << "\t\t\t\tconditions: " << effect.conditions.size() << std::endl;
std::for_each(effect.conditions.cbegin(), effect.conditions.cend(),
[&](const auto &condition)
{
ostream << "\t\t\t\t\t" << condition.variable.name << " = " << condition.value.name << std::endl;
});
ostream << "\t\t\t\tpostcondition:" << std::endl;
ostream << "\t\t\t\t\t" << effect.postcondition.variable.name << " = " << effect.postcondition.value.name << std::endl;
});
ostream << "\t\tcosts: " << operator_.costs << std::endl;
});
// Axiom section
ostream << "axiom rules: " << m_axiomRules.size() << std::endl;
std::for_each(m_axiomRules.cbegin(), m_axiomRules.cend(),
[&](const auto &axiomRule)
{
ostream << "\taxiom rule:" << std::endl;
ostream << "\t\tconditions: " << axiomRule.conditions.size() << std::endl;
std::for_each(axiomRule.conditions.cbegin(), axiomRule.conditions.cend(),
[&](const auto &condition)
{
ostream << "\t\t\t" << condition.variable.name << " = " << condition.value.name << std::endl;
});
ostream << "\t\tpostcondition:" << std::endl;
ostream << "\t\t\t" << axiomRule.postcondition.variable.name << " = " << axiomRule.postcondition.value.name << std::endl;
});
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseSectionIdentifier(std::istream &istream, const std::string &expectedSectionIdentifier) const
{
std::string sectionIdentifier;
istream >> sectionIdentifier;
if (sectionIdentifier != expectedSectionIdentifier)
throw ParserException("Invalid format, expected " + expectedSectionIdentifier + ", got " + sectionIdentifier);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
size_t Description::parseNumber(std::istream &istream) const
{
auto number = std::numeric_limits<size_t>::max();
try
{
istream >> number;
}
catch (const std::exception &e)
{
throw ParserException("Could not parse number");
}
if (number == std::numeric_limits<size_t>::max())
throw ParserException("Invalid number");
return number;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const Variable &Description::parseVariable(std::istream &istream) const
{
auto variableID = std::numeric_limits<size_t>::max();
istream >> variableID;
if (variableID >= m_variables.size())
throw ParserException("Variable index out of range (index " + std::to_string(variableID) + ")");
return m_variables[variableID];
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const Value &Description::parseVariableValue(std::istream &istream, const Variable &variable) const
{
auto valueID = std::numeric_limits<int>::max();
istream >> valueID;
if (valueID == -1)
return Value::Any;
if (valueID < 0 || static_cast<size_t>(valueID) >= variable.values.size())
throw ParserException("Value index out of range (variable " + variable.name + ", index " + std::to_string(valueID) + ")");
return variable.values[valueID];
}
////////////////////////////////////////////////////////////////////////////////////////////////////
AssignedVariable Description::parseAssignedVariable(std::istream &istream) const
{
const auto &variable = parseVariable(istream);
const auto &value = parseVariableValue(istream, variable);
return {variable, value};
}
////////////////////////////////////////////////////////////////////////////////////////////////////
VariableTransition Description::parseVariableTransition(std::istream &istream) const
{
const auto &variable = parseVariable(istream);
const auto &valueBefore = parseVariableValue(istream, variable);
const auto &valueAfter = parseVariableValue(istream, variable);
return {variable, valueBefore, valueAfter};
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseVersionSection(std::istream &istream) const
{
// Version section
parseSectionIdentifier(istream, "begin_version");
const auto formatVersion = parseNumber(istream);
if (formatVersion != 3)
throw ParserException("Unsupported SAS format version (" + std::to_string(formatVersion) + ")");
std::cout << "SAS format version: " << formatVersion << std::endl;
parseSectionIdentifier(istream, "end_version");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseMetricSection(std::istream &istream)
{
parseSectionIdentifier(istream, "begin_metric");
istream >> m_usesActionCosts;
parseSectionIdentifier(istream, "end_metric");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseVariablesSection(std::istream &istream)
{
const auto numberOfVariables = parseNumber(istream);
m_variables.resize(numberOfVariables);
for (size_t i = 0; i < numberOfVariables; i++)
{
auto &variable = m_variables[i];
parseSectionIdentifier(istream, "begin_variable");
istream >> variable.name;
istream >> variable.axiomLayer;
const auto numberOfValues = parseNumber(istream);
variable.values.resize(numberOfValues);
istream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
for (size_t j = 0; j < numberOfValues; j++)
{
auto &value = variable.values[j];
std::getline(istream, value.name);
}
parseSectionIdentifier(istream, "end_variable");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseMutexSection(std::istream &istream)
{
const auto numberOfMutexGroups = parseNumber(istream);
m_mutexGroups.resize(numberOfMutexGroups);
for (size_t i = 0; i < numberOfMutexGroups; i++)
{
parseSectionIdentifier(istream, "begin_mutex_group");
auto &mutexGroup = m_mutexGroups[i];
const auto numberOfFacts = parseNumber(istream);
mutexGroup.facts.reserve(numberOfFacts);
for (size_t j = 0; j < numberOfFacts; j++)
{
const auto fact = parseAssignedVariable(istream);
mutexGroup.facts.push_back(std::move(fact));
}
parseSectionIdentifier(istream, "end_mutex_group");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseInitialStateSection(std::istream &istream)
{
parseSectionIdentifier(istream, "begin_state");
m_initialStateFacts.reserve(m_variables.size());
for (size_t i = 0; i < m_variables.size(); i++)
{
const auto &variable = m_variables[i];
const auto &value = parseVariableValue(istream, variable);
m_initialStateFacts.push_back({variable, value});
}
parseSectionIdentifier(istream, "end_state");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseGoalSection(std::istream &istream)
{
parseSectionIdentifier(istream, "begin_goal");
const auto numberOfGoalFacts = parseNumber(istream);
m_goalFacts.reserve(numberOfGoalFacts);
for (size_t i = 0; i < numberOfGoalFacts; i++)
{
const auto goalFact = parseAssignedVariable(istream);
m_goalFacts.push_back(std::move(goalFact));
}
parseSectionIdentifier(istream, "end_goal");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseOperatorSection(std::istream &istream)
{
const auto numberOfOperators = parseNumber(istream);
m_operators.resize(numberOfOperators);
for (size_t i = 0; i < numberOfOperators; i++)
{
parseSectionIdentifier(istream, "begin_operator");
istream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
auto &operator_ = m_operators[i];
std::getline(istream, operator_.name);
const auto numberOfPrevailConditions = parseNumber(istream);
operator_.preconditions.reserve(numberOfPrevailConditions);
for (size_t j = 0; j < numberOfPrevailConditions; j++)
{
const auto precondition = parseAssignedVariable(istream);
operator_.preconditions.push_back(std::move(precondition));
}
const auto numberOfEffects = parseNumber(istream);
operator_.effects.reserve(numberOfEffects);
for (size_t j = 0; j < numberOfEffects; j++)
{
Effect::Conditions conditions;
const auto numberOfEffectConditions = parseNumber(istream);
conditions.reserve(numberOfEffectConditions);
for (size_t k = 0; k < numberOfEffectConditions; k++)
{
const auto condition = parseAssignedVariable(istream);
conditions.push_back(std::move(condition));
}
const auto variableTransition = parseVariableTransition(istream);
if (&variableTransition.valueBefore != &Value::Any)
operator_.preconditions.push_back({variableTransition.variable, variableTransition.valueBefore});
const Effect::Condition postcondition = {variableTransition.variable, variableTransition.valueAfter};
const Effect effect = {std::move(conditions), std::move(postcondition)};
operator_.effects.push_back(std::move(effect));
}
operator_.costs = parseNumber(istream);
parseSectionIdentifier(istream, "end_operator");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseAxiomSection(std::istream &istream)
{
const auto numberOfAxiomRules = parseNumber(istream);
m_axiomRules.reserve(numberOfAxiomRules);
std::cout << "Axiom rules: " << numberOfAxiomRules << std::endl;
for (size_t i = 0; i < numberOfAxiomRules; i++)
{
parseSectionIdentifier(istream, "begin_rule");
const auto numberOfConditions = parseNumber(istream);
AxiomRule::Conditions conditions;
conditions.reserve(numberOfConditions);
for (size_t j = 0; j < numberOfConditions; j++)
{
const auto condition = parseAssignedVariable(istream);
conditions.push_back(std::move(condition));
}
const auto variableTransition = parseVariableTransition(istream);
if (&variableTransition.valueBefore != &Value::Any)
conditions.push_back({variableTransition.variable, variableTransition.valueBefore});
const AxiomRule::Condition postcondition = {variableTransition.variable, variableTransition.valueAfter};
const AxiomRule axiomRule = {std::move(conditions), std::move(postcondition)};
m_axiomRules.push_back(std::move(axiomRule));
parseSectionIdentifier(istream, "end_rule");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
<|endoftext|> |
<commit_before>#include <string.h>
#include "lpc17xx_pinsel.h"
#include "lpc17xx_uart.h"
#include "interface/uart.h"
#include "pipeline.h"
#include "atcommander.h"
#include "util/bytebuffer.h"
#include "util/log.h"
#include "util/timer.h"
#include "gpio.h"
// Only UART1 supports hardware flow control, so this has to be UART1
#define UART1_DEVICE (LPC_UART_TypeDef*)LPC_UART1
#define UART_STATUS_PORT 0
#define UART_STATUS_PIN 18
#ifdef BLUEBOARD
#define UART1_FUNCNUM 2
#define UART1_PORTNUM 2
#define UART1_TX_PINNUM 0
#define UART1_RX_PINNUM 1
#define UART1_FLOW_PORTNUM UART1_PORTNUM
#define UART1_FLOW_FUNCNUM UART1_FUNCNUM
#define UART1_CTS1_PINNUM 2
#define UART1_RTS1_PINNUM 7
#else
// Ford OpenXC CAN Translator Prototype
#define UART1_FUNCNUM 1
#define UART1_PORTNUM 0
#define UART1_TX_PINNUM 15
#define UART1_RX_PINNUM 16
#define UART1_FLOW_PORTNUM 2
#define UART1_FLOW_FUNCNUM 2
#define UART1_RTS1_PINNUM 2
#define UART1_CTS1_PINNUM 7
#endif
namespace gpio = openxc::gpio;
using openxc::util::time::delayMs;
using openxc::util::log::debugNoNewline;
using openxc::pipeline::Pipeline;
using openxc::util::bytebuffer::processQueue;
using openxc::gpio::GpioValue;
using openxc::gpio::GpioDirection;
extern const AtCommanderPlatform AT_PLATFORM_RN42;
extern Pipeline pipeline;
__IO int32_t RTS_STATE;
__IO FlagStatus TRANSMIT_INTERRUPT_STATUS;
/* Disable request to send through RTS line. We cannot handle any more data
* right now.
*/
void pauseReceive() {
if(RTS_STATE == ACTIVE) {
// Disable request to send through RTS line
UART_FullModemForcePinState(LPC_UART1, UART1_MODEM_PIN_RTS, INACTIVE);
RTS_STATE = INACTIVE;
}
}
/* Enable request to send through RTS line. We can handle more data now. */
void resumeReceive() {
if (RTS_STATE == INACTIVE) {
// Enable request to send through RTS line
UART_FullModemForcePinState(LPC_UART1, UART1_MODEM_PIN_RTS, ACTIVE);
RTS_STATE = ACTIVE;
}
}
void disableTransmitInterrupt() {
UART_IntConfig(UART1_DEVICE, UART_INTCFG_THRE, DISABLE);
}
void enableTransmitInterrupt() {
TRANSMIT_INTERRUPT_STATUS = SET;
UART_IntConfig(UART1_DEVICE, UART_INTCFG_THRE, ENABLE);
}
void handleReceiveInterrupt() {
while(!QUEUE_FULL(uint8_t, &pipeline.uart->receiveQueue)) {
uint8_t byte;
uint32_t received = UART_Receive(UART1_DEVICE, &byte, 1, NONE_BLOCKING);
if(received > 0) {
QUEUE_PUSH(uint8_t, &pipeline.uart->receiveQueue, byte);
if(QUEUE_FULL(uint8_t, &pipeline.uart->receiveQueue)) {
pauseReceive();
}
} else {
break;
}
}
}
void handleTransmitInterrupt() {
disableTransmitInterrupt();
while(UART_CheckBusy(UART1_DEVICE) == SET);
while(!QUEUE_EMPTY(uint8_t, &pipeline.uart->sendQueue)) {
uint8_t byte = QUEUE_PEEK(uint8_t, &pipeline.uart->sendQueue);
if(UART_Send(UART1_DEVICE, &byte, 1, NONE_BLOCKING)) {
QUEUE_POP(uint8_t, &pipeline.uart->sendQueue);
} else {
break;
}
}
if(QUEUE_EMPTY(uint8_t, &pipeline.uart->sendQueue)) {
disableTransmitInterrupt();
TRANSMIT_INTERRUPT_STATUS = RESET;
} else {
enableTransmitInterrupt();
}
}
extern "C" {
void UART1_IRQHandler() {
uint32_t interruptSource = UART_GetIntId(UART1_DEVICE)
& UART_IIR_INTID_MASK;
switch(interruptSource) {
case UART1_IIR_INTID_MODEM: {
// Check Modem status
uint8_t modemStatus = UART_FullModemGetStatus(LPC_UART1);
// Check CTS status change flag
if (modemStatus & UART1_MODEM_STAT_DELTA_CTS) {
// if CTS status is active, continue to send data
if (modemStatus & UART1_MODEM_STAT_CTS) {
UART_TxCmd(UART1_DEVICE, ENABLE);
} else {
// Otherwise, Stop current transmission immediately
UART_TxCmd(UART1_DEVICE, DISABLE);
}
}
break;
}
case UART_IIR_INTID_RDA:
case UART_IIR_INTID_CTI:
handleReceiveInterrupt();
break;
case UART_IIR_INTID_THRE:
handleTransmitInterrupt();
break;
default:
break;
}
}
}
void openxc::interface::uart::read(UartDevice* device, bool (*callback)(uint8_t*)) {
if(device != NULL) {
if(!QUEUE_EMPTY(uint8_t, &device->receiveQueue)) {
processQueue(&device->receiveQueue, callback);
if(!QUEUE_FULL(uint8_t, &device->receiveQueue)) {
resumeReceive();
}
}
}
}
/* Auto flow control does work, but it turns the uart write functions into
* blocking functions, which drags USB down. Instead we handle it manually so we
* can make them asynchronous and let USB run at full speed.
*/
void configureFlowControl() {
if (UART_FullModemGetStatus(LPC_UART1) & UART1_MODEM_STAT_CTS) {
// Enable UART Transmit
UART_TxCmd(UART1_DEVICE, ENABLE);
}
// Enable Modem status interrupt
UART_IntConfig(UART1_DEVICE, UART1_INTCFG_MS, ENABLE);
// Enable CTS1 signal transition interrupt
UART_IntConfig(UART1_DEVICE, UART1_INTCFG_CTS, ENABLE);
resumeReceive();
}
void configureUartPins() {
PINSEL_CFG_Type PinCfg;
PinCfg.Funcnum = UART1_FUNCNUM;
PinCfg.OpenDrain = 0;
PinCfg.Pinmode = 0;
PinCfg.Portnum = UART1_PORTNUM;
PinCfg.Pinnum = UART1_TX_PINNUM;
PINSEL_ConfigPin(&PinCfg);
PinCfg.Pinnum = UART1_RX_PINNUM;
PINSEL_ConfigPin(&PinCfg);
PinCfg.Portnum = UART1_FLOW_PORTNUM;
PinCfg.Funcnum = UART1_FLOW_FUNCNUM;
PinCfg.Pinnum = UART1_CTS1_PINNUM;
PINSEL_ConfigPin(&PinCfg);
PinCfg.Pinnum = UART1_RTS1_PINNUM;
PINSEL_ConfigPin(&PinCfg);
}
void configureFifo() {
UART_FIFO_CFG_Type fifoConfig;
UART_FIFOConfigStructInit(&fifoConfig);
UART_FIFOConfig(UART1_DEVICE, &fifoConfig);
}
void configureUart(int baud) {
UART_CFG_Type UARTConfigStruct;
UART_ConfigStructInit(&UARTConfigStruct);
UARTConfigStruct.Baud_rate = baud;
UART_Init(UART1_DEVICE, &UARTConfigStruct);
}
void configureInterrupts() {
UART_IntConfig(UART1_DEVICE, UART_INTCFG_RBR, ENABLE);
enableTransmitInterrupt();
/* preemption = 1, sub-priority = 1 */
NVIC_SetPriority(UART1_IRQn, ((0x01<<3)|0x01));
NVIC_EnableIRQ(UART1_IRQn);
}
void writeByte(uint8_t byte) {
UART_SendByte(UART1_DEVICE, byte);
}
int readByte() {
if(!QUEUE_EMPTY(uint8_t, &pipeline.uart->receiveQueue)) {
return QUEUE_POP(uint8_t, &pipeline.uart->receiveQueue);
}
return -1;
}
// TODO this is stupid, fix the at-commander API
void delay(long unsigned int delayInMs) {
delayMs(delayInMs);
}
void openxc::interface::uart::initialize(UartDevice* device) {
if(device == NULL) {
debug("Can't initialize a NULL UartDevice");
return;
}
initializeCommon(device);
configureUartPins();
configureUart(BAUD_RATE);
configureFifo();
configureFlowControl();
configureInterrupts();
TRANSMIT_INTERRUPT_STATUS = RESET;
// Configure P0.18 as an input, pulldown
LPC_PINCON->PINMODE1 |= (1 << 5);
// Ensure BT reset line is held high.
LPC_GPIO1->FIODIR |= (1 << 17);
debug("Done.");
gpio::setDirection(UART_STATUS_PORT, UART_STATUS_PIN,
GpioDirection::GPIO_DIRECTION_INPUT);
AtCommanderConfig config = {AT_PLATFORM_RN42};
config.baud_rate_initializer = configureUart;
config.write_function = writeByte;
config.read_function = readByte;
config.delay_function = delay;
config.log_function = debugNoNewline;
delayMs(1000);
if(at_commander_set_baud(&config, BAUD_RATE)) {
debug("Successfully set baud rate");
at_commander_reboot(&config);
} else {
debug("Unable to set baud rate of attached UART device");
}
debug("Done.");
}
void openxc::interface::uart::processSendQueue(UartDevice* device) {
if(!QUEUE_EMPTY(uint8_t, &device->sendQueue)) {
if(TRANSMIT_INTERRUPT_STATUS == RESET) {
handleTransmitInterrupt();
} else {
enableTransmitInterrupt();
}
}
}
bool openxc::interface::uart::connected(UartDevice* device) {
return device != NULL && gpio::getValue(UART_STATUS_PORT, UART_STATUS_PIN)
!= GpioValue::GPIO_VALUE_LOW;
}
<commit_msg>Re-organize UART init for LPC17xx to allow changing baud on the fly.<commit_after>#include <string.h>
#include "lpc17xx_pinsel.h"
#include "lpc17xx_uart.h"
#include "interface/uart.h"
#include "pipeline.h"
#include "atcommander.h"
#include "util/bytebuffer.h"
#include "util/log.h"
#include "util/timer.h"
#include "gpio.h"
// Only UART1 supports hardware flow control, so this has to be UART1
#define UART1_DEVICE (LPC_UART_TypeDef*)LPC_UART1
#define UART_STATUS_PORT 0
#define UART_STATUS_PIN 18
#ifdef BLUEBOARD
#define UART1_FUNCNUM 2
#define UART1_PORTNUM 2
#define UART1_TX_PINNUM 0
#define UART1_RX_PINNUM 1
#define UART1_FLOW_PORTNUM UART1_PORTNUM
#define UART1_FLOW_FUNCNUM UART1_FUNCNUM
#define UART1_CTS1_PINNUM 2
#define UART1_RTS1_PINNUM 7
#else
// Ford OpenXC CAN Translator Prototype
#define UART1_FUNCNUM 1
#define UART1_PORTNUM 0
#define UART1_TX_PINNUM 15
#define UART1_RX_PINNUM 16
#define UART1_FLOW_PORTNUM 2
#define UART1_FLOW_FUNCNUM 2
#define UART1_RTS1_PINNUM 2
#define UART1_CTS1_PINNUM 7
#endif
namespace gpio = openxc::gpio;
using openxc::util::time::delayMs;
using openxc::util::log::debugNoNewline;
using openxc::pipeline::Pipeline;
using openxc::util::bytebuffer::processQueue;
using openxc::gpio::GpioValue;
using openxc::gpio::GpioDirection;
extern const AtCommanderPlatform AT_PLATFORM_RN42;
extern Pipeline pipeline;
__IO int32_t RTS_STATE;
__IO FlagStatus TRANSMIT_INTERRUPT_STATUS;
/* Disable request to send through RTS line. We cannot handle any more data
* right now.
*/
void pauseReceive() {
if(RTS_STATE == ACTIVE) {
// Disable request to send through RTS line
UART_FullModemForcePinState(LPC_UART1, UART1_MODEM_PIN_RTS, INACTIVE);
RTS_STATE = INACTIVE;
}
}
/* Enable request to send through RTS line. We can handle more data now. */
void resumeReceive() {
if (RTS_STATE == INACTIVE) {
// Enable request to send through RTS line
UART_FullModemForcePinState(LPC_UART1, UART1_MODEM_PIN_RTS, ACTIVE);
RTS_STATE = ACTIVE;
}
}
void disableTransmitInterrupt() {
UART_IntConfig(UART1_DEVICE, UART_INTCFG_THRE, DISABLE);
}
void enableTransmitInterrupt() {
TRANSMIT_INTERRUPT_STATUS = SET;
UART_IntConfig(UART1_DEVICE, UART_INTCFG_THRE, ENABLE);
}
void handleReceiveInterrupt() {
while(!QUEUE_FULL(uint8_t, &pipeline.uart->receiveQueue)) {
uint8_t byte;
uint32_t received = UART_Receive(UART1_DEVICE, &byte, 1, NONE_BLOCKING);
if(received > 0) {
QUEUE_PUSH(uint8_t, &pipeline.uart->receiveQueue, byte);
if(QUEUE_FULL(uint8_t, &pipeline.uart->receiveQueue)) {
pauseReceive();
}
} else {
break;
}
}
}
void handleTransmitInterrupt() {
disableTransmitInterrupt();
while(UART_CheckBusy(UART1_DEVICE) == SET);
while(!QUEUE_EMPTY(uint8_t, &pipeline.uart->sendQueue)) {
uint8_t byte = QUEUE_PEEK(uint8_t, &pipeline.uart->sendQueue);
if(UART_Send(UART1_DEVICE, &byte, 1, NONE_BLOCKING)) {
QUEUE_POP(uint8_t, &pipeline.uart->sendQueue);
} else {
break;
}
}
if(QUEUE_EMPTY(uint8_t, &pipeline.uart->sendQueue)) {
disableTransmitInterrupt();
TRANSMIT_INTERRUPT_STATUS = RESET;
} else {
enableTransmitInterrupt();
}
}
extern "C" {
void UART1_IRQHandler() {
uint32_t interruptSource = UART_GetIntId(UART1_DEVICE)
& UART_IIR_INTID_MASK;
switch(interruptSource) {
case UART1_IIR_INTID_MODEM: {
// Check Modem status
uint8_t modemStatus = UART_FullModemGetStatus(LPC_UART1);
// Check CTS status change flag
if (modemStatus & UART1_MODEM_STAT_DELTA_CTS) {
// if CTS status is active, continue to send data
if (modemStatus & UART1_MODEM_STAT_CTS) {
UART_TxCmd(UART1_DEVICE, ENABLE);
} else {
// Otherwise, Stop current transmission immediately
UART_TxCmd(UART1_DEVICE, DISABLE);
}
}
break;
}
case UART_IIR_INTID_RDA:
case UART_IIR_INTID_CTI:
handleReceiveInterrupt();
break;
case UART_IIR_INTID_THRE:
handleTransmitInterrupt();
break;
default:
break;
}
}
}
void openxc::interface::uart::read(UartDevice* device, bool (*callback)(uint8_t*)) {
if(device != NULL) {
if(!QUEUE_EMPTY(uint8_t, &device->receiveQueue)) {
processQueue(&device->receiveQueue, callback);
if(!QUEUE_FULL(uint8_t, &device->receiveQueue)) {
resumeReceive();
}
}
}
}
/* Auto flow control does work, but it turns the uart write functions into
* blocking functions, which drags USB down. Instead we handle it manually so we
* can make them asynchronous and let USB run at full speed.
*/
void configureFlowControl() {
if (UART_FullModemGetStatus(LPC_UART1) & UART1_MODEM_STAT_CTS) {
// Enable UART Transmit
UART_TxCmd(UART1_DEVICE, ENABLE);
}
// Enable Modem status interrupt
UART_IntConfig(UART1_DEVICE, UART1_INTCFG_MS, ENABLE);
// Enable CTS1 signal transition interrupt
UART_IntConfig(UART1_DEVICE, UART1_INTCFG_CTS, ENABLE);
resumeReceive();
}
void configureUartPins() {
PINSEL_CFG_Type PinCfg;
PinCfg.Funcnum = UART1_FUNCNUM;
PinCfg.OpenDrain = 0;
PinCfg.Pinmode = 0;
PinCfg.Portnum = UART1_PORTNUM;
PinCfg.Pinnum = UART1_TX_PINNUM;
PINSEL_ConfigPin(&PinCfg);
PinCfg.Pinnum = UART1_RX_PINNUM;
PINSEL_ConfigPin(&PinCfg);
PinCfg.Portnum = UART1_FLOW_PORTNUM;
PinCfg.Funcnum = UART1_FLOW_FUNCNUM;
PinCfg.Pinnum = UART1_CTS1_PINNUM;
PINSEL_ConfigPin(&PinCfg);
PinCfg.Pinnum = UART1_RTS1_PINNUM;
PINSEL_ConfigPin(&PinCfg);
}
void configureFifo() {
UART_FIFO_CFG_Type fifoConfig;
UART_FIFOConfigStructInit(&fifoConfig);
UART_FIFOConfig(UART1_DEVICE, &fifoConfig);
}
void configureInterrupts() {
UART_IntConfig(UART1_DEVICE, UART_INTCFG_RBR, ENABLE);
enableTransmitInterrupt();
/* preemption = 1, sub-priority = 1 */
NVIC_SetPriority(UART1_IRQn, ((0x01<<3)|0x01));
NVIC_EnableIRQ(UART1_IRQn);
}
void configureUart(int baud) {
UART_CFG_Type UARTConfigStruct;
UART_ConfigStructInit(&UARTConfigStruct);
UARTConfigStruct.Baud_rate = baud;
UART_Init(UART1_DEVICE, &UARTConfigStruct);
configureFifo();
configureFlowControl();
configureInterrupts();
TRANSMIT_INTERRUPT_STATUS = RESET;
}
void writeByte(uint8_t byte) {
UART_SendByte(UART1_DEVICE, byte);
}
int readByte() {
if(!QUEUE_EMPTY(uint8_t, &pipeline.uart->receiveQueue)) {
return QUEUE_POP(uint8_t, &pipeline.uart->receiveQueue);
}
return -1;
}
// TODO this is stupid, fix the at-commander API
void delay(long unsigned int delayInMs) {
delayMs(delayInMs);
}
void openxc::interface::uart::initialize(UartDevice* device) {
if(device == NULL) {
debug("Can't initialize a NULL UartDevice");
return;
}
initializeCommon(device);
// Configure P0.18 as an input, pulldown
LPC_PINCON->PINMODE1 |= (1 << 5);
// Ensure BT reset line is held high.
LPC_GPIO1->FIODIR |= (1 << 17);
debug("Done.");
gpio::setDirection(UART_STATUS_PORT, UART_STATUS_PIN,
GpioDirection::GPIO_DIRECTION_INPUT);
configureUartPins();
configureUart(BAUD_RATE);
AtCommanderConfig config = {AT_PLATFORM_RN42};
config.baud_rate_initializer = configureUart;
config.write_function = writeByte;
config.read_function = readByte;
config.delay_function = delay;
config.log_function = debugNoNewline;
delayMs(1000);
if(at_commander_set_baud(&config, BAUD_RATE)) {
debug("Successfully set baud rate");
at_commander_reboot(&config);
} else {
debug("Unable to set baud rate of attached UART device");
}
debug("Done.");
}
void openxc::interface::uart::processSendQueue(UartDevice* device) {
if(!QUEUE_EMPTY(uint8_t, &device->sendQueue)) {
if(TRANSMIT_INTERRUPT_STATUS == RESET) {
handleTransmitInterrupt();
} else {
enableTransmitInterrupt();
}
}
}
bool openxc::interface::uart::connected(UartDevice* device) {
return device != NULL && gpio::getValue(UART_STATUS_PORT, UART_STATUS_PIN)
!= GpioValue::GPIO_VALUE_LOW;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* This program 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 program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "VLCThumbnailer.h"
#include "Media.h"
#include "File.h"
#include "logging/Logger.h"
#include "MediaLibrary.h"
#include "utils/VLCInstance.h"
#include "utils/ModificationsNotifier.h"
#ifdef HAVE_JPEG
#include "imagecompressors/JpegCompressor.h"
#elif defined(HAVE_EVAS)
#include "imagecompressors/EvasCompressor.h"
#else
#error No image compressor available
#endif
namespace medialibrary
{
VLCThumbnailer::VLCThumbnailer()
: m_instance( VLCInstance::get() )
, m_thumbnailRequired( false )
, m_width( 0 )
, m_height( 0 )
, m_prevSize( 0 )
{
#ifdef HAVE_JPEG
m_compressor.reset( new JpegCompressor );
#elif defined(HAVE_EVAS)
m_compressor.reset( new EvasCompressor );
#endif
}
bool VLCThumbnailer::initialize()
{
return true;
}
File::ParserStep VLCThumbnailer::step() const
{
return File::ParserStep::Thumbnailer;
}
parser::Task::Status VLCThumbnailer::run( parser::Task& task )
{
auto media = task.media;
auto file = task.file;
if ( media->type() == IMedia::Type::UnknownType )
{
// If we don't know the media type yet, it actually looks more like a bug
// since this should run after media type deduction, and not run in case
// that step fails.
return parser::Task::Status::Fatal;
}
else if ( media->type() != IMedia::Type::VideoType )
{
// There's no point in generating a thumbnail for a non-video media.
task.file->markStepCompleted( File::ParserStep::Thumbnailer );
task.file->saveParserStep();
return parser::Task::Status::Success;
}
LOG_INFO( "Generating ", file->mrl(), " thumbnail..." );
task.vlcMedia.addOption( ":no-audio" );
task.vlcMedia.addOption( ":no-osd" );
task.vlcMedia.addOption( ":no-spu" );
task.vlcMedia.addOption( ":input-fast-seek" );
VLC::MediaPlayer mp( task.vlcMedia );
setupVout( mp );
auto res = startPlayback( mp );
if ( res != parser::Task::Status::Success )
{
LOG_WARN( "Failed to generate ", file->mrl(), " thumbnail: Can't start playback" );
return res;
}
// Seek ahead to have a significant preview
res = seekAhead( mp );
if ( res != parser::Task::Status::Success )
{
LOG_WARN( "Failed to generate ", file->mrl(), " thumbnail: Failed to seek ahead" );
return res;
}
return takeThumbnail( media, file, mp );
}
parser::Task::Status VLCThumbnailer::startPlayback( VLC::MediaPlayer &mp )
{
// Use a copy of the event manager to automatically unregister all events as soon
// as we leave this method.
auto em = mp.eventManager();
em.onPlaying([this]() {
m_cond.notify_all();
});
em.onEncounteredError([this]() {
m_cond.notify_all();
});
std::unique_lock<compat::Mutex> lock( m_mutex );
mp.play();
bool success = m_cond.wait_for( lock, std::chrono::seconds( 3 ), [&mp]() {
auto s = mp.state();
return s == libvlc_Playing || s == libvlc_Error || s == libvlc_Ended;
});
auto s = mp.state();
if ( success == false || s == libvlc_Error || s == libvlc_Ended )
{
// In case of timeout or error, don't go any further
return parser::Task::Status::Error;
}
return parser::Task::Status::Success;
}
parser::Task::Status VLCThumbnailer::seekAhead( VLC::MediaPlayer& mp )
{
std::unique_lock<compat::Mutex> lock( m_mutex );
float pos = .0f;
auto event = mp.eventManager().onPositionChanged([this, &pos](float p) {
std::unique_lock<compat::Mutex> lock( m_mutex );
pos = p;
m_cond.notify_all();
});
mp.setPosition( .4f );
bool success = m_cond.wait_for( lock, std::chrono::seconds( 3 ), [&pos]() {
return pos >= .1f;
});
// Since we're locking a mutex for each position changed, let's unregister ASAP
event->unregister();
if ( success == false )
return parser::Task::Status::Error;
return parser::Task::Status::Success;
}
void VLCThumbnailer::setupVout( VLC::MediaPlayer& mp )
{
mp.setVideoFormatCallbacks(
// Setup
[this, &mp](char* chroma, unsigned int* width, unsigned int *height, unsigned int *pitches, unsigned int *lines) {
strcpy( chroma, m_compressor->fourCC() );
const float inputAR = (float)*width / *height;
m_width = DesiredWidth;
m_height = (float)m_width / inputAR + 1;
if ( m_height < DesiredHeight )
{
// Avoid downscaling too much for really wide pictures
m_width = inputAR * DesiredHeight;
m_height = DesiredHeight;
}
auto size = m_width * m_height * m_compressor->bpp();
// If our buffer isn't enough anymore, reallocate a new one.
if ( size > m_prevSize )
{
m_buff.reset( new uint8_t[size] );
m_prevSize = size;
}
*width = m_width;
*height = m_height;
*pitches = m_width * m_compressor->bpp();
*lines = m_height;
return 1;
},
// Cleanup
nullptr);
mp.setVideoCallbacks(
// Lock
[this](void** pp_buff) {
*pp_buff = m_buff.get();
return nullptr;
},
//unlock
nullptr,
//display
[this](void*) {
bool expected = true;
if ( m_thumbnailRequired.compare_exchange_strong( expected, false ) )
{
m_cond.notify_all();
}
}
);
}
parser::Task::Status VLCThumbnailer::takeThumbnail( std::shared_ptr<Media> media, std::shared_ptr<File> file, VLC::MediaPlayer &mp )
{
// lock, signal that we want a thumbnail, and wait.
{
std::unique_lock<compat::Mutex> lock( m_mutex );
m_thumbnailRequired = true;
bool success = m_cond.wait_for( lock, std::chrono::seconds( 3 ), [this]() {
// Keep waiting if the vmem thread hasn't restored m_thumbnailRequired to false
return m_thumbnailRequired == false;
});
if ( success == false )
{
LOG_WARN( "Timed out while computing ", file->mrl(), " snapshot" );
return parser::Task::Status::Error;
}
}
mp.stop();
return compress( media, file );
}
parser::Task::Status VLCThumbnailer::compress( std::shared_ptr<Media> media, std::shared_ptr<File> file )
{
auto path = m_ml->thumbnailPath();
path += "/";
path += std::to_string( media->id() ) + "." + m_compressor->extension();
auto hOffset = m_width > DesiredWidth ? ( m_width - DesiredWidth ) / 2 : 0;
auto vOffset = m_height > DesiredHeight ? ( m_height - DesiredHeight ) / 2 : 0;
if ( m_compressor->compress( m_buff.get(), path, m_width, m_height, DesiredWidth, DesiredHeight,
hOffset, vOffset ) == false )
return parser::Task::Status::Fatal;
media->setThumbnail( path );
LOG_INFO( "Done generating ", file->mrl(), " thumbnail" );
auto t = m_ml->getConn()->newTransaction();
if ( media->save() == false )
return parser::Task::Status::Error;
file->markStepCompleted( File::ParserStep::Thumbnailer );
if ( file->saveParserStep() == false )
return parser::Task::Status::Error;
t->commit();
m_notifier->notifyMediaModification( media );
return parser::Task::Status::Success;
}
const char*VLCThumbnailer::name() const
{
return "Thumbnailer";
}
uint8_t VLCThumbnailer::nbThreads() const
{
return 1;
}
}
<commit_msg>Thumbnailer: Wait for a video track to be added rather than the playing event<commit_after>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* This program 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 program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "VLCThumbnailer.h"
#include "Media.h"
#include "File.h"
#include "logging/Logger.h"
#include "MediaLibrary.h"
#include "utils/VLCInstance.h"
#include "utils/ModificationsNotifier.h"
#ifdef HAVE_JPEG
#include "imagecompressors/JpegCompressor.h"
#elif defined(HAVE_EVAS)
#include "imagecompressors/EvasCompressor.h"
#else
#error No image compressor available
#endif
namespace medialibrary
{
VLCThumbnailer::VLCThumbnailer()
: m_instance( VLCInstance::get() )
, m_thumbnailRequired( false )
, m_width( 0 )
, m_height( 0 )
, m_prevSize( 0 )
{
#ifdef HAVE_JPEG
m_compressor.reset( new JpegCompressor );
#elif defined(HAVE_EVAS)
m_compressor.reset( new EvasCompressor );
#endif
}
bool VLCThumbnailer::initialize()
{
return true;
}
File::ParserStep VLCThumbnailer::step() const
{
return File::ParserStep::Thumbnailer;
}
parser::Task::Status VLCThumbnailer::run( parser::Task& task )
{
auto media = task.media;
auto file = task.file;
if ( media->type() == IMedia::Type::UnknownType )
{
// If we don't know the media type yet, it actually looks more like a bug
// since this should run after media type deduction, and not run in case
// that step fails.
return parser::Task::Status::Fatal;
}
else if ( media->type() != IMedia::Type::VideoType )
{
// There's no point in generating a thumbnail for a non-video media.
task.file->markStepCompleted( File::ParserStep::Thumbnailer );
task.file->saveParserStep();
return parser::Task::Status::Success;
}
LOG_INFO( "Generating ", file->mrl(), " thumbnail..." );
task.vlcMedia.addOption( ":no-audio" );
task.vlcMedia.addOption( ":no-osd" );
task.vlcMedia.addOption( ":no-spu" );
task.vlcMedia.addOption( ":input-fast-seek" );
VLC::MediaPlayer mp( task.vlcMedia );
setupVout( mp );
auto res = startPlayback( mp );
if ( res != parser::Task::Status::Success )
{
LOG_WARN( "Failed to generate ", file->mrl(), " thumbnail: Can't start playback" );
return res;
}
// Seek ahead to have a significant preview
res = seekAhead( mp );
if ( res != parser::Task::Status::Success )
{
LOG_WARN( "Failed to generate ", file->mrl(), " thumbnail: Failed to seek ahead" );
return res;
}
return takeThumbnail( media, file, mp );
}
parser::Task::Status VLCThumbnailer::startPlayback( VLC::MediaPlayer &mp )
{
// Use a copy of the event manager to automatically unregister all events as soon
// as we leave this method.
auto em = mp.eventManager();
bool hasVideoTrack = false;
em.onESAdded([this, &hasVideoTrack]( libvlc_track_type_t type, int ) {
if ( type == libvlc_track_video )
{
m_cond.notify_all();
hasVideoTrack = true;
}
});
em.onEncounteredError([this]() {
m_cond.notify_all();
});
std::unique_lock<compat::Mutex> lock( m_mutex );
mp.play();
bool success = m_cond.wait_for( lock, std::chrono::seconds( 1 ), [&mp, &hasVideoTrack]() {
auto s = mp.state();
return s == libvlc_Error || s == libvlc_Ended || hasVideoTrack == true;
});
if ( success == false || hasVideoTrack == false )
{
// In case of timeout or error, don't go any further
return parser::Task::Status::Error;
}
return parser::Task::Status::Success;
}
parser::Task::Status VLCThumbnailer::seekAhead( VLC::MediaPlayer& mp )
{
std::unique_lock<compat::Mutex> lock( m_mutex );
float pos = .0f;
auto event = mp.eventManager().onPositionChanged([this, &pos](float p) {
std::unique_lock<compat::Mutex> lock( m_mutex );
pos = p;
m_cond.notify_all();
});
mp.setPosition( .4f );
bool success = m_cond.wait_for( lock, std::chrono::seconds( 3 ), [&pos]() {
return pos >= .1f;
});
// Since we're locking a mutex for each position changed, let's unregister ASAP
event->unregister();
if ( success == false )
return parser::Task::Status::Error;
return parser::Task::Status::Success;
}
void VLCThumbnailer::setupVout( VLC::MediaPlayer& mp )
{
mp.setVideoFormatCallbacks(
// Setup
[this, &mp](char* chroma, unsigned int* width, unsigned int *height, unsigned int *pitches, unsigned int *lines) {
strcpy( chroma, m_compressor->fourCC() );
const float inputAR = (float)*width / *height;
m_width = DesiredWidth;
m_height = (float)m_width / inputAR + 1;
if ( m_height < DesiredHeight )
{
// Avoid downscaling too much for really wide pictures
m_width = inputAR * DesiredHeight;
m_height = DesiredHeight;
}
auto size = m_width * m_height * m_compressor->bpp();
// If our buffer isn't enough anymore, reallocate a new one.
if ( size > m_prevSize )
{
m_buff.reset( new uint8_t[size] );
m_prevSize = size;
}
*width = m_width;
*height = m_height;
*pitches = m_width * m_compressor->bpp();
*lines = m_height;
return 1;
},
// Cleanup
nullptr);
mp.setVideoCallbacks(
// Lock
[this](void** pp_buff) {
*pp_buff = m_buff.get();
return nullptr;
},
//unlock
nullptr,
//display
[this](void*) {
bool expected = true;
if ( m_thumbnailRequired.compare_exchange_strong( expected, false ) )
{
m_cond.notify_all();
}
}
);
}
parser::Task::Status VLCThumbnailer::takeThumbnail( std::shared_ptr<Media> media, std::shared_ptr<File> file, VLC::MediaPlayer &mp )
{
// lock, signal that we want a thumbnail, and wait.
{
std::unique_lock<compat::Mutex> lock( m_mutex );
m_thumbnailRequired = true;
bool success = m_cond.wait_for( lock, std::chrono::seconds( 3 ), [this]() {
// Keep waiting if the vmem thread hasn't restored m_thumbnailRequired to false
return m_thumbnailRequired == false;
});
if ( success == false )
{
LOG_WARN( "Timed out while computing ", file->mrl(), " snapshot" );
return parser::Task::Status::Error;
}
}
mp.stop();
return compress( media, file );
}
parser::Task::Status VLCThumbnailer::compress( std::shared_ptr<Media> media, std::shared_ptr<File> file )
{
auto path = m_ml->thumbnailPath();
path += "/";
path += std::to_string( media->id() ) + "." + m_compressor->extension();
auto hOffset = m_width > DesiredWidth ? ( m_width - DesiredWidth ) / 2 : 0;
auto vOffset = m_height > DesiredHeight ? ( m_height - DesiredHeight ) / 2 : 0;
if ( m_compressor->compress( m_buff.get(), path, m_width, m_height, DesiredWidth, DesiredHeight,
hOffset, vOffset ) == false )
return parser::Task::Status::Fatal;
media->setThumbnail( path );
LOG_INFO( "Done generating ", file->mrl(), " thumbnail" );
auto t = m_ml->getConn()->newTransaction();
if ( media->save() == false )
return parser::Task::Status::Error;
file->markStepCompleted( File::ParserStep::Thumbnailer );
if ( file->saveParserStep() == false )
return parser::Task::Status::Error;
t->commit();
m_notifier->notifyMediaModification( media );
return parser::Task::Status::Success;
}
const char*VLCThumbnailer::name() const
{
return "Thumbnailer";
}
uint8_t VLCThumbnailer::nbThreads() const
{
return 1;
}
}
<|endoftext|> |
<commit_before>/**
* \file
*
* \brief Plugin which acts as proxy and calls other plugins written in python
*
* \copyright BSD License (see doc/COPYING or http://www.libelektra.org)
*
*/
#ifndef SWIG_TYPE_TABLE
# error Build system error, SWIG_TYPE_TABLE is not defined
#endif
#include <Python.h>
#ifndef HAVE_KDBCONFIG
# include <kdbconfig.h>
#endif
#include <kdbhelper.h>
#include SWIG_RUNTIME
#include "python.hpp"
#include <key.hpp>
#include <keyset.hpp>
#include <libgen.h>
#include <pthread.h>
using namespace ckdb;
#include <kdberrors.h>
#define PYTHON_PLUGIN_NAME_STR2(x) ELEKTRA_QUOTE(x)
#define PYTHON_PLUGIN_NAME_STR PYTHON_PLUGIN_NAME_STR2(PYTHON_PLUGIN_NAME)
static PyObject *Python_fromSWIG(ckdb::Key *key)
{
swig_type_info *ti = SWIG_TypeQuery("kdb::Key *");
if (key == NULL || ti == NULL)
return Py_None;
return SWIG_NewPointerObj(new kdb::Key(key), ti, 0);
}
static PyObject *Python_fromSWIG(ckdb::KeySet *keyset)
{
swig_type_info *ti = SWIG_TypeQuery("kdb::KeySet *");
if (keyset == NULL || ti == NULL)
return Py_None;
return SWIG_NewPointerObj(new kdb::KeySet(keyset), ti, 0);
}
extern "C"
{
typedef struct
{
PyObject *instance;
int printError;
int shutdown;
} moduleData;
/* pythons repr() - a little debug helper - misses all Py_DECREF calls! */
#define Python_Repr(obj) \
PyBytes_AS_STRING( \
PyUnicode_AsEncodedString(PyObject_Repr(obj), "utf-8", "Error ~") \
)
static PyObject *Python_ImportModule(const char *name)
{
if (!name)
return NULL;
PyGILState_STATE gstate = PyGILState_Ensure();
PyObject *module = PyImport_ImportModule(name);
PyGILState_Release(gstate);
return module;
}
static PyObject *Python_CallFunction(PyObject *object, PyObject *args)
{
PyGILState_STATE gstate = PyGILState_Ensure();
if (!PyCallable_Check(object))
{
PyGILState_Release(gstate);
return NULL;
}
PyObject *res = PyObject_CallObject(object, args ? args : PyTuple_New (0));
PyGILState_Release(gstate);
Py_XINCREF(res);
return res;
}
static int Python_CallFunction_Int(moduleData *data, PyObject *object,
PyObject *args, ckdb::Key *errorKey)
{
int ret = -1;
PyGILState_STATE gstate = PyGILState_Ensure();
PyObject *res = Python_CallFunction(object, args);
if (!res)
{
ELEKTRA_SET_ERROR(111, errorKey,
"Error while calling python function");
if (data->printError)
PyErr_Print();
}
else
{
#if PY_MAJOR_VERSION >= 3
if (!PyLong_Check(res))
#else
if (!PyInt_Check(res))
#endif
ELEKTRA_SET_ERROR(111, errorKey,
"Return value is no integer");
else
ret = PyLong_AsLong(res);
}
PyGILState_Release(gstate);
Py_XDECREF(res);
return ret;
}
static int Python_CallFunction_Helper1(moduleData *data, const char *funcName,
ckdb::Key *errorKey)
{
int ret = 0;
PyGILState_STATE gstate = PyGILState_Ensure();
PyObject *func = PyObject_GetAttrString(data->instance, funcName);
if (func)
{
PyObject *arg0 = Python_fromSWIG(errorKey);
PyObject *args = Py_BuildValue("(O)", arg0);
ret = Python_CallFunction_Int(data, func, args, errorKey);
Py_DECREF(arg0);
Py_DECREF(args);
Py_DECREF(func);
}
PyGILState_Release(gstate);
return ret;
}
static int Python_CallFunction_Helper2(moduleData *data, const char *funcName,
ckdb::KeySet *returned, ckdb::Key *parentKey)
{
int ret = 0;
PyGILState_STATE gstate = PyGILState_Ensure();
PyObject *func = PyObject_GetAttrString(data->instance, funcName);
if (func)
{
PyObject *arg0 = Python_fromSWIG(returned);
PyObject *arg1 = Python_fromSWIG(parentKey);
PyObject *args = Py_BuildValue("(OO)", arg0, arg1);
ret = Python_CallFunction_Int(data, func, args, parentKey);
Py_DECREF(arg0);
Py_DECREF(arg1);
Py_DECREF(args);
Py_DECREF(func);
}
PyGILState_Release(gstate);
return ret;
}
static int Python_AppendToSysPath(const char *path)
{
if (path == NULL)
return 0;
PyGILState_STATE gstate = PyGILState_Ensure();
PyObject *sysPath = PySys_GetObject((char *)"path");
PyObject *pyPath = PyUnicode_FromString(path);
PyList_Append(sysPath, pyPath);
Py_DECREF(pyPath);
PyGILState_Release(gstate);
return 1;
}
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static unsigned open_cnt = 0;
static void Python_Shutdown(moduleData *data)
{
/* destroy python if plugin isn't used anymore */
//FIXME python reinitialization is known to be buggy
pthread_mutex_lock(&mutex);
if (Py_IsInitialized() && !--open_cnt && data->shutdown) // order matters!
Py_Finalize();
pthread_mutex_unlock(&mutex);
}
int PYTHON_PLUGIN_FUNCTION(Open)(ckdb::Plugin *handle, ckdb::Key *errorKey)
{
KeySet *config = elektraPluginGetConfig(handle);
Key *script = ksLookupByName(config, "/script", 0);
if (script == NULL)
return 0; // success if no script to execute
if (keyString(script) == NULL)
{
ELEKTRA_SET_ERROR(111, errorKey, "No python script set");
return -1;
}
/* create module data */
moduleData *data = new moduleData;
data->instance = NULL;
data->printError = (ksLookupByName(config, "/print", 0) != NULL);
/* shutdown flag is integer by design. This way users can set the
* expected behaviour without worring about default values
*/
data->shutdown = (ksLookupByName(config, "/shutdown", 0) &&
!!strcmp(keyString(ksLookupByName(config, "/shutdown", 0)), "0"));
{
/* initialize python interpreter - only once */
pthread_mutex_lock(&mutex);
if (!Py_IsInitialized())
{
Py_Initialize();
PyEval_InitThreads();
if (!Py_IsInitialized())
{
pthread_mutex_unlock(&mutex);
goto error;
}
}
open_cnt++;
pthread_mutex_unlock(&mutex);
/* import kdb */
PyObject *kdbModule = Python_ImportModule("kdb");
if (kdbModule == NULL)
{
ELEKTRA_SET_ERROR(111, errorKey, "Unable to import kdb module");
goto error_print;
}
Py_XDECREF(kdbModule);
/* extend sys path */
char *tmpScript = elektraStrDup(keyString(script));
const char *dname = dirname(tmpScript);
if (!Python_AppendToSysPath(dname))
{
ELEKTRA_SET_ERROR(111, errorKey, "Unable to extend sys.path");
elektraFree(tmpScript);
goto error;
}
elektraFree(tmpScript);
/* import module/script */
tmpScript = elektraStrDup(keyString(script));
char *bname = basename(tmpScript);
size_t bname_len = strlen(bname);
if (bname_len >= 4 && strcmp(bname + bname_len - 3, ".py") == 0)
bname[bname_len - 3] = '\0';
PyObject *pModule = Python_ImportModule(bname);
if (pModule == NULL)
{
ELEKTRA_SET_ERRORF(111, errorKey,"Unable to import python script %s",
keyString(script));
elektraFree(tmpScript);
goto error_print;
}
elektraFree(tmpScript);
/* get class */
PyGILState_STATE gstate = PyGILState_Ensure();
PyObject *klass = PyObject_GetAttrString(pModule, "ElektraPlugin");
Py_DECREF(pModule);
PyGILState_Release(gstate);
if (klass == NULL)
{
ELEKTRA_SET_ERROR(111, errorKey,
"Module doesn't provide a ElektraPlugin class");
goto error_print;
}
/* create instance of class */
gstate = PyGILState_Ensure();
PyObject *inst_args = Py_BuildValue("()");
PyObject *inst = PyEval_CallObject(klass, inst_args);
Py_DECREF(klass);
Py_DECREF(inst_args);
PyGILState_Release(gstate);
if (inst == NULL)
{
ELEKTRA_SET_ERROR(111, errorKey,
"Unable to create instance of ElektraPlugin");
goto error_print;
}
data->instance = inst;
}
/* store module data after everything is set up */
elektraPluginSetData(handle, data);
/* call python function */
return Python_CallFunction_Helper1(data, "open", errorKey);
error_print:
if (data->printError)
PyErr_Print();
error:
/* destroy python */
Python_Shutdown(data);
delete data;
return -1;
}
int PYTHON_PLUGIN_FUNCTION(Close)(ckdb::Plugin *handle, ckdb::Key *errorKey)
{
moduleData *data = static_cast<moduleData *>(elektraPluginGetData(handle));
if (data == NULL)
return 0;
/* call python function */
int ret = 0;
if (data != NULL)
{
PyGILState_STATE gstate = PyGILState_Ensure();
ret = Python_CallFunction_Helper1(data, "close", errorKey);
/* clean up references */
Py_DECREF(data->instance);
data->instance = NULL;
PyGILState_Release(gstate);
}
/* destroy python */
Python_Shutdown(data);
delete data;
return ret;
}
int PYTHON_PLUGIN_FUNCTION(Get)(ckdb::Plugin *handle, ckdb::KeySet *returned,
ckdb::Key *parentKey)
{
#define _MODULE_CONFIG_PATH "system/elektra/modules/" PYTHON_PLUGIN_NAME_STR
if (!strcmp(keyName(parentKey), _MODULE_CONFIG_PATH))
{
KeySet *n;
ksAppend(returned, n = ksNew(30,
keyNew(_MODULE_CONFIG_PATH,
KEY_VALUE, "python interpreter waits for your orders", KEY_END),
keyNew(_MODULE_CONFIG_PATH "/exports", KEY_END),
keyNew(_MODULE_CONFIG_PATH "/exports/get",
KEY_FUNC, PYTHON_PLUGIN_FUNCTION(Get),
KEY_END),
keyNew(_MODULE_CONFIG_PATH "/exports/set",
KEY_FUNC, PYTHON_PLUGIN_FUNCTION(Set),
KEY_END),
keyNew(_MODULE_CONFIG_PATH "/exports/error",
KEY_FUNC, PYTHON_PLUGIN_FUNCTION(Error),
KEY_END),
keyNew(_MODULE_CONFIG_PATH "/exports/open",
KEY_FUNC, PYTHON_PLUGIN_FUNCTION(Open),
KEY_END),
keyNew(_MODULE_CONFIG_PATH "/exports/close",
KEY_FUNC, PYTHON_PLUGIN_FUNCTION(Close),
KEY_END),
#include ELEKTRA_README(PYTHON_PLUGIN_NAME)
keyNew(_MODULE_CONFIG_PATH "/infos/version",
KEY_VALUE, PLUGINVERSION, KEY_END),
KS_END));
ksDel(n);
}
moduleData *data = static_cast<moduleData *>(elektraPluginGetData(handle));
if (data != NULL)
return Python_CallFunction_Helper2(data, "get", returned,
parentKey);
return 0;
}
int PYTHON_PLUGIN_FUNCTION(Set)(ckdb::Plugin *handle, ckdb::KeySet *returned,
ckdb::Key *parentKey)
{
moduleData *data = static_cast<moduleData *>(elektraPluginGetData(handle));
if (data != NULL)
return Python_CallFunction_Helper2(data, "set", returned,
parentKey);
return 0;
}
int PYTHON_PLUGIN_FUNCTION(Error)(ckdb::Plugin *handle, ckdb::KeySet *returned,
ckdb::Key *parentKey)
{
moduleData *data = static_cast<moduleData *>(elektraPluginGetData(handle));
if (data != NULL)
return Python_CallFunction_Helper2(data, "error", returned,
parentKey);
return 0;
}
ckdb::Plugin *PYTHON_PLUGIN_EXPORT(PYTHON_PLUGIN_NAME)
{
return elektraPluginExport(PYTHON_PLUGIN_NAME_STR,
ELEKTRA_PLUGIN_OPEN, &PYTHON_PLUGIN_FUNCTION(Open),
ELEKTRA_PLUGIN_CLOSE, &PYTHON_PLUGIN_FUNCTION(Close),
ELEKTRA_PLUGIN_GET, &PYTHON_PLUGIN_FUNCTION(Get),
ELEKTRA_PLUGIN_SET, &PYTHON_PLUGIN_FUNCTION(Set),
ELEKTRA_PLUGIN_ERROR, &PYTHON_PLUGIN_FUNCTION(Error),
ELEKTRA_PLUGIN_END);
}
}
<commit_msg>python: fix check for /module<commit_after>/**
* \file
*
* \brief Plugin which acts as proxy and calls other plugins written in python
*
* \copyright BSD License (see doc/COPYING or http://www.libelektra.org)
*
*/
#ifndef SWIG_TYPE_TABLE
# error Build system error, SWIG_TYPE_TABLE is not defined
#endif
#include <Python.h>
#ifndef HAVE_KDBCONFIG
# include <kdbconfig.h>
#endif
#include <kdbhelper.h>
#include SWIG_RUNTIME
#include "python.hpp"
#include <key.hpp>
#include <keyset.hpp>
#include <libgen.h>
#include <pthread.h>
using namespace ckdb;
#include <kdberrors.h>
#define PYTHON_PLUGIN_NAME_STR2(x) ELEKTRA_QUOTE(x)
#define PYTHON_PLUGIN_NAME_STR PYTHON_PLUGIN_NAME_STR2(PYTHON_PLUGIN_NAME)
static PyObject *Python_fromSWIG(ckdb::Key *key)
{
swig_type_info *ti = SWIG_TypeQuery("kdb::Key *");
if (key == NULL || ti == NULL)
return Py_None;
return SWIG_NewPointerObj(new kdb::Key(key), ti, 0);
}
static PyObject *Python_fromSWIG(ckdb::KeySet *keyset)
{
swig_type_info *ti = SWIG_TypeQuery("kdb::KeySet *");
if (keyset == NULL || ti == NULL)
return Py_None;
return SWIG_NewPointerObj(new kdb::KeySet(keyset), ti, 0);
}
extern "C"
{
typedef struct
{
PyObject *instance;
int printError;
int shutdown;
} moduleData;
/* pythons repr() - a little debug helper - misses all Py_DECREF calls! */
#define Python_Repr(obj) \
PyBytes_AS_STRING( \
PyUnicode_AsEncodedString(PyObject_Repr(obj), "utf-8", "Error ~") \
)
static PyObject *Python_ImportModule(const char *name)
{
if (!name)
return NULL;
PyGILState_STATE gstate = PyGILState_Ensure();
PyObject *module = PyImport_ImportModule(name);
PyGILState_Release(gstate);
return module;
}
static PyObject *Python_CallFunction(PyObject *object, PyObject *args)
{
PyGILState_STATE gstate = PyGILState_Ensure();
if (!PyCallable_Check(object))
{
PyGILState_Release(gstate);
return NULL;
}
PyObject *res = PyObject_CallObject(object, args ? args : PyTuple_New (0));
PyGILState_Release(gstate);
Py_XINCREF(res);
return res;
}
static int Python_CallFunction_Int(moduleData *data, PyObject *object,
PyObject *args, ckdb::Key *errorKey)
{
int ret = -1;
PyGILState_STATE gstate = PyGILState_Ensure();
PyObject *res = Python_CallFunction(object, args);
if (!res)
{
ELEKTRA_SET_ERROR(111, errorKey,
"Error while calling python function");
if (data->printError)
PyErr_Print();
}
else
{
#if PY_MAJOR_VERSION >= 3
if (!PyLong_Check(res))
#else
if (!PyInt_Check(res))
#endif
ELEKTRA_SET_ERROR(111, errorKey,
"Return value is no integer");
else
ret = PyLong_AsLong(res);
}
PyGILState_Release(gstate);
Py_XDECREF(res);
return ret;
}
static int Python_CallFunction_Helper1(moduleData *data, const char *funcName,
ckdb::Key *errorKey)
{
int ret = 0;
PyGILState_STATE gstate = PyGILState_Ensure();
PyObject *func = PyObject_GetAttrString(data->instance, funcName);
if (func)
{
PyObject *arg0 = Python_fromSWIG(errorKey);
PyObject *args = Py_BuildValue("(O)", arg0);
ret = Python_CallFunction_Int(data, func, args, errorKey);
Py_DECREF(arg0);
Py_DECREF(args);
Py_DECREF(func);
}
PyGILState_Release(gstate);
return ret;
}
static int Python_CallFunction_Helper2(moduleData *data, const char *funcName,
ckdb::KeySet *returned, ckdb::Key *parentKey)
{
int ret = 0;
PyGILState_STATE gstate = PyGILState_Ensure();
PyObject *func = PyObject_GetAttrString(data->instance, funcName);
if (func)
{
PyObject *arg0 = Python_fromSWIG(returned);
PyObject *arg1 = Python_fromSWIG(parentKey);
PyObject *args = Py_BuildValue("(OO)", arg0, arg1);
ret = Python_CallFunction_Int(data, func, args, parentKey);
Py_DECREF(arg0);
Py_DECREF(arg1);
Py_DECREF(args);
Py_DECREF(func);
}
PyGILState_Release(gstate);
return ret;
}
static int Python_AppendToSysPath(const char *path)
{
if (path == NULL)
return 0;
PyGILState_STATE gstate = PyGILState_Ensure();
PyObject *sysPath = PySys_GetObject((char *)"path");
PyObject *pyPath = PyUnicode_FromString(path);
PyList_Append(sysPath, pyPath);
Py_DECREF(pyPath);
PyGILState_Release(gstate);
return 1;
}
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static unsigned open_cnt = 0;
static void Python_Shutdown(moduleData *data)
{
/* destroy python if plugin isn't used anymore */
//FIXME python reinitialization is known to be buggy
pthread_mutex_lock(&mutex);
if (Py_IsInitialized() && !--open_cnt && data->shutdown) // order matters!
Py_Finalize();
pthread_mutex_unlock(&mutex);
}
int PYTHON_PLUGIN_FUNCTION(Open)(ckdb::Plugin *handle, ckdb::Key *errorKey)
{
KeySet *config = elektraPluginGetConfig(handle);
if (ksLookupByName(config, "/module", 0) != NULL)
return 0; // by convention: success if /module exists
Key *script = ksLookupByName(config, "/script", 0);
if (script == NULL || !strlen(keyString(script)))
{
ELEKTRA_SET_ERROR(111, errorKey, "No python script set");
return -1;
}
/* create module data */
moduleData *data = new moduleData;
data->instance = NULL;
data->printError = (ksLookupByName(config, "/print", 0) != NULL);
/* shutdown flag is integer by design. This way users can set the
* expected behaviour without worring about default values
*/
data->shutdown = (ksLookupByName(config, "/shutdown", 0) &&
!!strcmp(keyString(ksLookupByName(config, "/shutdown", 0)), "0"));
{
/* initialize python interpreter - only once */
pthread_mutex_lock(&mutex);
if (!Py_IsInitialized())
{
Py_Initialize();
PyEval_InitThreads();
if (!Py_IsInitialized())
{
pthread_mutex_unlock(&mutex);
goto error;
}
}
open_cnt++;
pthread_mutex_unlock(&mutex);
/* import kdb */
PyObject *kdbModule = Python_ImportModule("kdb");
if (kdbModule == NULL)
{
ELEKTRA_SET_ERROR(111, errorKey, "Unable to import kdb module");
goto error_print;
}
Py_XDECREF(kdbModule);
/* extend sys path */
char *tmpScript = elektraStrDup(keyString(script));
const char *dname = dirname(tmpScript);
if (!Python_AppendToSysPath(dname))
{
ELEKTRA_SET_ERROR(111, errorKey, "Unable to extend sys.path");
elektraFree(tmpScript);
goto error;
}
elektraFree(tmpScript);
/* import module/script */
tmpScript = elektraStrDup(keyString(script));
char *bname = basename(tmpScript);
size_t bname_len = strlen(bname);
if (bname_len >= 4 && strcmp(bname + bname_len - 3, ".py") == 0)
bname[bname_len - 3] = '\0';
PyObject *pModule = Python_ImportModule(bname);
if (pModule == NULL)
{
ELEKTRA_SET_ERRORF(111, errorKey,"Unable to import python script %s",
keyString(script));
elektraFree(tmpScript);
goto error_print;
}
elektraFree(tmpScript);
/* get class */
PyGILState_STATE gstate = PyGILState_Ensure();
PyObject *klass = PyObject_GetAttrString(pModule, "ElektraPlugin");
Py_DECREF(pModule);
PyGILState_Release(gstate);
if (klass == NULL)
{
ELEKTRA_SET_ERROR(111, errorKey,
"Module doesn't provide a ElektraPlugin class");
goto error_print;
}
/* create instance of class */
gstate = PyGILState_Ensure();
PyObject *inst_args = Py_BuildValue("()");
PyObject *inst = PyEval_CallObject(klass, inst_args);
Py_DECREF(klass);
Py_DECREF(inst_args);
PyGILState_Release(gstate);
if (inst == NULL)
{
ELEKTRA_SET_ERROR(111, errorKey,
"Unable to create instance of ElektraPlugin");
goto error_print;
}
data->instance = inst;
}
/* store module data after everything is set up */
elektraPluginSetData(handle, data);
/* call python function */
return Python_CallFunction_Helper1(data, "open", errorKey);
error_print:
if (data->printError)
PyErr_Print();
error:
/* destroy python */
Python_Shutdown(data);
delete data;
return -1;
}
int PYTHON_PLUGIN_FUNCTION(Close)(ckdb::Plugin *handle, ckdb::Key *errorKey)
{
moduleData *data = static_cast<moduleData *>(elektraPluginGetData(handle));
if (data == NULL)
return 0;
/* call python function */
int ret = 0;
if (data != NULL)
{
PyGILState_STATE gstate = PyGILState_Ensure();
ret = Python_CallFunction_Helper1(data, "close", errorKey);
/* clean up references */
Py_DECREF(data->instance);
data->instance = NULL;
PyGILState_Release(gstate);
}
/* destroy python */
Python_Shutdown(data);
delete data;
return ret;
}
int PYTHON_PLUGIN_FUNCTION(Get)(ckdb::Plugin *handle, ckdb::KeySet *returned,
ckdb::Key *parentKey)
{
#define _MODULE_CONFIG_PATH "system/elektra/modules/" PYTHON_PLUGIN_NAME_STR
if (!strcmp(keyName(parentKey), _MODULE_CONFIG_PATH))
{
KeySet *n;
ksAppend(returned, n = ksNew(30,
keyNew(_MODULE_CONFIG_PATH,
KEY_VALUE, "python interpreter waits for your orders", KEY_END),
keyNew(_MODULE_CONFIG_PATH "/exports", KEY_END),
keyNew(_MODULE_CONFIG_PATH "/exports/get",
KEY_FUNC, PYTHON_PLUGIN_FUNCTION(Get),
KEY_END),
keyNew(_MODULE_CONFIG_PATH "/exports/set",
KEY_FUNC, PYTHON_PLUGIN_FUNCTION(Set),
KEY_END),
keyNew(_MODULE_CONFIG_PATH "/exports/error",
KEY_FUNC, PYTHON_PLUGIN_FUNCTION(Error),
KEY_END),
keyNew(_MODULE_CONFIG_PATH "/exports/open",
KEY_FUNC, PYTHON_PLUGIN_FUNCTION(Open),
KEY_END),
keyNew(_MODULE_CONFIG_PATH "/exports/close",
KEY_FUNC, PYTHON_PLUGIN_FUNCTION(Close),
KEY_END),
#include ELEKTRA_README(PYTHON_PLUGIN_NAME)
keyNew(_MODULE_CONFIG_PATH "/infos/version",
KEY_VALUE, PLUGINVERSION, KEY_END),
KS_END));
ksDel(n);
}
moduleData *data = static_cast<moduleData *>(elektraPluginGetData(handle));
if (data != NULL)
return Python_CallFunction_Helper2(data, "get", returned,
parentKey);
return 0;
}
int PYTHON_PLUGIN_FUNCTION(Set)(ckdb::Plugin *handle, ckdb::KeySet *returned,
ckdb::Key *parentKey)
{
moduleData *data = static_cast<moduleData *>(elektraPluginGetData(handle));
if (data != NULL)
return Python_CallFunction_Helper2(data, "set", returned,
parentKey);
return 0;
}
int PYTHON_PLUGIN_FUNCTION(Error)(ckdb::Plugin *handle, ckdb::KeySet *returned,
ckdb::Key *parentKey)
{
moduleData *data = static_cast<moduleData *>(elektraPluginGetData(handle));
if (data != NULL)
return Python_CallFunction_Helper2(data, "error", returned,
parentKey);
return 0;
}
ckdb::Plugin *PYTHON_PLUGIN_EXPORT(PYTHON_PLUGIN_NAME)
{
return elektraPluginExport(PYTHON_PLUGIN_NAME_STR,
ELEKTRA_PLUGIN_OPEN, &PYTHON_PLUGIN_FUNCTION(Open),
ELEKTRA_PLUGIN_CLOSE, &PYTHON_PLUGIN_FUNCTION(Close),
ELEKTRA_PLUGIN_GET, &PYTHON_PLUGIN_FUNCTION(Get),
ELEKTRA_PLUGIN_SET, &PYTHON_PLUGIN_FUNCTION(Set),
ELEKTRA_PLUGIN_ERROR, &PYTHON_PLUGIN_FUNCTION(Error),
ELEKTRA_PLUGIN_END);
}
}
<|endoftext|> |
<commit_before>
/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkTypes.h"
static const size_t kBufferSize = 256;
#define LOG_TAG "skia"
#include <android/log.h>
void SkDebugf(const char format[], ...) {
va_list args;
va_start(args, format);
__android_log_vprint(ANDROID_LOG_DEBUG, LOG_TAG, format, args);
va_end(args);
}
<commit_msg>Enable Android executables (like skia_launcher) to redirect SkDebugf output to stdout as well as the system logs.<commit_after>
/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkTypes.h"
static const size_t kBufferSize = 256;
#define LOG_TAG "skia"
#include <android/log.h>
static bool gSkDebugToStdOut = false;
extern "C" void AndroidSkDebugToStdOut(bool debugToStdOut) {
gSkDebugToStdOut = debugToStdOut;
}
void SkDebugf(const char format[], ...) {
va_list args;
va_start(args, format);
__android_log_vprint(ANDROID_LOG_DEBUG, LOG_TAG, format, args);
// Print debug output to stdout as well. This is useful for command
// line applications (e.g. skia_launcher)
if (gSkDebugToStdOut) {
vprintf(format, args);
}
va_end(args);
}
<|endoftext|> |
<commit_before>/*
* This source file is part of EasyPaint.
*
* Copyright (c) 2012 EasyPaint <https://github.com/Gr1N/EasyPaint>
*
* 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 "mainwindow.h"
#include "toolbar.h"
#include "imagearea.h"
#include <QtGui/QApplication>
#include <QtGui/QAction>
#include <QtGui/QMenu>
#include <QtGui/QMenuBar>
#include <QtGui/QStatusBar>
#include <QtGui/QMessageBox>
#include <QtGui/QScrollArea>
#include <QtGui/QLabel>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
initializeMainMenu();
initializeToolBar();
initializeStatusBar();
initializeTabWidget();
}
MainWindow::~MainWindow()
{
}
void MainWindow::initializeTabWidget()
{
mTabWidget = new QTabWidget();
mTabWidget->setUsesScrollButtons(true);
mTabWidget->setTabsClosable(true);
mTabWidget->setMovable(true);
connect(mTabWidget, SIGNAL(currentChanged(int)), this, SLOT(activateTab(int)));
setCentralWidget(mTabWidget);
initializeNewTab();
}
void MainWindow::initializeNewTab(const bool &isOpen)
{
ImageArea *imageArea;
QString fileName("new");
if(isOpen)
{
imageArea = new ImageArea(isOpen);
fileName = imageArea->getFileName();
}
else
{
imageArea = new ImageArea();
}
QScrollArea *scrollArea = new QScrollArea();
scrollArea->setAttribute(Qt::WA_DeleteOnClose);
scrollArea->setBackgroundRole(QPalette::Dark);
scrollArea->setWidget(imageArea);
mTabWidget->addTab(scrollArea, fileName);
mTabWidget->setCurrentIndex(mTabWidget->count()-1);
connect(imageArea, SIGNAL(sendFirstColorView()), mToolbar, SLOT(setFirstColorView()));
connect(imageArea, SIGNAL(sendSecondColorView()), mToolbar, SLOT(setSecondColorView()));
connect(imageArea, SIGNAL(sendNewImageSize(QSize)), this, SLOT(setNewSizeToSizeLabel(QSize)));
connect(imageArea, SIGNAL(sendCursorPos(QPoint)), this, SLOT(setNewPosToPosLabel(QPoint)));
}
void MainWindow::initializeMainMenu()
{
QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
QAction *newAction = new QAction(tr("&New"), this);
newAction->setShortcut(QKeySequence::New);
newAction->setIcon(QIcon::fromTheme("document-new"/*, QIcon("")*/));
// newAction->setStatusTip();
connect(newAction, SIGNAL(triggered()), this, SLOT(newAct()));
fileMenu->addAction(newAction);
QAction *openAction = new QAction(tr("&Open"), this);
openAction->setShortcut(QKeySequence::Open);
openAction->setIcon(QIcon::fromTheme("document-open"/*, QIcon("")*/));
// newAction->setStatusTip();
connect(openAction, SIGNAL(triggered()), this, SLOT(openAct()));
fileMenu->addAction(openAction);
QAction *saveAction = new QAction(tr("&Save"), this);
saveAction->setShortcut(QKeySequence::Save);
saveAction->setIcon(QIcon::fromTheme("document-save"/*, QIcon("")*/));
// newAction->setStatusTip();
connect(saveAction, SIGNAL(triggered()), this, SLOT(saveAct()));
fileMenu->addAction(saveAction);
QAction *saveAsAction = new QAction(tr("Save as..."), this);
saveAsAction->setShortcut(QKeySequence::SaveAs);
saveAsAction->setIcon(QIcon::fromTheme("document-save-as"/*, QIcon("")*/));
// newAction->setStatusTip();
connect(saveAsAction, SIGNAL(triggered()), this, SLOT(saveAsAct()));
fileMenu->addAction(saveAsAction);
QAction *closeAction = new QAction(tr("&Close"), this);
closeAction->setShortcut(QKeySequence::Close);
closeAction->setIcon(QIcon::fromTheme("window-close"/*, QIcon("")*/));
// newAction->setStatusTip();
// connect();
fileMenu->addAction(closeAction);
fileMenu->addSeparator();
QAction *printAction = new QAction(tr("&Print"), this);
printAction->setShortcut(QKeySequence::Print);
printAction->setIcon(QIcon::fromTheme("document-print"/*, QIcon("")*/));
// newAction->setStatusTip();
connect(printAction, SIGNAL(triggered()), this, SLOT(printAct()));
fileMenu->addAction(printAction);
fileMenu->addSeparator();
QAction *exitAction = new QAction(tr("&Exit"), this);
exitAction->setShortcut(QKeySequence::Quit);
exitAction->setIcon(QIcon::fromTheme("application-exit"/*, QIcon("")*/));
// newAction->setStatusTip();
// connect();
fileMenu->addAction(exitAction);
QMenu *editMenu = menuBar()->addMenu(tr("&Edit"));
QAction *undoAction = new QAction(tr("&Undo"), this);
undoAction->setShortcut(QKeySequence::Undo);
undoAction->setIcon(QIcon::fromTheme("edit-undo"/*, QIcon("")*/));
// newAction->setStatusTip();
// connect();
editMenu->addAction(undoAction);
QAction *redoAction = new QAction(tr("&Redo"), this);
redoAction->setShortcut(QKeySequence::Redo);
redoAction->setIcon(QIcon::fromTheme("edit-redo"/*, QIcon("")*/));
// newAction->setStatusTip();
// connect();
editMenu->addAction(redoAction);
editMenu->addSeparator();
QAction *copyAction = new QAction(tr("&Copy"), this);
copyAction->setShortcut(QKeySequence::Copy);
copyAction->setIcon(QIcon::fromTheme("edit-copy"/*, QIcon("")*/));
// newAction->setStatusTip();
// connect();
editMenu->addAction(copyAction);
QAction *pasteAction = new QAction(tr("&Paste"), this);
pasteAction->setShortcut(QKeySequence::Paste);
pasteAction->setIcon(QIcon::fromTheme("edit-paste"/*, QIcon("")*/));
// newAction->setStatusTip();
// connect();
editMenu->addAction(pasteAction);
QAction *cutAction = new QAction(tr("C&ut"), this);
cutAction->setShortcut(QKeySequence::Cut);
cutAction->setIcon(QIcon::fromTheme("edit-cut"/*, QIcon("")*/));
// newAction->setStatusTip();
// connect();
editMenu->addAction(cutAction);
editMenu->addSeparator();
QAction *settingsAction = new QAction(tr("&Settings"), this);
settingsAction->setShortcut(QKeySequence::Preferences);
settingsAction->setIcon(QIcon::fromTheme("document-properties"/*, QIcon("")*/));
// newAction->setStatusTip();
// connect();
editMenu->addAction(settingsAction);
QMenu *effectsMenu = menuBar()->addMenu(tr("E&ffects"));
QAction *grayEfAction = new QAction(tr("Gray"), this);
// newAction->setStatusTip();
connect(grayEfAction, SIGNAL(triggered()), this, SLOT(effectGrayAct()));
effectsMenu->addAction(grayEfAction);
QAction *negativeEfAction = new QAction(tr("Negative"), this);
// newAction->setStatusTip();
connect(negativeEfAction, SIGNAL(triggered()), this, SLOT(effectNegativeAct()));
effectsMenu->addAction(negativeEfAction);
QMenu *toolsMenu = menuBar()->addMenu(tr("&Tools"));
QAction *resizeImAction = new QAction(tr("Resize"), this);
// newAction->setStatusTip();
connect(resizeImAction, SIGNAL(triggered()), this, SLOT(resizeImageAct()));
toolsMenu->addAction(resizeImAction);
QMenu *rotateMenu = new QMenu(tr("Rotate"));
QAction *rotateLAction = new QAction(tr("Left"), this);
rotateLAction->setIcon(QIcon::fromTheme("object-rotate-left"/*, QIcon("")*/));
// newAction->setStatusTip();
connect(rotateLAction, SIGNAL(triggered()), this, SLOT(rotateLeftImageAct()));
rotateMenu->addAction(rotateLAction);
QAction *rotateRAction = new QAction(tr("Right"), this);
rotateRAction->setIcon(QIcon::fromTheme("object-rotate-right"/*, QIcon("")*/));
// newAction->setStatusTip();
connect(rotateRAction, SIGNAL(triggered()), this, SLOT(rotateRightImageAct()));
rotateMenu->addAction(rotateRAction);
toolsMenu->addMenu(rotateMenu);
QMenu *aboutMenu = menuBar()->addMenu(tr("&About"));
QAction *aboutAction = new QAction(tr("&About"), this);
aboutAction->setShortcut(QKeySequence::HelpContents);
aboutAction->setIcon(QIcon::fromTheme("help-browser"/*, QIcon("")*/));
// newAction->setStatusTip();
connect(aboutAction, SIGNAL(triggered()), this, SLOT(helpAct()));
aboutMenu->addAction(aboutAction);
QAction *aboutQtAction = new QAction(tr("About Qt"), this);
// newAction->setStatusTip();
connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
aboutMenu->addAction(aboutQtAction);
}
void MainWindow::initializeStatusBar()
{
mStatusBar = new QStatusBar();
setStatusBar(mStatusBar);
mSizeLabel = new QLabel();
mPosLabel = new QLabel();
mStatusBar->addPermanentWidget(mSizeLabel, -1);
mStatusBar->addPermanentWidget(mPosLabel, 1);
}
void MainWindow::initializeToolBar()
{
mToolbar = new ToolBar(this);
addToolBar(Qt::LeftToolBarArea, mToolbar);
}
ImageArea* MainWindow::getCurrentImageArea()
{
QScrollArea *tempScrollArea = qobject_cast<QScrollArea*>(mTabWidget->currentWidget());
ImageArea *tempArea = qobject_cast<ImageArea*>(tempScrollArea->widget());
return tempArea;
}
void MainWindow::activateTab(const int &index)
{
mTabWidget->setCurrentIndex(index);
QSize size = getCurrentImageArea()->getImage()->size();
mSizeLabel->setText(QString("%1 x %2").arg(size.width()).arg(size.height()));
}
void MainWindow::setNewSizeToSizeLabel(const QSize &size)
{
mSizeLabel->setText(QString("%1 x %2").arg(size.width()).arg(size.height()));
}
void MainWindow::setNewPosToPosLabel(const QPoint &pos)
{
mPosLabel->setText(QString("%1,%2").arg(pos.x()).arg(pos.y()));
}
void MainWindow::newAct()
{
initializeNewTab();
}
void MainWindow::openAct()
{
initializeNewTab(true);
}
void MainWindow::saveAct()
{
getCurrentImageArea()->save();
mTabWidget->setTabText(mTabWidget->currentIndex(), getCurrentImageArea()->getFileName());
}
void MainWindow::saveAsAct()
{
getCurrentImageArea()->saveAs();
mTabWidget->setTabText(mTabWidget->currentIndex(), getCurrentImageArea()->getFileName());
}
void MainWindow::printAct()
{
getCurrentImageArea()->print();
}
void MainWindow::effectGrayAct()
{
getCurrentImageArea()->effectGray();
}
void MainWindow::effectNegativeAct()
{
getCurrentImageArea()->effectNegative();
}
void MainWindow::resizeImageAct()
{
getCurrentImageArea()->resizeImage();
}
void MainWindow::rotateLeftImageAct()
{
getCurrentImageArea()->rotateImage(true);
}
void MainWindow::rotateRightImageAct()
{
getCurrentImageArea()->rotateImage(false);
}
void MainWindow::helpAct()
{
QMessageBox::about(this, tr("About EasyPaint"),
QString("EasyPaint version: %1 <br> <br> Site: "
"<a href=\"https://github.com/Gr1N/EasyPaint/\">https://github.com/Gr1N/EasyPaint/</a>"
"<br> <br>Copyright (c) 2012 Nikita Grishko"
"<br> <br>Authors:<ul>"
"<li>Nikita Grishko (Gr1N)</li>"
"</ul>")
.arg(tr("0.0.1")));
}
<commit_msg>Cloced Issue #22. Canceling open dialog.<commit_after>/*
* This source file is part of EasyPaint.
*
* Copyright (c) 2012 EasyPaint <https://github.com/Gr1N/EasyPaint>
*
* 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 "mainwindow.h"
#include "toolbar.h"
#include "imagearea.h"
#include <QtGui/QApplication>
#include <QtGui/QAction>
#include <QtGui/QMenu>
#include <QtGui/QMenuBar>
#include <QtGui/QStatusBar>
#include <QtGui/QMessageBox>
#include <QtGui/QScrollArea>
#include <QtGui/QLabel>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
initializeMainMenu();
initializeToolBar();
initializeStatusBar();
initializeTabWidget();
}
MainWindow::~MainWindow()
{
}
void MainWindow::initializeTabWidget()
{
mTabWidget = new QTabWidget();
mTabWidget->setUsesScrollButtons(true);
mTabWidget->setTabsClosable(true);
mTabWidget->setMovable(true);
connect(mTabWidget, SIGNAL(currentChanged(int)), this, SLOT(activateTab(int)));
setCentralWidget(mTabWidget);
initializeNewTab();
}
void MainWindow::initializeNewTab(const bool &isOpen)
{
ImageArea *imageArea;
QString fileName("new");
if(isOpen)
{
imageArea = new ImageArea(isOpen);
fileName = imageArea->getFileName();
}
else
{
imageArea = new ImageArea();
}
if (!fileName.isEmpty())
{
QScrollArea *scrollArea = new QScrollArea();
scrollArea->setAttribute(Qt::WA_DeleteOnClose);
scrollArea->setBackgroundRole(QPalette::Dark);
scrollArea->setWidget(imageArea);
mTabWidget->addTab(scrollArea, fileName);
mTabWidget->setCurrentIndex(mTabWidget->count()-1);
connect(imageArea, SIGNAL(sendFirstColorView()), mToolbar, SLOT(setFirstColorView()));
connect(imageArea, SIGNAL(sendSecondColorView()), mToolbar, SLOT(setSecondColorView()));
connect(imageArea, SIGNAL(sendNewImageSize(QSize)), this, SLOT(setNewSizeToSizeLabel(QSize)));
connect(imageArea, SIGNAL(sendCursorPos(QPoint)), this, SLOT(setNewPosToPosLabel(QPoint)));
}
else
{
delete imageArea;
}
}
void MainWindow::initializeMainMenu()
{
QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
QAction *newAction = new QAction(tr("&New"), this);
newAction->setShortcut(QKeySequence::New);
newAction->setIcon(QIcon::fromTheme("document-new"/*, QIcon("")*/));
// newAction->setStatusTip();
connect(newAction, SIGNAL(triggered()), this, SLOT(newAct()));
fileMenu->addAction(newAction);
QAction *openAction = new QAction(tr("&Open"), this);
openAction->setShortcut(QKeySequence::Open);
openAction->setIcon(QIcon::fromTheme("document-open"/*, QIcon("")*/));
// newAction->setStatusTip();
connect(openAction, SIGNAL(triggered()), this, SLOT(openAct()));
fileMenu->addAction(openAction);
QAction *saveAction = new QAction(tr("&Save"), this);
saveAction->setShortcut(QKeySequence::Save);
saveAction->setIcon(QIcon::fromTheme("document-save"/*, QIcon("")*/));
// newAction->setStatusTip();
connect(saveAction, SIGNAL(triggered()), this, SLOT(saveAct()));
fileMenu->addAction(saveAction);
QAction *saveAsAction = new QAction(tr("Save as..."), this);
saveAsAction->setShortcut(QKeySequence::SaveAs);
saveAsAction->setIcon(QIcon::fromTheme("document-save-as"/*, QIcon("")*/));
// newAction->setStatusTip();
connect(saveAsAction, SIGNAL(triggered()), this, SLOT(saveAsAct()));
fileMenu->addAction(saveAsAction);
QAction *closeAction = new QAction(tr("&Close"), this);
closeAction->setShortcut(QKeySequence::Close);
closeAction->setIcon(QIcon::fromTheme("window-close"/*, QIcon("")*/));
// newAction->setStatusTip();
// connect();
fileMenu->addAction(closeAction);
fileMenu->addSeparator();
QAction *printAction = new QAction(tr("&Print"), this);
printAction->setShortcut(QKeySequence::Print);
printAction->setIcon(QIcon::fromTheme("document-print"/*, QIcon("")*/));
// newAction->setStatusTip();
connect(printAction, SIGNAL(triggered()), this, SLOT(printAct()));
fileMenu->addAction(printAction);
fileMenu->addSeparator();
QAction *exitAction = new QAction(tr("&Exit"), this);
exitAction->setShortcut(QKeySequence::Quit);
exitAction->setIcon(QIcon::fromTheme("application-exit"/*, QIcon("")*/));
// newAction->setStatusTip();
// connect();
fileMenu->addAction(exitAction);
QMenu *editMenu = menuBar()->addMenu(tr("&Edit"));
QAction *undoAction = new QAction(tr("&Undo"), this);
undoAction->setShortcut(QKeySequence::Undo);
undoAction->setIcon(QIcon::fromTheme("edit-undo"/*, QIcon("")*/));
// newAction->setStatusTip();
// connect();
editMenu->addAction(undoAction);
QAction *redoAction = new QAction(tr("&Redo"), this);
redoAction->setShortcut(QKeySequence::Redo);
redoAction->setIcon(QIcon::fromTheme("edit-redo"/*, QIcon("")*/));
// newAction->setStatusTip();
// connect();
editMenu->addAction(redoAction);
editMenu->addSeparator();
QAction *copyAction = new QAction(tr("&Copy"), this);
copyAction->setShortcut(QKeySequence::Copy);
copyAction->setIcon(QIcon::fromTheme("edit-copy"/*, QIcon("")*/));
// newAction->setStatusTip();
// connect();
editMenu->addAction(copyAction);
QAction *pasteAction = new QAction(tr("&Paste"), this);
pasteAction->setShortcut(QKeySequence::Paste);
pasteAction->setIcon(QIcon::fromTheme("edit-paste"/*, QIcon("")*/));
// newAction->setStatusTip();
// connect();
editMenu->addAction(pasteAction);
QAction *cutAction = new QAction(tr("C&ut"), this);
cutAction->setShortcut(QKeySequence::Cut);
cutAction->setIcon(QIcon::fromTheme("edit-cut"/*, QIcon("")*/));
// newAction->setStatusTip();
// connect();
editMenu->addAction(cutAction);
editMenu->addSeparator();
QAction *settingsAction = new QAction(tr("&Settings"), this);
settingsAction->setShortcut(QKeySequence::Preferences);
settingsAction->setIcon(QIcon::fromTheme("document-properties"/*, QIcon("")*/));
// newAction->setStatusTip();
// connect();
editMenu->addAction(settingsAction);
QMenu *effectsMenu = menuBar()->addMenu(tr("E&ffects"));
QAction *grayEfAction = new QAction(tr("Gray"), this);
// newAction->setStatusTip();
connect(grayEfAction, SIGNAL(triggered()), this, SLOT(effectGrayAct()));
effectsMenu->addAction(grayEfAction);
QAction *negativeEfAction = new QAction(tr("Negative"), this);
// newAction->setStatusTip();
connect(negativeEfAction, SIGNAL(triggered()), this, SLOT(effectNegativeAct()));
effectsMenu->addAction(negativeEfAction);
QMenu *toolsMenu = menuBar()->addMenu(tr("&Tools"));
QAction *resizeImAction = new QAction(tr("Resize"), this);
// newAction->setStatusTip();
connect(resizeImAction, SIGNAL(triggered()), this, SLOT(resizeImageAct()));
toolsMenu->addAction(resizeImAction);
QMenu *rotateMenu = new QMenu(tr("Rotate"));
QAction *rotateLAction = new QAction(tr("Left"), this);
rotateLAction->setIcon(QIcon::fromTheme("object-rotate-left"/*, QIcon("")*/));
// newAction->setStatusTip();
connect(rotateLAction, SIGNAL(triggered()), this, SLOT(rotateLeftImageAct()));
rotateMenu->addAction(rotateLAction);
QAction *rotateRAction = new QAction(tr("Right"), this);
rotateRAction->setIcon(QIcon::fromTheme("object-rotate-right"/*, QIcon("")*/));
// newAction->setStatusTip();
connect(rotateRAction, SIGNAL(triggered()), this, SLOT(rotateRightImageAct()));
rotateMenu->addAction(rotateRAction);
toolsMenu->addMenu(rotateMenu);
QMenu *aboutMenu = menuBar()->addMenu(tr("&About"));
QAction *aboutAction = new QAction(tr("&About"), this);
aboutAction->setShortcut(QKeySequence::HelpContents);
aboutAction->setIcon(QIcon::fromTheme("help-browser"/*, QIcon("")*/));
// newAction->setStatusTip();
connect(aboutAction, SIGNAL(triggered()), this, SLOT(helpAct()));
aboutMenu->addAction(aboutAction);
QAction *aboutQtAction = new QAction(tr("About Qt"), this);
// newAction->setStatusTip();
connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
aboutMenu->addAction(aboutQtAction);
}
void MainWindow::initializeStatusBar()
{
mStatusBar = new QStatusBar();
setStatusBar(mStatusBar);
mSizeLabel = new QLabel();
mPosLabel = new QLabel();
mStatusBar->addPermanentWidget(mSizeLabel, -1);
mStatusBar->addPermanentWidget(mPosLabel, 1);
}
void MainWindow::initializeToolBar()
{
mToolbar = new ToolBar(this);
addToolBar(Qt::LeftToolBarArea, mToolbar);
}
ImageArea* MainWindow::getCurrentImageArea()
{
QScrollArea *tempScrollArea = qobject_cast<QScrollArea*>(mTabWidget->currentWidget());
ImageArea *tempArea = qobject_cast<ImageArea*>(tempScrollArea->widget());
return tempArea;
}
void MainWindow::activateTab(const int &index)
{
mTabWidget->setCurrentIndex(index);
QSize size = getCurrentImageArea()->getImage()->size();
mSizeLabel->setText(QString("%1 x %2").arg(size.width()).arg(size.height()));
}
void MainWindow::setNewSizeToSizeLabel(const QSize &size)
{
mSizeLabel->setText(QString("%1 x %2").arg(size.width()).arg(size.height()));
}
void MainWindow::setNewPosToPosLabel(const QPoint &pos)
{
mPosLabel->setText(QString("%1,%2").arg(pos.x()).arg(pos.y()));
}
void MainWindow::newAct()
{
initializeNewTab();
}
void MainWindow::openAct()
{
initializeNewTab(true);
}
void MainWindow::saveAct()
{
getCurrentImageArea()->save();
mTabWidget->setTabText(mTabWidget->currentIndex(), getCurrentImageArea()->getFileName());
}
void MainWindow::saveAsAct()
{
getCurrentImageArea()->saveAs();
mTabWidget->setTabText(mTabWidget->currentIndex(), getCurrentImageArea()->getFileName());
}
void MainWindow::printAct()
{
getCurrentImageArea()->print();
}
void MainWindow::effectGrayAct()
{
getCurrentImageArea()->effectGray();
}
void MainWindow::effectNegativeAct()
{
getCurrentImageArea()->effectNegative();
}
void MainWindow::resizeImageAct()
{
getCurrentImageArea()->resizeImage();
}
void MainWindow::rotateLeftImageAct()
{
getCurrentImageArea()->rotateImage(true);
}
void MainWindow::rotateRightImageAct()
{
getCurrentImageArea()->rotateImage(false);
}
void MainWindow::helpAct()
{
QMessageBox::about(this, tr("About EasyPaint"),
QString("EasyPaint version: %1 <br> <br> Site: "
"<a href=\"https://github.com/Gr1N/EasyPaint/\">https://github.com/Gr1N/EasyPaint/</a>"
"<br> <br>Copyright (c) 2012 Nikita Grishko"
"<br> <br>Authors:<ul>"
"<li>Nikita Grishko (Gr1N)</li>"
"</ul>")
.arg(tr("0.0.1")));
}
<|endoftext|> |
<commit_before>#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include "commctrl.h"
#pragma comment(lib, "comctl32.lib")
#include <windowsx.h>
#include <dbghelp.h>
#include <assert.h>
#pragma comment(lib, "dbghelp.lib")
#pragma comment(lib, "kernel32.lib")
#pragma warning(disable: 4996)
extern "C"
{
NTSYSAPI USHORT NTAPI RtlCaptureStackBackTrace(DWORD FramesToSkip, DWORD FramesToCapture, PVOID *BackTrace, _Out_opt_ PDWORD BackTraceHash);
};
#include <vector>
#include <algorithm>
#include "hash_map.h"
#include "function_info.h"
#include "source_info.h"
#include "symbol_info.h"
#include "stack_element.h"
#include "memory_stats.h"
#include "stack_info.h"
#include "memory_block.h"
namespace muitv
{
namespace detail
{
char* formatted_string(const char* src, ...)
{
static char temp[512];
va_list args;
va_start(args, src);
vsnprintf(temp, 512, src, args);
temp[511] = '\0';
return temp;
}
LRESULT CALLBACK window_proc(HWND hWnd, DWORD message, WPARAM wParam, LPARAM lParam);
}
struct memory_dashboard
{
memory_dashboard()
{
InitializeCriticalSectionAndSpinCount(&cs, 1024);
heap = HeapCreate(0, 8 * 1024 * 1024, 0);
root = stackElementPool.allocate();
root->pos = stackElements.size();
stackElements.push_back(root);
HINSTANCE instance = GetModuleHandle(0);
WNDCLASSEX wcex;
memset(&wcex, 0, sizeof(WNDCLASSEX));
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.lpfnWndProc = (WNDPROC)detail::window_proc;
wcex.hInstance = instance;
wcex.hCursor = LoadCursor(0, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW);
wcex.lpszClassName = "MUITV_DASHBOARD";
RegisterClassEx(&wcex);
RECT windowRect = { 0, 0, 500, 500 };
AdjustWindowRect(&windowRect, WS_OVERLAPPEDWINDOW, false);
unsigned width = windowRect.right - windowRect.left;
unsigned height = windowRect.bottom - windowRect.top;
window = CreateWindow("MUITV_DASHBOARD", "muitv - Dashboard", WS_OVERLAPPEDWINDOW | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, width, height, 0, 0, instance, this);
SetWindowLongPtr(window, GWLP_USERDATA, (uintptr_t)this);
INITCOMMONCONTROLSEX commControlTypes;
commControlTypes.dwSize = sizeof(INITCOMMONCONTROLSEX);
commControlTypes.dwICC = ICC_TREEVIEW_CLASSES;
InitCommonControlsEx(&commControlTypes);
tree = CreateWindow(WC_TREEVIEW, "", WS_CHILD | WS_BORDER | WS_VISIBLE | TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT | TVS_EDITLABELS, 5, 55, width - 10, height - 60, window, 0, instance, 0);
TreeView_SetExtendedStyle(tree, TVS_EX_DOUBLEBUFFER, TVS_EX_DOUBLEBUFFER);
TVINSERTSTRUCT helpInsert;
helpInsert.hParent = 0;
helpInsert.hInsertAfter = TVI_ROOT;
helpInsert.item.mask = TVIF_TEXT | TVIF_CHILDREN | TVIF_PARAM;
helpInsert.item.pszText = "Root";
helpInsert.item.cChildren = I_CHILDRENCALLBACK;
helpInsert.item.lParam = root->pos;
TreeView_InsertItem(tree, &helpInsert);
SetTimer(window, 10001, 200, 0);
}
~memory_dashboard()
{
HeapDestroy(heap);
DeleteCriticalSection(&cs);
}
static memory_dashboard& instance()
{
static memory_dashboard inst;
return inst;
}
void* malloc(size_t size)
{
EnterCriticalSection(&cs);
const size_t maxStackTraceDepth = 64;
void* stackBuf[maxStackTraceDepth];
size_t stackSize = RtlCaptureStackBackTrace(0, maxStackTraceDepth, stackBuf, 0);
char* ptr = (char*)HeapAlloc(heap, HEAP_ZERO_MEMORY, size + (sizeof(void*) * stackSize) + sizeof(memory_block));
if(!ptr)
return 0;
memory_block* block = (memory_block*)(ptr + (sizeof(void*) * stackSize));
block->blockNum = stats.lastBlockNum++;
block->blockSize = size;
block->blockStart = ptr + sizeof(memory_block) + (sizeof(void*) * stackSize);
block->blockInfoStart = ptr;
block->stackInfo.stackSize = stackSize;
block->stackInfo.stackInfo = (void**)(ptr);
memcpy(block->stackInfo.stackInfo, stackBuf, sizeof(void*) * stackSize);
stats.bytesCount += size;
stats.blocksCount++;
stats.memopsCount++;
stats.allocCount++;
if(block->stackInfo.stackSize > skipBegin + skipEnd)
insert_block_to_tree(root, block->stackInfo.stackInfo + skipBegin, block->stackInfo.stackSize - (skipBegin + skipEnd), block->blockSize, true);
LeaveCriticalSection(&cs);
ptr += sizeof(memory_block) + (sizeof(void*) * stackSize);
return ptr;
}
void free(void *ptr)
{
if(!ptr)
return;
EnterCriticalSection(&cs);
char* cPtr = (char*)(ptr);
cPtr -= sizeof(memory_block);
memory_block* block = (memory_block*)cPtr;
int size = block->blockSize;
stats.bytesCount -= size;
stats.blocksCount--;
stats.memopsCount++;
stats.freeCount++;
if(block->stackInfo.stackSize > skipBegin + skipEnd)
insert_block_to_tree(root, block->stackInfo.stackInfo + skipBegin, block->stackInfo.stackSize - (skipBegin + skipEnd), block->blockSize, false);
HeapFree(heap, 0, block->blockInfoStart);
LeaveCriticalSection(&cs);
}
void insert_block_to_tree(stack_element *node, void** addresses, unsigned count, unsigned size, bool isAllocation)
{
if(isAllocation)
{
node->objectCount++;
node->objectSize += size;
node->allocCount++;
node->allocSize += size;
}
else
{
node->objectCount--;
node->objectSize -= size;
node->freeCount++;
}
if(count)
{
function_info *fInfo = symbol_info::instance().get_function_info(addresses[count - 1]);
bool found = false;
for(unsigned i = 0; i < node->children.size(); i++)
{
if(node->children[i]->fInfo == fInfo)
{
insert_block_to_tree(node->children[i], addresses, count - 1, size, isAllocation);
found = true;
break;
}
}
if(!found)
{
stack_element *element = stackElementPool.allocate();
element->pos = stackElements.size();
stackElements.push_back(element);
element->fInfo = fInfo;
insert_block_to_tree(element, addresses, count - 1, size, isAllocation);
node->children.push_back(element);
}
}
}
void update_tree_display(HTREEITEM parent)
{
if(!parent)
return;
TVITEM item;
item.mask = TVIF_TEXT | TVIF_PARAM;
item.cchTextMax = 0;
item.hItem = parent;
TreeView_GetItem(tree, &item);
if(stackElements.empty())
return;
stack_element *node = stackElements[item.lParam];
item.mask = TVIF_TEXT;
item.pszText = detail::formatted_string("%s (x%d for %dkb)", node->get_name(), node->objectCount, node->objectSize / 1024);
TreeView_SetItem(tree, &item);
HTREEITEM child = TreeView_GetChild(tree, parent);
while(child)
{
update_tree_display(child);
child = TreeView_GetNextSibling(tree, child);
}
}
LRESULT window_message_handle(HWND hWnd, DWORD message, WPARAM wParam, LPARAM lParam)
{
switch(message)
{
case WM_NOTIFY:
if(((LPNMHDR)lParam)->code == TVN_GETDISPINFO && ((LPNMHDR)lParam)->hwndFrom == tree)
{
LPNMTVDISPINFO info = (LPNMTVDISPINFO)lParam;
EnterCriticalSection(&cs);
if(info->item.mask & TVIF_CHILDREN)
{
if(size_t(info->item.lParam) < stackElements.size())
info->item.cChildren = stackElements[info->item.lParam]->children.size();
else
info->item.cChildren = 0;
}
LeaveCriticalSection(&cs);
}
else if(((LPNMHDR)lParam)->code == TVN_ITEMEXPANDING && ((LPNMHDR)lParam)->hwndFrom == tree)
{
LPNMTREEVIEW info = (LPNMTREEVIEW)lParam;
while(HTREEITEM child = TreeView_GetChild(tree, info->itemNew.hItem))
TreeView_DeleteItem(tree, child);
EnterCriticalSection(&cs);
if(size_t(info->itemNew.lParam) < stackElements.size())
{
stack_element *parent = stackElements[info->itemNew.lParam];
parent->sort_children(compare_object_size);
for(unsigned i = 0; i < parent->children.size(); i++)
{
stack_element *elem = parent->children[i];
TVINSERTSTRUCT helpInsert;
helpInsert.hParent = info->itemNew.hItem;
helpInsert.hInsertAfter = TVI_LAST;
helpInsert.item.cchTextMax = 0;
helpInsert.item.mask = TVIF_TEXT | TVIF_CHILDREN | TVIF_PARAM;
helpInsert.item.pszText = detail::formatted_string("%s (x%d for %dkb)", elem->get_name(), elem->objectCount, elem->objectSize / 1024);
helpInsert.item.cChildren = I_CHILDRENCALLBACK;
helpInsert.item.lParam = elem->pos;
TreeView_InsertItem(tree, &helpInsert);
}
}
LeaveCriticalSection(&cs);
}
break;
case WM_TIMER:
if(wParam == 10001)
{
EnterCriticalSection(&cs);
TVITEM item;
item.mask = TVIF_TEXT;
item.cchTextMax = 0;
item.pszText = detail::formatted_string("Root (x%d for %dkb)", stats.blocksCount, stats.bytesCount / 1024);
item.hItem = TreeView_GetRoot(tree);
TreeView_SetItem(tree, &item);
update_tree_display(TreeView_GetChild(tree, item.hItem));
LeaveCriticalSection(&cs);
return 0;
}
break;
case WM_SIZE:
{
unsigned width = LOWORD(lParam);
unsigned height = HIWORD(lParam);
SetWindowPos(tree, HWND_TOP, 5, 55, width - 10, height - 60, 0);
}
break;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
static const size_t skipBegin = 2;
static const size_t skipEnd = 4;
CRITICAL_SECTION cs;
HANDLE heap;
memory_stats stats;
stack_element *root;
block_pool<stack_element, 1024> stackElementPool;
std::vector<stack_element*> stackElements;
// Display
HWND window;
HWND tree;
};
LRESULT CALLBACK detail::window_proc(HWND hWnd, DWORD message, WPARAM wParam, LPARAM lParam)
{
memory_dashboard *memoryMan = (memory_dashboard*)GetWindowLongPtr(hWnd, GWLP_USERDATA);
if(memoryMan)
return memoryMan->window_message_handle(hWnd, message, wParam, lParam);
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
extern "C" __declspec(dllexport) void* muitv_alloc(size_t size)
{
return muitv::memory_dashboard::instance().malloc(size);
}
extern "C" __declspec(dllexport) void muitv_free(void* ptr)
{
muitv::memory_dashboard::instance().free(ptr);
}
<commit_msg>Added total memory statistics<commit_after>#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include "commctrl.h"
#pragma comment(lib, "comctl32.lib")
#include <windowsx.h>
#include <dbghelp.h>
#include <assert.h>
#pragma comment(lib, "dbghelp.lib")
#pragma comment(lib, "kernel32.lib")
#pragma warning(disable: 4996)
extern "C"
{
NTSYSAPI USHORT NTAPI RtlCaptureStackBackTrace(DWORD FramesToSkip, DWORD FramesToCapture, PVOID *BackTrace, _Out_opt_ PDWORD BackTraceHash);
};
#include <vector>
#include <algorithm>
#include "hash_map.h"
#include "function_info.h"
#include "source_info.h"
#include "symbol_info.h"
#include "stack_element.h"
#include "memory_stats.h"
#include "stack_info.h"
#include "memory_block.h"
namespace muitv
{
namespace detail
{
char* formatted_string(const char* src, ...)
{
static char temp[512];
va_list args;
va_start(args, src);
vsnprintf(temp, 512, src, args);
temp[511] = '\0';
return temp;
}
LRESULT CALLBACK window_proc(HWND hWnd, DWORD message, WPARAM wParam, LPARAM lParam);
}
struct memory_dashboard
{
memory_dashboard()
{
InitializeCriticalSectionAndSpinCount(&cs, 1024);
heap = HeapCreate(0, 8 * 1024 * 1024, 0);
root = stackElementPool.allocate();
root->pos = stackElements.size();
stackElements.push_back(root);
HINSTANCE instance = GetModuleHandle(0);
WNDCLASSEX wcex;
memset(&wcex, 0, sizeof(WNDCLASSEX));
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.lpfnWndProc = (WNDPROC)detail::window_proc;
wcex.hInstance = instance;
wcex.hCursor = LoadCursor(0, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW);
wcex.lpszClassName = "MUITV_DASHBOARD";
RegisterClassEx(&wcex);
RECT windowRect = { 0, 0, 500, 500 };
AdjustWindowRect(&windowRect, WS_OVERLAPPEDWINDOW, false);
unsigned width = windowRect.right - windowRect.left;
unsigned height = windowRect.bottom - windowRect.top;
window = CreateWindow("MUITV_DASHBOARD", "muitv - Dashboard", WS_OVERLAPPEDWINDOW | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, width, height, 0, 0, instance, this);
SetWindowLongPtr(window, GWLP_USERDATA, (uintptr_t)this);
INITCOMMONCONTROLSEX commControlTypes;
commControlTypes.dwSize = sizeof(INITCOMMONCONTROLSEX);
commControlTypes.dwICC = ICC_TREEVIEW_CLASSES;
InitCommonControlsEx(&commControlTypes);
tree = CreateWindow(WC_TREEVIEW, "", WS_CHILD | WS_BORDER | WS_VISIBLE | TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT | TVS_EDITLABELS, 5, 55, width - 10, height - 60, window, 0, instance, 0);
TreeView_SetExtendedStyle(tree, TVS_EX_DOUBLEBUFFER, TVS_EX_DOUBLEBUFFER);
TVINSERTSTRUCT helpInsert;
helpInsert.hParent = 0;
helpInsert.hInsertAfter = TVI_ROOT;
helpInsert.item.mask = TVIF_TEXT | TVIF_CHILDREN | TVIF_PARAM;
helpInsert.item.pszText = "Root";
helpInsert.item.cChildren = I_CHILDRENCALLBACK;
helpInsert.item.lParam = root->pos;
TreeView_InsertItem(tree, &helpInsert);
labelAllocCount = CreateWindow("STATIC", "", WS_VISIBLE | WS_CHILD, 5 + (width - 10) / 3 * 0, 5, (width - 10) / 3 - 5, 20, window, 0, instance, 0);
labelFreeCount = CreateWindow("STATIC", "", WS_VISIBLE | WS_CHILD, 5 + (width - 10) / 3 * 1, 5, (width - 10) / 3 - 5, 20, window, 0, instance, 0);
labelOperationCount = CreateWindow("STATIC", "", WS_VISIBLE | WS_CHILD, 5 + (width - 10) / 3 * 2, 5, (width - 10) / 3 - 5, 20, window, 0, instance, 0);
labelBlockCount = CreateWindow("STATIC", "", WS_VISIBLE | WS_CHILD, 5 + (width - 10) / 3 * 0, 30, (width - 10) / 3 - 5, 20, window, 0, instance, 0);
labelByteCount = CreateWindow("STATIC", "", WS_VISIBLE | WS_CHILD, 5 + (width - 10) / 3 * 1, 30, (width - 10) / 3 - 5, 20, window, 0, instance, 0);
SetTimer(window, 10001, 200, 0);
UpdateWindow(window);
}
~memory_dashboard()
{
HeapDestroy(heap);
DeleteCriticalSection(&cs);
}
static memory_dashboard& instance()
{
static memory_dashboard inst;
return inst;
}
void* malloc(size_t size)
{
EnterCriticalSection(&cs);
const size_t maxStackTraceDepth = 64;
void* stackBuf[maxStackTraceDepth];
size_t stackSize = RtlCaptureStackBackTrace(0, maxStackTraceDepth, stackBuf, 0);
char* ptr = (char*)HeapAlloc(heap, HEAP_ZERO_MEMORY, size + (sizeof(void*) * stackSize) + sizeof(memory_block));
if(!ptr)
return 0;
memory_block* block = (memory_block*)(ptr + (sizeof(void*) * stackSize));
block->blockNum = stats.lastBlockNum++;
block->blockSize = size;
block->blockStart = ptr + sizeof(memory_block) + (sizeof(void*) * stackSize);
block->blockInfoStart = ptr;
block->stackInfo.stackSize = stackSize;
block->stackInfo.stackInfo = (void**)(ptr);
memcpy(block->stackInfo.stackInfo, stackBuf, sizeof(void*) * stackSize);
stats.bytesCount += size;
stats.blocksCount++;
stats.memopsCount++;
stats.allocCount++;
if(block->stackInfo.stackSize > skipBegin + skipEnd)
insert_block_to_tree(root, block->stackInfo.stackInfo + skipBegin, block->stackInfo.stackSize - (skipBegin + skipEnd), block->blockSize, true);
LeaveCriticalSection(&cs);
ptr += sizeof(memory_block) + (sizeof(void*) * stackSize);
return ptr;
}
void free(void *ptr)
{
if(!ptr)
return;
EnterCriticalSection(&cs);
char* cPtr = (char*)(ptr);
cPtr -= sizeof(memory_block);
memory_block* block = (memory_block*)cPtr;
int size = block->blockSize;
stats.bytesCount -= size;
stats.blocksCount--;
stats.memopsCount++;
stats.freeCount++;
if(block->stackInfo.stackSize > skipBegin + skipEnd)
insert_block_to_tree(root, block->stackInfo.stackInfo + skipBegin, block->stackInfo.stackSize - (skipBegin + skipEnd), block->blockSize, false);
HeapFree(heap, 0, block->blockInfoStart);
LeaveCriticalSection(&cs);
}
void insert_block_to_tree(stack_element *node, void** addresses, unsigned count, unsigned size, bool isAllocation)
{
if(isAllocation)
{
node->objectCount++;
node->objectSize += size;
node->allocCount++;
node->allocSize += size;
}
else
{
node->objectCount--;
node->objectSize -= size;
node->freeCount++;
}
if(count)
{
function_info *fInfo = symbol_info::instance().get_function_info(addresses[count - 1]);
bool found = false;
for(unsigned i = 0; i < node->children.size(); i++)
{
if(node->children[i]->fInfo == fInfo)
{
insert_block_to_tree(node->children[i], addresses, count - 1, size, isAllocation);
found = true;
break;
}
}
if(!found)
{
stack_element *element = stackElementPool.allocate();
element->pos = stackElements.size();
stackElements.push_back(element);
element->fInfo = fInfo;
insert_block_to_tree(element, addresses, count - 1, size, isAllocation);
node->children.push_back(element);
}
}
}
void update_tree_display(HTREEITEM parent)
{
if(!parent)
return;
TVITEM item;
item.mask = TVIF_TEXT | TVIF_PARAM;
item.cchTextMax = 0;
item.hItem = parent;
TreeView_GetItem(tree, &item);
if(stackElements.empty())
return;
stack_element *node = stackElements[item.lParam];
item.mask = TVIF_TEXT;
item.pszText = detail::formatted_string("%s (x%d for %dkb)", node->get_name(), node->objectCount, node->objectSize / 1024);
TreeView_SetItem(tree, &item);
HTREEITEM child = TreeView_GetChild(tree, parent);
while(child)
{
update_tree_display(child);
child = TreeView_GetNextSibling(tree, child);
}
}
LRESULT window_message_handle(HWND hWnd, DWORD message, WPARAM wParam, LPARAM lParam)
{
switch(message)
{
case WM_NOTIFY:
if(((LPNMHDR)lParam)->code == TVN_GETDISPINFO && ((LPNMHDR)lParam)->hwndFrom == tree)
{
LPNMTVDISPINFO info = (LPNMTVDISPINFO)lParam;
EnterCriticalSection(&cs);
if(info->item.mask & TVIF_CHILDREN)
{
if(size_t(info->item.lParam) < stackElements.size())
info->item.cChildren = stackElements[info->item.lParam]->children.size();
else
info->item.cChildren = 0;
}
LeaveCriticalSection(&cs);
}
else if(((LPNMHDR)lParam)->code == TVN_ITEMEXPANDING && ((LPNMHDR)lParam)->hwndFrom == tree)
{
LPNMTREEVIEW info = (LPNMTREEVIEW)lParam;
while(HTREEITEM child = TreeView_GetChild(tree, info->itemNew.hItem))
TreeView_DeleteItem(tree, child);
EnterCriticalSection(&cs);
if(size_t(info->itemNew.lParam) < stackElements.size())
{
stack_element *parent = stackElements[info->itemNew.lParam];
parent->sort_children(compare_object_size);
for(unsigned i = 0; i < parent->children.size(); i++)
{
stack_element *elem = parent->children[i];
TVINSERTSTRUCT helpInsert;
helpInsert.hParent = info->itemNew.hItem;
helpInsert.hInsertAfter = TVI_LAST;
helpInsert.item.cchTextMax = 0;
helpInsert.item.mask = TVIF_TEXT | TVIF_CHILDREN | TVIF_PARAM;
helpInsert.item.pszText = detail::formatted_string("%s (x%d for %dkb)", elem->get_name(), elem->objectCount, elem->objectSize / 1024);
helpInsert.item.cChildren = I_CHILDRENCALLBACK;
helpInsert.item.lParam = elem->pos;
TreeView_InsertItem(tree, &helpInsert);
}
}
LeaveCriticalSection(&cs);
}
break;
case WM_TIMER:
if(wParam == 10001)
{
EnterCriticalSection(&cs);
Static_SetText(labelAllocCount, detail::formatted_string("Alloc: %d", stats.allocCount));
Static_SetText(labelFreeCount, detail::formatted_string("Free: %d", stats.freeCount));
Static_SetText(labelOperationCount, detail::formatted_string("Total: %d", stats.memopsCount));
Static_SetText(labelBlockCount, detail::formatted_string("Blocks: %d", stats.blocksCount));
Static_SetText(labelByteCount, detail::formatted_string("Size: %.3fmb", stats.bytesCount / 1024.0 / 1024.0));
TVITEM item;
item.mask = TVIF_TEXT;
item.cchTextMax = 0;
item.pszText = detail::formatted_string("Root (x%d for %dkb)", stats.blocksCount, stats.bytesCount / 1024);
item.hItem = TreeView_GetRoot(tree);
TreeView_SetItem(tree, &item);
update_tree_display(TreeView_GetChild(tree, item.hItem));
LeaveCriticalSection(&cs);
return 0;
}
break;
case WM_SIZE:
{
unsigned width = LOWORD(lParam);
unsigned height = HIWORD(lParam);
SetWindowPos(labelAllocCount, HWND_TOP, 5 + (width - 10) / 3 * 0, 5, (width - 10) / 3 - 5, 20, 0);
SetWindowPos(labelFreeCount, HWND_TOP, 5 + (width - 10) / 3 * 1, 5, (width - 10) / 3 - 5, 20, 0);
SetWindowPos(labelOperationCount, HWND_TOP, 5 + (width - 10) / 3 * 2, 5, (width - 10) / 3 - 5, 20, 0);
SetWindowPos(labelBlockCount, HWND_TOP, 5 + (width - 10) / 3 * 0, 30, (width - 10) / 3 - 5, 20, 0);
SetWindowPos(labelByteCount, HWND_TOP, 5 + (width - 10) / 3 * 1, 30, (width - 10) / 3 - 5, 20, 0);
SetWindowPos(tree, HWND_TOP, 5, 55, width - 10, height - 60, 0);
}
break;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
static const size_t skipBegin = 2;
static const size_t skipEnd = 4;
CRITICAL_SECTION cs;
HANDLE heap;
memory_stats stats;
stack_element *root;
block_pool<stack_element, 1024> stackElementPool;
std::vector<stack_element*> stackElements;
// Display
HWND window;
HWND labelAllocCount;
HWND labelFreeCount;
HWND labelOperationCount;
HWND labelBlockCount;
HWND labelByteCount;
HWND tree;
};
LRESULT CALLBACK detail::window_proc(HWND hWnd, DWORD message, WPARAM wParam, LPARAM lParam)
{
memory_dashboard *memoryMan = (memory_dashboard*)GetWindowLongPtr(hWnd, GWLP_USERDATA);
if(memoryMan)
return memoryMan->window_message_handle(hWnd, message, wParam, lParam);
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
extern "C" __declspec(dllexport) void* muitv_alloc(size_t size)
{
return muitv::memory_dashboard::instance().malloc(size);
}
extern "C" __declspec(dllexport) void muitv_free(void* ptr)
{
muitv::memory_dashboard::instance().free(ptr);
}
<|endoftext|> |
<commit_before>// (C) 2014 Arek Olek
#pragma once
#include <boost/algorithm/string/join.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <algorithm>
#include <vector>
#include <utility>
#include <random>
template <typename ... Args>
auto range(Args&& ... args) -> decltype(boost::make_iterator_range(std::forward<Args>(args)...)) {
return boost::make_iterator_range(std::forward<Args>(args)...);
}
template <typename ... Args>
auto filter(Args&& ... args) {
return boost::make_filter_iterator(std::forward<Args>(args)...);
}
template <class Iterator, class Generator = std::default_random_engine>
auto shuffled(std::pair<Iterator, Iterator> p, Generator generator = Generator()) -> std::vector<decltype(*p.first)> {
std::vector<decltype(*p.first)> R(p.first, p.second);
std::shuffle(R.begin(), R.end(), generator);
return R;
}
template <class IntType = int, class Generator = std::default_random_engine>
IntType random(IntType a = 0, IntType b = std::numeric_limits<IntType>::max()) {
static Generator generator;
return std::uniform_int_distribution<IntType>{a, b}(generator);
}
template<class Container>
std::string join(Container const & container, std::string const & delimeter) {
using boost::algorithm::join;
using boost::adaptors::transformed;
using value_type = typename Container::value_type;
auto tostr = static_cast<std::string(*)(value_type)>(std::to_string);
return join(container | transformed(tostr), delimeter);
};
template<class Container>
int sum(Container const & container) {
return std::accumulate(container.begin(), container.end(), 0);
};
<commit_msg>add include to range.hpp<commit_after>// (C) 2014 Arek Olek
#pragma once
#include <boost/algorithm/string/join.hpp>
#include <boost/iterator/filter_iterator.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <algorithm>
#include <vector>
#include <utility>
#include <random>
template <typename ... Args>
auto range(Args&& ... args) -> decltype(boost::make_iterator_range(std::forward<Args>(args)...)) {
return boost::make_iterator_range(std::forward<Args>(args)...);
}
template <typename ... Args>
auto filter(Args&& ... args) {
return boost::make_filter_iterator(std::forward<Args>(args)...);
}
template <class Iterator, class Generator = std::default_random_engine>
auto shuffled(std::pair<Iterator, Iterator> p, Generator generator = Generator()) -> std::vector<decltype(*p.first)> {
std::vector<decltype(*p.first)> R(p.first, p.second);
std::shuffle(R.begin(), R.end(), generator);
return R;
}
template <class IntType = int, class Generator = std::default_random_engine>
IntType random(IntType a = 0, IntType b = std::numeric_limits<IntType>::max()) {
static Generator generator;
return std::uniform_int_distribution<IntType>{a, b}(generator);
}
template<class Container>
std::string join(Container const & container, std::string const & delimeter) {
using boost::algorithm::join;
using boost::adaptors::transformed;
using value_type = typename Container::value_type;
auto tostr = static_cast<std::string(*)(value_type)>(std::to_string);
return join(container | transformed(tostr), delimeter);
};
template<class Container>
int sum(Container const & container) {
return std::accumulate(container.begin(), container.end(), 0);
};
<|endoftext|> |
<commit_before>#include "include/rados/librados.h"
#include "test/rados-api/test.h"
#include "gtest/gtest.h"
#include <errno.h>
#include <vector>
#define POOL_LIST_BUF_SZ 32768
TEST(LibRadosPools, PoolList) {
std::vector<char> pool_list_buf(POOL_LIST_BUF_SZ, '\0');
char *buf = &pool_list_buf[0];
rados_t cluster;
std::string pool_name = get_temp_pool_name();
ASSERT_EQ("", create_one_pool(pool_name, &cluster));
ASSERT_LT(rados_pool_list(cluster, buf, POOL_LIST_BUF_SZ), POOL_LIST_BUF_SZ);
bool found_pool = false;
while (buf[0] != '\0') {
if ((found_pool == false) && (strcmp(buf, pool_name.c_str()) == 0)) {
found_pool = true;
}
buf += strlen(buf) + 1;
}
ASSERT_EQ(found_pool, true);
ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}
int rados_pool_lookup(rados_t cluster, const char *pool_name);
TEST(LibRadosPools, PoolLookup) {
rados_t cluster;
std::string pool_name = get_temp_pool_name();
ASSERT_EQ("", create_one_pool(pool_name, &cluster));
ASSERT_LT(0, rados_pool_lookup(cluster, pool_name.c_str()));
ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}
TEST(LibRadosPools, PoolLookup2) {
rados_t cluster;
std::string pool_name = get_temp_pool_name();
ASSERT_EQ("", create_one_pool(pool_name, &cluster));
int pool_id = rados_pool_lookup(cluster, pool_name.c_str());
ASSERT_GT(pool_id, 0);
rados_ioctx_t ioctx;
ASSERT_EQ(0, rados_ioctx_create(cluster, pool_name.c_str(), &ioctx));
int pool_id2 = rados_ioctx_get_id(ioctx);
ASSERT_EQ(pool_id, pool_id2);
rados_ioctx_destroy(ioctx);
ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}
TEST(LibRadosPools, PoolDelete) {
rados_t cluster;
std::string pool_name = get_temp_pool_name();
ASSERT_EQ("", create_one_pool(pool_name, &cluster));
ASSERT_EQ(0, rados_pool_delete(cluster, pool_name.c_str()));
ASSERT_GT(0, rados_pool_lookup(cluster, pool_name.c_str()));
ASSERT_EQ(0, rados_pool_create(cluster, pool_name.c_str()));
ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}
TEST(LibRadosPools, AuidTest1) {
rados_t cluster;
std::string pool_name = get_temp_pool_name();
ASSERT_EQ("", create_one_pool(pool_name, &cluster));
rados_ioctx_t ioctx;
ASSERT_EQ(0, rados_ioctx_create(cluster, pool_name.c_str(), &ioctx));
ASSERT_EQ(0, rados_ioctx_pool_set_auid(ioctx, 123));
uint64_t auid;
ASSERT_EQ(0, rados_ioctx_pool_get_auid(ioctx, &auid));
ASSERT_EQ(123ull, auid);
rados_ioctx_destroy(ioctx);
ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}
TEST(LibRadosPools, AuidTest2) {
rados_t cluster;
std::string pool_name = get_temp_pool_name();
ASSERT_EQ("", create_one_pool(pool_name, &cluster));
ASSERT_EQ(0, rados_pool_delete(cluster, pool_name.c_str()));
ASSERT_EQ(0, rados_pool_create_with_auid(cluster, pool_name.c_str(), 456));
rados_ioctx_t ioctx;
ASSERT_EQ(0, rados_ioctx_create(cluster, pool_name.c_str(), &ioctx));
uint64_t auid;
ASSERT_EQ(0, rados_ioctx_pool_get_auid(ioctx, &auid));
ASSERT_EQ(456ull, auid);
rados_ioctx_destroy(ioctx);
ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}
<commit_msg>test/rados-api/pool.cc:test PoolCreateWithCrushRule<commit_after>#include "include/rados/librados.h"
#include "test/rados-api/test.h"
#include "gtest/gtest.h"
#include <errno.h>
#include <vector>
#define POOL_LIST_BUF_SZ 32768
TEST(LibRadosPools, PoolList) {
std::vector<char> pool_list_buf(POOL_LIST_BUF_SZ, '\0');
char *buf = &pool_list_buf[0];
rados_t cluster;
std::string pool_name = get_temp_pool_name();
ASSERT_EQ("", create_one_pool(pool_name, &cluster));
ASSERT_LT(rados_pool_list(cluster, buf, POOL_LIST_BUF_SZ), POOL_LIST_BUF_SZ);
bool found_pool = false;
while (buf[0] != '\0') {
if ((found_pool == false) && (strcmp(buf, pool_name.c_str()) == 0)) {
found_pool = true;
}
buf += strlen(buf) + 1;
}
ASSERT_EQ(found_pool, true);
ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}
int rados_pool_lookup(rados_t cluster, const char *pool_name);
TEST(LibRadosPools, PoolLookup) {
rados_t cluster;
std::string pool_name = get_temp_pool_name();
ASSERT_EQ("", create_one_pool(pool_name, &cluster));
ASSERT_LT(0, rados_pool_lookup(cluster, pool_name.c_str()));
ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}
TEST(LibRadosPools, PoolLookup2) {
rados_t cluster;
std::string pool_name = get_temp_pool_name();
ASSERT_EQ("", create_one_pool(pool_name, &cluster));
int pool_id = rados_pool_lookup(cluster, pool_name.c_str());
ASSERT_GT(pool_id, 0);
rados_ioctx_t ioctx;
ASSERT_EQ(0, rados_ioctx_create(cluster, pool_name.c_str(), &ioctx));
int pool_id2 = rados_ioctx_get_id(ioctx);
ASSERT_EQ(pool_id, pool_id2);
rados_ioctx_destroy(ioctx);
ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}
TEST(LibRadosPools, PoolDelete) {
rados_t cluster;
std::string pool_name = get_temp_pool_name();
ASSERT_EQ("", create_one_pool(pool_name, &cluster));
ASSERT_EQ(0, rados_pool_delete(cluster, pool_name.c_str()));
ASSERT_GT(0, rados_pool_lookup(cluster, pool_name.c_str()));
ASSERT_EQ(0, rados_pool_create(cluster, pool_name.c_str()));
ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}
TEST(LibRadosPools, AuidTest1) {
rados_t cluster;
std::string pool_name = get_temp_pool_name();
ASSERT_EQ("", create_one_pool(pool_name, &cluster));
rados_ioctx_t ioctx;
ASSERT_EQ(0, rados_ioctx_create(cluster, pool_name.c_str(), &ioctx));
ASSERT_EQ(0, rados_ioctx_pool_set_auid(ioctx, 123));
uint64_t auid;
ASSERT_EQ(0, rados_ioctx_pool_get_auid(ioctx, &auid));
ASSERT_EQ(123ull, auid);
rados_ioctx_destroy(ioctx);
ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}
TEST(LibRadosPools, AuidTest2) {
rados_t cluster;
std::string pool_name = get_temp_pool_name();
ASSERT_EQ("", create_one_pool(pool_name, &cluster));
ASSERT_EQ(0, rados_pool_delete(cluster, pool_name.c_str()));
ASSERT_EQ(0, rados_pool_create_with_auid(cluster, pool_name.c_str(), 456));
rados_ioctx_t ioctx;
ASSERT_EQ(0, rados_ioctx_create(cluster, pool_name.c_str(), &ioctx));
uint64_t auid;
ASSERT_EQ(0, rados_ioctx_pool_get_auid(ioctx, &auid));
ASSERT_EQ(456ull, auid);
rados_ioctx_destroy(ioctx);
ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}
TEST(LibRadosPools, PoolCreateWithCrushRule) {
rados_t cluster;
std::string pool_name = get_temp_pool_name();
ASSERT_EQ("", create_one_pool(pool_name, &cluster));
std::string pool2_name = get_temp_pool_name();
ASSERT_EQ(0, rados_pool_create_with_crush_rule(cluster,
pool2_name.c_str(), 0));
ASSERT_EQ(0, rados_pool_delete(cluster, pool2_name.c_str()));
std::string pool3_name = get_temp_pool_name();
ASSERT_EQ(0, rados_pool_create_with_all(cluster, pool3_name.c_str(),
456ull, 0));
rados_ioctx_t ioctx;
ASSERT_EQ(0, rados_ioctx_create(cluster, pool3_name.c_str(), &ioctx));
uint64_t auid;
ASSERT_EQ(0, rados_ioctx_pool_get_auid(ioctx, &auid));
ASSERT_EQ(456ull, auid);
ASSERT_EQ(0, rados_pool_delete(cluster, pool3_name.c_str()));
rados_ioctx_destroy(ioctx);
ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}
<|endoftext|> |
<commit_before>#include <c3d.h>
#include <iostream>
namespace c3d
{
//constructors plus plus
Surface::Surface()
{
position.setxyz(0.0,0.0,0.0);
axisX.setxyz(1.0,0.0,0.0);
axisY.setxyz(0.0,1.0,0.0);
axisZ.setxyz(0.0,0.0,1.0);
}
Surface::Surface(const Vector & pos, const Vector & ox, const Vector & oy)
{
position.copy(pos);
axisX.copy(ox);
axisY.copy(oy);
normalize();
}
Surface::Surface(const Surface & surface)
{
copy(surface);
}
Surface & Surface::copy(const Surface & surface)
{
position.copy(surface.position);
axisX.copy(surface.axisX);
axisY.copy(surface.axisY);
axisZ.copy(surface.axisZ);
return *this;
}
//getters / setters
Surface & Surface::setPosition(const Vector & pos)
{
position.copy(pos);
return *this;
}
Surface & Surface::setAxisX(const Vector & v)
{
axisX.copy(v);
return *this;
}
Surface & Surface::setAxisY(const Vector & v)
{
axisY.copy(v);
return *this;
}
Surface & Surface::setAxisZ(const Vector & v)
{
axisZ.copy(v);
return *this;
}
Vector & Surface::getPosition()
{
return position;
}
Vector & Surface::getAxisX()
{
return axisX;
}
Vector & Surface::getAxisY()
{
return axisY;
}
Vector & Surface::getAxisZ()
{
return axisZ;
}
Surface & Surface::copyPositionTo(Vector & v)
{
v.copy(position);
return *this;
}
Surface & Surface::copyAxisXTo(Vector & v)
{
v.copy(axisX);
return *this;
}
Surface & Surface::copyAxisYTo(Vector & v)
{
v.copy(axisY);
return *this;
}
Surface & Surface::copyAxisZTo(Vector & v)
{
v.copy(axisZ);
return *this;
}
Surface & Surface::normalize()
{
axisY.normalize(); //Y is now length one
axisZ.copy(axisX).cross(axisY).normalize(); //z perpendicular to y and y
axisX.copy(axisY).cross(axisZ).normalize(); //x perpendicular to x and y
return *this;
}
//virtual Surface Surface::clone() is virtual
//virtual double Surface::intersection(Ray) is virtual
}
<commit_msg>Minor change to comments<commit_after>#include <c3d.h>
#include <iostream>
namespace c3d
{
//constructors plus plus
Surface::Surface()
{
position.setxyz(0.0,0.0,0.0);
axisX.setxyz(1.0,0.0,0.0);
axisY.setxyz(0.0,1.0,0.0);
axisZ.setxyz(0.0,0.0,1.0);
}
Surface::Surface(const Vector & pos, const Vector & ox, const Vector & oy)
{
position.copy(pos);
axisX.copy(ox);
axisY.copy(oy);
normalize();
}
Surface::Surface(const Surface & surface)
{
copy(surface);
}
Surface & Surface::copy(const Surface & surface)
{
position.copy(surface.position);
axisX.copy(surface.axisX);
axisY.copy(surface.axisY);
axisZ.copy(surface.axisZ);
return *this;
}
//getters / setters
Surface & Surface::setPosition(const Vector & pos)
{
position.copy(pos);
return *this;
}
Surface & Surface::setAxisX(const Vector & v)
{
axisX.copy(v);
return *this;
}
Surface & Surface::setAxisY(const Vector & v)
{
axisY.copy(v);
return *this;
}
Surface & Surface::setAxisZ(const Vector & v)
{
axisZ.copy(v);
return *this;
}
Vector & Surface::getPosition()
{
return position;
}
Vector & Surface::getAxisX()
{
return axisX;
}
Vector & Surface::getAxisY()
{
return axisY;
}
Vector & Surface::getAxisZ()
{
return axisZ;
}
Surface & Surface::copyPositionTo(Vector & v)
{
v.copy(position);
return *this;
}
Surface & Surface::copyAxisXTo(Vector & v)
{
v.copy(axisX);
return *this;
}
Surface & Surface::copyAxisYTo(Vector & v)
{
v.copy(axisY);
return *this;
}
Surface & Surface::copyAxisZTo(Vector & v)
{
v.copy(axisZ);
return *this;
}
Surface & Surface::normalize()
{
axisY.normalize(); //Y is now length one
axisZ.copy(axisX).cross(axisY).normalize(); //z perpendicular to x and y
axisX.copy(axisY).cross(axisZ).normalize(); //x perpendicular to y and z
return *this;
}
//virtual Surface Surface::clone() is virtual
//virtual double Surface::intersection(Ray) is virtual
}
<|endoftext|> |
<commit_before>#include <sstream>
#include <string>
#include <string_view>
#include "../test.h"
#include "simdjson.cpp"
#include "simdjson.h"
using namespace simdjson;
static void GenStat(Stat &stat, const dom::element &v) {
switch (v.type()) {
case dom::element_type::ARRAY:
for (dom::element child : dom::array(v)) {
stat.elementCount++;
GenStat(stat, child);
}
stat.arrayCount++;
break;
case dom::element_type::OBJECT:
for (dom::key_value_pair kv : dom::object(v)) {
GenStat(stat, dom::element(kv.value));
stat.memberCount++;
stat.stringCount++;
}
stat.objectCount++;
break;
case dom::element_type::INT64:
case dom::element_type::UINT64:
case dom::element_type::DOUBLE:
stat.numberCount++;
break;
case dom::element_type::STRING: {
stat.stringCount++;
std::string_view sv = v.get<std::string_view>();
stat.stringLength += sv.size();
} break;
case dom::element_type::BOOL:
if (v.get<bool>()) {
stat.trueCount++;
} else {
stat.falseCount++;
}
break;
case dom::element_type::NULL_VALUE:
++stat.nullCount;
break;
}
}
class SimdJsonParseResult : public ParseResultBase {
public:
dom::element root{};
std::unique_ptr<dom::parser> parser = std::make_unique<dom::parser>();
};
class SimdStringResult : public StringResultBase {
public:
std::stringstream ss;
const char *c_str() const override { return ss.str().c_str(); }
};
class SimdTest : public TestBase {
public:
#if TEST_INFO
const char *GetName() const override { return "simdjson"; }
const char *GetFilename() const override { return __FILE__; }
#endif
#if TEST_PARSE
ParseResultBase *Parse(const char *j, size_t length) const override {
auto pr = std::make_unique<SimdJsonParseResult>();
std::string_view s(j, length);
simdjson::error_code error;
pr->parser->parse(s).tie(pr->root, error);
if (error) {
return nullptr;
}
return pr.release();
}
#endif
#if TEST_STRINGIFY
StringResultBase *Stringify(
const ParseResultBase *parseResult) const override {
auto sr = std::make_unique<SimdStringResult>();
auto pr = static_cast<const SimdJsonParseResult *>(parseResult);
sr->ss << pr->root;
return sr.release();
}
#endif
#if TEST_PRETTIFY
// Currently unsupported, simdjson v0.3
StringResultBase *Prettify(
const ParseResultBase *parseResult) const override {
(void)parseResult;
return nullptr;
}
#endif
#if TEST_STATISTICS
bool Statistics(const ParseResultBase *parseResult,
Stat *stat) const override {
auto pr = static_cast<const SimdJsonParseResult *>(parseResult);
memset(stat, 0, sizeof(Stat));
GenStat(*stat, pr->root);
return true;
}
#endif
#if TEST_CONFORMANCE
bool ParseDouble(const char *j, double *d) const override {
simdjson::error_code error;
simdjson::dom::parser parser;
parser.parse(j, std::strlen(j)).at(0).get<double>().tie(*d, error);
if (error) {
return false;
}
return true;
}
bool ParseString(const char *j, std::string &s) const override {
simdjson::error_code error;
std::string_view answer;
parser.parse(j,strlen(j))
.at(0)
.get<std::string_view>()
.tie(answer, error);
if (error) {
return false;
}
s = answer;
return true;
}
#endif
};
REGISTER_TEST(SimdTest);
<commit_msg>Tweaking.<commit_after>#include <sstream>
#include <string>
#include <string_view>
#include "../test.h"
#include "simdjson.cpp"
#include "simdjson.h"
using namespace simdjson;
static void GenStat(Stat &stat, const dom::element &v) {
switch (v.type()) {
case dom::element_type::ARRAY:
for (dom::element child : dom::array(v)) {
stat.elementCount++;
GenStat(stat, child);
}
stat.arrayCount++;
break;
case dom::element_type::OBJECT:
for (dom::key_value_pair kv : dom::object(v)) {
GenStat(stat, dom::element(kv.value));
stat.memberCount++;
stat.stringCount++;
}
stat.objectCount++;
break;
case dom::element_type::INT64:
case dom::element_type::UINT64:
case dom::element_type::DOUBLE:
stat.numberCount++;
break;
case dom::element_type::STRING: {
stat.stringCount++;
std::string_view sv = v.get<std::string_view>();
stat.stringLength += sv.size();
} break;
case dom::element_type::BOOL:
if (v.get<bool>()) {
stat.trueCount++;
} else {
stat.falseCount++;
}
break;
case dom::element_type::NULL_VALUE:
++stat.nullCount;
break;
}
}
class SimdJsonParseResult : public ParseResultBase {
public:
dom::element root{};
std::unique_ptr<dom::parser> parser = std::make_unique<dom::parser>();
};
class SimdStringResult : public StringResultBase {
public:
std::stringstream ss;
const char *c_str() const override { return ss.str().c_str(); }
};
class SimdTest : public TestBase {
public:
#if TEST_INFO
const char *GetName() const override { return "simdjson"; }
const char *GetFilename() const override { return __FILE__; }
#endif
#if TEST_PARSE
ParseResultBase *Parse(const char *j, size_t length) const override {
auto pr = std::make_unique<SimdJsonParseResult>();
std::string_view s(j, length);
simdjson::error_code error;
pr->parser->parse(s).tie(pr->root, error);
if (error) {
return nullptr;
}
return pr.release();
}
#endif
#if TEST_STRINGIFY
StringResultBase *Stringify(
const ParseResultBase *parseResult) const override {
auto sr = std::make_unique<SimdStringResult>();
auto pr = static_cast<const SimdJsonParseResult *>(parseResult);
sr->ss << pr->root;
return sr.release();
}
#endif
#if TEST_PRETTIFY
// Currently unsupported, simdjson v0.3
StringResultBase *Prettify(
const ParseResultBase *parseResult) const override {
(void)parseResult;
return nullptr;
}
#endif
#if TEST_STATISTICS
bool Statistics(const ParseResultBase *parseResult,
Stat *stat) const override {
auto pr = static_cast<const SimdJsonParseResult *>(parseResult);
memset(stat, 0, sizeof(Stat));
GenStat(*stat, pr->root);
return true;
}
#endif
#if TEST_CONFORMANCE
bool ParseDouble(const char *j, double *d) const override {
simdjson::error_code error;
simdjson::dom::parser parser;
parser.parse(j, std::strlen(j)).at(0).get<double>().tie(*d, error);
if (error) {
return false;
}
return true;
}
bool ParseString(const char *j, std::string &s) const override {
simdjson::error_code error;
std::string_view answer;
parser.parse(j,strlen(j))
.at(0)
.get<std::string_view>()
.tie(answer, error);
if (error) {
return false;
}
s.assign(answer.data(), answer.size());
return true;
}
#endif
};
REGISTER_TEST(SimdTest);
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: TableDeco.hxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: hr $ $Date: 2004-08-02 15:13: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 _DBA_CORE_TABLEDECORATOR_HXX_
#define _DBA_CORE_TABLEDECORATOR_HXX_
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATSSUPPLIER_HPP_
#include <com/sun/star/util/XNumberFormatsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XCOLUMNSSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XColumnsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XDATADESCRIPTORFACTORY_HPP_
#include <com/sun/star/sdbcx/XDataDescriptorFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XINDEXESSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XIndexesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XKEYSSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XKeysSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XRENAME_HPP_
#include <com/sun/star/sdbcx/XRename.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XALTERTABLE_HPP_
#include <com/sun/star/sdbcx/XAlterTable.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE9_HXX_
#include <cppuhelper/compbase9.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE5_HXX_
#include <cppuhelper/implbase5.hxx>
#endif
#ifndef _DBASHARED_APITOOLS_HXX_
#include "apitools.hxx"
#endif
#ifndef _DBA_CORE_DATASETTINGS_HXX_
#include "datasettings.hxx"
#endif
#ifndef _DBA_COREAPI_COLUMN_HXX_
#include "column.hxx"
#endif
#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#include <connectivity/CommonTools.hxx>
#endif
#ifndef _CONNECTIVITY_SDBCX_IREFRESHABLE_HXX_
#include <connectivity/sdbcx/IRefreshable.hxx>
#endif
#ifndef COMPHELPER_IDPROPERTYARRAYUSAGEHELPER_HXX
#include <comphelper/IdPropArrayHelper.hxx>
#endif
namespace dbaccess
{
typedef ::cppu::WeakComponentImplHelper9< ::com::sun::star::sdbcx::XColumnsSupplier,
::com::sun::star::sdbcx::XKeysSupplier,
::com::sun::star::container::XNamed,
::com::sun::star::lang::XServiceInfo,
::com::sun::star::sdbcx::XDataDescriptorFactory,
::com::sun::star::sdbcx::XIndexesSupplier,
::com::sun::star::sdbcx::XRename,
::com::sun::star::lang::XUnoTunnel,
::com::sun::star::sdbcx::XAlterTable> OTableDescriptor_BASE;
//==========================================================================
//= OTables
//==========================================================================
class ODBTableDecorator;
typedef ::comphelper::OIdPropertyArrayUsageHelper< ODBTableDecorator > ODBTableDecorator_PROP;
class ODBTableDecorator :public comphelper::OBaseMutex
,public OTableDescriptor_BASE
,public ODataSettings //ODataSettings_Base
,public IColumnFactory
,public ::connectivity::sdbcx::IRefreshableColumns
,public ODBTableDecorator_PROP
{
void fillPrivileges() const;
protected:
::com::sun::star::uno::Reference< ::com::sun::star::container::XContainerListener > m_xColumnMediator;
::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XColumnsSupplier > m_xTable;
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > m_xColumnDefinitions;
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > m_xMetaData;
::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier > m_xNumberFormats;
// <properties>
mutable sal_Int32 m_nPrivileges;
// </properties>
::connectivity::sdbcx::OCollection* m_pColumns;
::connectivity::sdbcx::OCollection* m_pTables;
// IColumnFactory
virtual OColumn* createColumn(const ::rtl::OUString& _rName) const;
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > createEmptyObject();
virtual void columnDropped(const ::rtl::OUString& _sName);
virtual void refreshColumns();
virtual ::cppu::IPropertyArrayHelper* createArrayHelper(sal_Int32 _nId) const;
virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();
// OPropertySetHelper
virtual sal_Bool SAL_CALL convertFastPropertyValue(
::com::sun::star::uno::Any & rConvertedValue,
::com::sun::star::uno::Any & rOldValue,
sal_Int32 nHandle,
const ::com::sun::star::uno::Any& rValue )
throw (::com::sun::star::lang::IllegalArgumentException);
virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle) const;
virtual void SAL_CALL setFastPropertyValue_NoBroadcast(
sal_Int32 nHandle,
const ::com::sun::star::uno::Any& rValue
)
throw (::com::sun::star::uno::Exception);
virtual ~ODBTableDecorator();
public:
/** constructs a wrapper supporting the com.sun.star.sdb.Table service.<BR>
@param _rxConn the connection the table belongs to
@param _rxTable the table from the driver can be null
*/
ODBTableDecorator(
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >& _rxConn
,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XColumnsSupplier >& _rxTable
,const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >& _rxNumberFormats
,const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& _rxColumnDefinitions
) throw(::com::sun::star::sdbc::SQLException);
void setTable(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XColumnsSupplier >& _rxTable);
// ODescriptor
virtual void construct();
//XInterface
virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL acquire() throw();
virtual void SAL_CALL release() throw();
//XTypeProvider
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw (::com::sun::star::uno::RuntimeException);
// OComponentHelper
virtual void SAL_CALL disposing(void);
// ::com::sun::star::lang::XServiceInfo
DECLARE_SERVICE_INFO();
// XPropertySet
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::sdbcx::XRename,
virtual void SAL_CALL rename( const ::rtl::OUString& _rNewName ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::container::ElementExistException, ::com::sun::star::uno::RuntimeException);
// ::com::sun::star::sdbcx::XAlterTable,
virtual void SAL_CALL alterColumnByName( const ::rtl::OUString& _rName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxDescriptor ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL alterColumnByIndex( sal_Int32 _nIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxDescriptor ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
// XNamed
virtual ::rtl::OUString SAL_CALL getName() throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setName( const ::rtl::OUString& aName ) throw (::com::sun::star::uno::RuntimeException);
// com::sun::star::lang::XUnoTunnel
virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);
static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData> getMetaData() const { return m_xMetaData; }
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> getConnection() const { return m_xMetaData.is() ? m_xMetaData->getConnection() : ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>(); }
// XColumnsSupplier
virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getColumns( ) throw (::com::sun::star::uno::RuntimeException);
// XKeysSupplier
virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess > SAL_CALL getKeys( ) throw (::com::sun::star::uno::RuntimeException);
// XIndexesSupplier
virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getIndexes( ) throw (::com::sun::star::uno::RuntimeException);
// XDataDescriptorFactory
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > SAL_CALL createDataDescriptor( ) throw (::com::sun::star::uno::RuntimeException);
};
}
#endif // _DBA_CORE_TABLEDECORATOR_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.15.204); FILE MERGED 2005/09/05 17:32:27 rt 1.15.204.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: TableDeco.hxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: rt $ $Date: 2005-09-08 13:34:22 $
*
* 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 _DBA_CORE_TABLEDECORATOR_HXX_
#define _DBA_CORE_TABLEDECORATOR_HXX_
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATSSUPPLIER_HPP_
#include <com/sun/star/util/XNumberFormatsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XCOLUMNSSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XColumnsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XDATADESCRIPTORFACTORY_HPP_
#include <com/sun/star/sdbcx/XDataDescriptorFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XINDEXESSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XIndexesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XKEYSSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XKeysSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XRENAME_HPP_
#include <com/sun/star/sdbcx/XRename.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XALTERTABLE_HPP_
#include <com/sun/star/sdbcx/XAlterTable.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE9_HXX_
#include <cppuhelper/compbase9.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE5_HXX_
#include <cppuhelper/implbase5.hxx>
#endif
#ifndef _DBASHARED_APITOOLS_HXX_
#include "apitools.hxx"
#endif
#ifndef _DBA_CORE_DATASETTINGS_HXX_
#include "datasettings.hxx"
#endif
#ifndef _DBA_COREAPI_COLUMN_HXX_
#include "column.hxx"
#endif
#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#include <connectivity/CommonTools.hxx>
#endif
#ifndef _CONNECTIVITY_SDBCX_IREFRESHABLE_HXX_
#include <connectivity/sdbcx/IRefreshable.hxx>
#endif
#ifndef COMPHELPER_IDPROPERTYARRAYUSAGEHELPER_HXX
#include <comphelper/IdPropArrayHelper.hxx>
#endif
namespace dbaccess
{
typedef ::cppu::WeakComponentImplHelper9< ::com::sun::star::sdbcx::XColumnsSupplier,
::com::sun::star::sdbcx::XKeysSupplier,
::com::sun::star::container::XNamed,
::com::sun::star::lang::XServiceInfo,
::com::sun::star::sdbcx::XDataDescriptorFactory,
::com::sun::star::sdbcx::XIndexesSupplier,
::com::sun::star::sdbcx::XRename,
::com::sun::star::lang::XUnoTunnel,
::com::sun::star::sdbcx::XAlterTable> OTableDescriptor_BASE;
//==========================================================================
//= OTables
//==========================================================================
class ODBTableDecorator;
typedef ::comphelper::OIdPropertyArrayUsageHelper< ODBTableDecorator > ODBTableDecorator_PROP;
class ODBTableDecorator :public comphelper::OBaseMutex
,public OTableDescriptor_BASE
,public ODataSettings //ODataSettings_Base
,public IColumnFactory
,public ::connectivity::sdbcx::IRefreshableColumns
,public ODBTableDecorator_PROP
{
void fillPrivileges() const;
protected:
::com::sun::star::uno::Reference< ::com::sun::star::container::XContainerListener > m_xColumnMediator;
::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XColumnsSupplier > m_xTable;
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > m_xColumnDefinitions;
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > m_xMetaData;
::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier > m_xNumberFormats;
// <properties>
mutable sal_Int32 m_nPrivileges;
// </properties>
::connectivity::sdbcx::OCollection* m_pColumns;
::connectivity::sdbcx::OCollection* m_pTables;
// IColumnFactory
virtual OColumn* createColumn(const ::rtl::OUString& _rName) const;
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > createEmptyObject();
virtual void columnDropped(const ::rtl::OUString& _sName);
virtual void refreshColumns();
virtual ::cppu::IPropertyArrayHelper* createArrayHelper(sal_Int32 _nId) const;
virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();
// OPropertySetHelper
virtual sal_Bool SAL_CALL convertFastPropertyValue(
::com::sun::star::uno::Any & rConvertedValue,
::com::sun::star::uno::Any & rOldValue,
sal_Int32 nHandle,
const ::com::sun::star::uno::Any& rValue )
throw (::com::sun::star::lang::IllegalArgumentException);
virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle) const;
virtual void SAL_CALL setFastPropertyValue_NoBroadcast(
sal_Int32 nHandle,
const ::com::sun::star::uno::Any& rValue
)
throw (::com::sun::star::uno::Exception);
virtual ~ODBTableDecorator();
public:
/** constructs a wrapper supporting the com.sun.star.sdb.Table service.<BR>
@param _rxConn the connection the table belongs to
@param _rxTable the table from the driver can be null
*/
ODBTableDecorator(
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >& _rxConn
,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XColumnsSupplier >& _rxTable
,const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >& _rxNumberFormats
,const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& _rxColumnDefinitions
) throw(::com::sun::star::sdbc::SQLException);
void setTable(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XColumnsSupplier >& _rxTable);
// ODescriptor
virtual void construct();
//XInterface
virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL acquire() throw();
virtual void SAL_CALL release() throw();
//XTypeProvider
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw (::com::sun::star::uno::RuntimeException);
// OComponentHelper
virtual void SAL_CALL disposing(void);
// ::com::sun::star::lang::XServiceInfo
DECLARE_SERVICE_INFO();
// XPropertySet
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::sdbcx::XRename,
virtual void SAL_CALL rename( const ::rtl::OUString& _rNewName ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::container::ElementExistException, ::com::sun::star::uno::RuntimeException);
// ::com::sun::star::sdbcx::XAlterTable,
virtual void SAL_CALL alterColumnByName( const ::rtl::OUString& _rName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxDescriptor ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL alterColumnByIndex( sal_Int32 _nIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxDescriptor ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
// XNamed
virtual ::rtl::OUString SAL_CALL getName() throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setName( const ::rtl::OUString& aName ) throw (::com::sun::star::uno::RuntimeException);
// com::sun::star::lang::XUnoTunnel
virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);
static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData> getMetaData() const { return m_xMetaData; }
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> getConnection() const { return m_xMetaData.is() ? m_xMetaData->getConnection() : ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>(); }
// XColumnsSupplier
virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getColumns( ) throw (::com::sun::star::uno::RuntimeException);
// XKeysSupplier
virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess > SAL_CALL getKeys( ) throw (::com::sun::star::uno::RuntimeException);
// XIndexesSupplier
virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getIndexes( ) throw (::com::sun::star::uno::RuntimeException);
// XDataDescriptorFactory
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > SAL_CALL createDataDescriptor( ) throw (::com::sun::star::uno::RuntimeException);
};
}
#endif // _DBA_CORE_TABLEDECORATOR_HXX_
<|endoftext|> |
<commit_before>{{{header}}}
{{#includes}}
#include <{{{.}}}>
{{/includes}}
{{{precontent}}}
#include <boost/python.hpp>
#include <cmath>
/* postinclude */
void {{class.mangled_name}}()
{
::boost::python::object parent_object(::boost::python::scope(){{!
}}{{#class.scope}}{{#name}}.attr("{{name}}"){{/name}}{{/class.scope}});
::boost::python::scope parent_scope(parent_object);
::boost::python::class_<{{{class.type}}}{{^class.is_copyable}}, {{!
}}::boost::noncopyable{{/class.is_copyable}}{{#class.held_type}}, {{!
}}{{{.}}}{{/class.held_type}}{{#class.bases?}}, {{!
}}::boost::python::bases<{{!
}}{{#class.bases}}{{{qualified_name}}}{{^last}}, {{/last}}{{/class.bases}}{{!
}} >{{/class.bases?}} >("{{class.name}}", boost::python::no_init){{!
/* constructors */}}
{{#class.constructors}}{{!
}}.def(::boost::python::init<{{!
}}{{#params}}{{{type}}}{{^last}}, {{/last}}{{/params}}{{!
}}>({{#params?}}({{#params}}::boost::python::arg("{{name}}"){{^last}}, {{/last}}{{/params}}){{/params?}}))
{{/class.constructors}}{{!
/* member functions */}}
{{#class.methods}}{{!
}}{{^is_static}}{{!
}}{{#overloads}}{{!
}}.def("{{name}}", []({{#is_const}}const {{/is_const}}{{{class.type}}} *self{{#params}}, {{{type}}} {{name}}{{/params}}) -> {{{return_type}}} { {{!
}}return self->{{name}}({{#params}}{{name}}{{^last}}, {{/last}}{{/params}}); }{{!
}}{{#return_value_policy}}, ::boost::python::return_value_policy<{{{.}}} >(){{/return_value_policy}}{{!
}}{{#params?}}, ({{#params}}::boost::python::arg("{{name}}"){{^last}}, {{/last}}{{/params}}){{/params?}})
{{/overloads}}{{!
}}{{/is_static}}{{!
}}{{/class.methods}}{{!
/* static member functions */}}
{{#class.methods}}{{!
}}{{#is_static}}{{!
}}{{#overloads}}{{!
}}.def("{{name}}", []({{#params}}{{{type}}} {{name}}{{^last}}, {{/last}}{{/params}}) -> {{{return_type}}} { {{!
}}return {{{class.qualified_name}}}::{{name}}({{#params}}{{name}}{{^last}}, {{/last}}{{/params}}); }{{!
}}{{#return_value_policy}}, ::boost::python::return_value_policy<{{{.}}} >(){{/return_value_policy}}{{!
}}{{#params?}}, ({{#params}}::boost::python::arg("{{name}}"){{^last}}, {{/last}}{{/params}}){{/params?}})
{{/overloads}}{{!
}}{{/is_static}}{{!
}}{{/class.methods}}
{{#class.static_methods}}{{!
}}.staticmethod("{{.}}")
{{/class.static_methods}}{{!
/* fields */}}
{{#class.fields}}{{!
}}{{#is_assignable}}.def_readwrite{{/is_assignable}}{{!
}}{{^is_assignable}}.def_readonly{{/is_assignable}}{{!
}}("{{name}}", &{{{qualified_name}}})
{{/class.fields}}{{!
/* static fields */
/* TODO: Add make_setter if this property is assignable */}}
{{#class.static_fields}}{{!
}}.add_static_property("{{name}}", {{!
}}::boost::python::make_getter({{{qualified_name}}}))
{{/class.static_fields}}
;
}
{{{postcontent}}}
{{{footer}}}
<commit_msg>Fixed constructor overloads.<commit_after>{{{header}}}
{{#includes}}
#include <{{{.}}}>
{{/includes}}
{{{precontent}}}
#include <boost/python.hpp>
#include <cmath>
/* postinclude */
void {{class.mangled_name}}()
{
::boost::python::object parent_object(::boost::python::scope(){{!
}}{{#class.scope}}{{#name}}.attr("{{name}}"){{/name}}{{/class.scope}});
::boost::python::scope parent_scope(parent_object);
::boost::python::class_<{{{class.type}}}{{^class.is_copyable}}, {{!
}}::boost::noncopyable{{/class.is_copyable}}{{#class.held_type}}, {{!
}}{{{.}}}{{/class.held_type}}{{#class.bases?}}, {{!
}}::boost::python::bases<{{!
}}{{#class.bases}}{{{qualified_name}}}{{^last}}, {{/last}}{{/class.bases}}{{!
}} >{{/class.bases?}} >("{{class.name}}", boost::python::no_init){{!
/* constructors */}}
{{#class.constructors}}{{!
}}{{#overloads}}{{!
}}.def("__init__", ::boost::python::make_constructor({{!
}}[]({{#params}}{{{type}}} {{name}}{{^last}}, {{/last}}{{/params}}){{!
}} -> {{{class.type}}} * { {{!
}}return new {{{class.type}}}({{#params}}{{name}}{{^last}}, {{/last}}{{/params}}); }{{!
}}, ::boost::python::default_call_policies(){{!
}}{{#params?}}, ({{#params}}::boost::python::arg("{{name}}"){{^last}}, {{/last}}{{/params}}){{/params?}}))
{{/overloads}}{{!
}}{{/class.constructors}}{{!
/* member functions */}}
{{#class.methods}}{{!
}}{{^is_static}}{{!
}}{{#overloads}}{{!
}}.def("{{name}}", []({{#is_const}}const {{/is_const}}{{{class.type}}} *self{{#params}}, {{{type}}} {{name}}{{/params}}) -> {{{return_type}}} { {{!
}}return self->{{name}}({{#params}}{{name}}{{^last}}, {{/last}}{{/params}}); }{{!
}}{{#return_value_policy}}, ::boost::python::return_value_policy<{{{.}}} >(){{/return_value_policy}}{{!
}}{{#params?}}, ({{#params}}::boost::python::arg("{{name}}"){{^last}}, {{/last}}{{/params}}){{/params?}})
{{/overloads}}{{!
}}{{/is_static}}{{!
}}{{/class.methods}}{{!
/* static member functions */}}
{{#class.methods}}{{!
}}{{#is_static}}{{!
}}{{#overloads}}{{!
}}.def("{{name}}", []({{#params}}{{{type}}} {{name}}{{^last}}, {{/last}}{{/params}}) -> {{{return_type}}} { {{!
}}return {{{class.qualified_name}}}::{{name}}({{#params}}{{name}}{{^last}}, {{/last}}{{/params}}); }{{!
}}{{#return_value_policy}}, ::boost::python::return_value_policy<{{{.}}} >(){{/return_value_policy}}{{!
}}{{#params?}}, ({{#params}}::boost::python::arg("{{name}}"){{^last}}, {{/last}}{{/params}}){{/params?}})
{{/overloads}}{{!
}}{{/is_static}}{{!
}}{{/class.methods}}
{{#class.static_methods}}{{!
}}.staticmethod("{{.}}")
{{/class.static_methods}}{{!
/* fields */}}
{{#class.fields}}{{!
}}{{#is_assignable}}.def_readwrite{{/is_assignable}}{{!
}}{{^is_assignable}}.def_readonly{{/is_assignable}}{{!
}}("{{name}}", &{{{qualified_name}}})
{{/class.fields}}{{!
/* static fields */
/* TODO: Add make_setter if this property is assignable */}}
{{#class.static_fields}}{{!
}}.add_static_property("{{name}}", {{!
}}::boost::python::make_getter({{{qualified_name}}}))
{{/class.static_fields}}
;
}
{{{postcontent}}}
{{{footer}}}
<|endoftext|> |
<commit_before><commit_msg>No chartopengl library built for iOS or Android yet<commit_after><|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
int main(int argc,char *argv[]) {
std::vector<std::string> temp(5);
std::string tempString;
std::ifstream ifs(argv[1]);
std::istringstream istringstream(tempString);
int n=0;
if(!(ifs.is_open())) {
std::cerr << "Error! Could not open file";
}
while (std::getline(ifs, tempString)) {
for (std::istream_iterator<std::string> iterator = std::istream_iterator<std::string>(istringstream);
iterator != std::istream_iterator<std::string>() && n < 5; ++iterator, ++n) {
temp[n] = *iterator;
}
}
ifs.close();
std::cout << "Hello World\n";
return 0;
}<commit_msg>Fixed main.cpp<commit_after>#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
int main(int argc,char *argv[]) {
std::vector<std::string> temp(5);
std::string tempString;
std::string file = argv[1];
std::ifstream ifs(file);
std::istringstream istringstream(tempString);
int n=0;
if(!(ifs.is_open())) {
std::cerr << "Error! Could not open file";
}
while (std::getline(ifs, tempString)) {
for (std::istream_iterator<std::string> iterator = std::istream_iterator<std::string>(istringstream);
iterator != std::istream_iterator<std::string>() && n < 5; ++iterator, ++n) {
temp[n] = *iterator;
}
}
ifs.close();
std::cout << "Hello World\n";
return 0;
}<|endoftext|> |
<commit_before>#include "blob.h"
#include "file.h"
#include "string.h"
#include <sys/stat.h>
#include <sys/unistd.h>
File::File(const String &file_name, const String &mode) {
file = fopen(file_name, mode);
}
File::~File() {
if (file)
fclose(file);
}
int File::atime(const String &file_name) {
struct stat buf;
if (stat(file_name, &buf) < 0)
throw "Stat failure";
return buf.st_atime;
}
int File::ctime(const String &file_name) {
struct stat buf;
if (stat(file_name, &buf) < 0)
throw "Stat failure";
return buf.st_ctime;
}
static const char *last_separator(const char *path) {
const char *last = NULL;
while (*path) {
if (*path == '/') {
const char *tmp = path++;
while (*path == '/')
path++;
if (!*path)
break;
last = tmp;
} else {
path++;
}
}
return last;
}
String File::dirname(const String &path) {
const char *name = path;
const char *root = name;
while (*root == '/')
root++;
if (root > name + 1)
name = root - 1;
const char *last = last_separator(root);
if (!last)
last = root;
if (last == name)
return ".";
return String(name, 0, last - name);
}
bool File::exists(const String &file_name) {
struct stat buf;
if (stat(file_name, &buf) < 0)
return false;
return true;
}
bool File::is_directory(const String &file_name) {
struct stat buf;
if (stat(file_name, &buf) < 0)
return false;
if (S_ISDIR(buf.st_mode))
return true;
return false;
}
bool File::is_file(const String &file_name) {
struct stat buf;
if (stat(file_name, &buf) < 0)
return false;
if (S_ISREG(buf.st_mode))
return true;
return false;
}
bool File::is_readable(const String &file_name) {
if (access(file_name, R_OK) < 0)
return false;
return true;
}
//Time File::mtime(const String &file_name) {
int File::mtime(const String &file_name) {
struct stat buf;
if (stat(file_name, &buf) < 0)
throw "Stat failure";
long sec = buf.st_mtime;
/*
#if defined(HAVE_STRUCT_STAT_ST_MTIM)
int nsec = st->st_mtim.tv_nsec;
#elif defined(HAVE_STRUCT_STAT_ST_MTIMESPEC)
int nsec = st->st_mtimespec.tv_nsec;
#elif defined(HAVE_STRUCT_STAT_ST_MTIMENSEC)
int nsec = st->st_mtimensec;
#else
int nsec = 0;
#endif
*/
return sec; //Time::at(sec, nsec);
}
long File::size(const String &file_name) {
struct stat buf;
if (stat(file_name, &buf) < 0)
throw "Stat failure";
return buf.st_size;
}
void File::close() {
fclose(file);
file = nullptr;
}
Blob File::read(int length) {
if (length == -1)
length = size() - tell();
Blob result;
result.ensure_capacity(length);
int read = fread(result.ptr(), 1, length, file);
result.size(read);
return result;
}
long File::size() const {
struct stat buf;
int fd = fileno(file);
if (fstat(fd, &buf) == -1)
throw "Stat failure";
return buf.st_size;
}
long File::tell() const {
return ftell(file);
}
<commit_msg>Changed File throws to proper exceptions.<commit_after>#include "blob.h"
#include "file.h"
#include "string.h"
#include "errno_exception.h"
#include <sys/stat.h>
#include <sys/unistd.h>
File::File(const String &file_name, const String &mode) {
file = fopen(file_name, mode);
}
File::~File() {
if (file)
fclose(file);
}
int File::atime(const String &file_name) {
struct stat buf;
if (stat(file_name, &buf) < 0)
throw ErrnoException("Could not stat " + file_name, errno);
return buf.st_atime;
}
int File::ctime(const String &file_name) {
struct stat buf;
if (stat(file_name, &buf) < 0)
throw ErrnoException("Could not stat " + file_name, errno);
return buf.st_ctime;
}
static const char *last_separator(const char *path) {
const char *last = NULL;
while (*path) {
if (*path == '/') {
const char *tmp = path++;
while (*path == '/')
path++;
if (!*path)
break;
last = tmp;
} else {
path++;
}
}
return last;
}
String File::dirname(const String &path) {
const char *name = path;
const char *root = name;
while (*root == '/')
root++;
if (root > name + 1)
name = root - 1;
const char *last = last_separator(root);
if (!last)
last = root;
if (last == name)
return ".";
return String(name, 0, last - name);
}
bool File::exists(const String &file_name) {
struct stat buf;
if (stat(file_name, &buf) < 0)
return false;
return true;
}
bool File::is_directory(const String &file_name) {
struct stat buf;
if (stat(file_name, &buf) < 0)
return false;
if (S_ISDIR(buf.st_mode))
return true;
return false;
}
bool File::is_file(const String &file_name) {
struct stat buf;
if (stat(file_name, &buf) < 0)
return false;
if (S_ISREG(buf.st_mode))
return true;
return false;
}
bool File::is_readable(const String &file_name) {
if (access(file_name, R_OK) < 0)
return false;
return true;
}
//Time File::mtime(const String &file_name) {
int File::mtime(const String &file_name) {
struct stat buf;
if (stat(file_name, &buf) < 0)
throw ErrnoException("Could not stat " + file_name, errno);
long sec = buf.st_mtime;
/*
#if defined(HAVE_STRUCT_STAT_ST_MTIM)
int nsec = st->st_mtim.tv_nsec;
#elif defined(HAVE_STRUCT_STAT_ST_MTIMESPEC)
int nsec = st->st_mtimespec.tv_nsec;
#elif defined(HAVE_STRUCT_STAT_ST_MTIMENSEC)
int nsec = st->st_mtimensec;
#else
int nsec = 0;
#endif
*/
return sec; //Time::at(sec, nsec);
}
long File::size(const String &file_name) {
struct stat buf;
if (stat(file_name, &buf) < 0)
throw ErrnoException("Could not stat " + file_name, errno);
return buf.st_size;
}
void File::close() {
fclose(file);
file = nullptr;
}
Blob File::read(int length) {
if (length == -1)
length = size() - tell();
Blob result;
result.ensure_capacity(length);
int read = fread(result.ptr(), 1, length, file);
result.size(read);
return result;
}
long File::size() const {
struct stat buf;
int fd = fileno(file);
if (fstat(fd, &buf) == -1)
throw ErrnoException("Could not stat " + file_name, errno);
return buf.st_size;
}
long File::tell() const {
return ftell(file);
}
<|endoftext|> |
<commit_before><commit_msg>Fix options window for Personalization on Linux. Review URL: http://codereview.chromium.org/132028<commit_after><|endoftext|> |
<commit_before><commit_msg>[GTK] Use gtk_window_present_with_time since the doc's says it is better to use it when it is a response to a user action.<commit_after><|endoftext|> |
<commit_before>/**************************************************************************
* newbucket.hxx -- new bucket routines for better world modeling
*
* Written by Curtis L. Olson, started February 1999.
*
* Copyright (C) 1999 Curtis L. Olson - curt@flightgear.org
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id$
**************************************************************************/
#ifndef _NEWBUCKET_HXX
#define _NEWBUCKET_HXX
#include <Include/compiler.h>
#include STL_STRING
#ifdef FG_HAVE_STD_INCLUDES
# include <cstdio> // sprintf()
# include <iostream>
#else
# include <stdio.h> // sprintf()
# include <iostream.h>
#endif
FG_USING_STD(string);
#if ! defined( FG_HAVE_NATIVE_SGI_COMPILERS )
FG_USING_STD(ostream);
#endif
#ifdef __MWERKS__
#include <math.h>
#include <stdio.h>
#endif
#include <Include/fg_constants.h>
#define FG_BUCKET_SPAN 0.125 // 1/8 of a degree
#define FG_HALF_BUCKET_SPAN 0.0625 // 1/2 of 1/8 of a degree = 1/16 = 0.0625
class FGBucket;
ostream& operator<< ( ostream&, const FGBucket& );
bool operator== ( const FGBucket&, const FGBucket& );
class FGBucket {
private:
double cx, cy; // centerpoint (lon, lat) in degrees of bucket
int lon; // longitude index (-180 to 179)
int lat; // latitude index (-90 to 89)
int x; // x subdivision (0 to 7)
int y; // y subdivision (0 to 7)
public:
// default constructor
FGBucket();
// create a bucket which would contain the specified lon/lat
FGBucket(const double lon, const double lat);
// create a bucket based on "long int" index
FGBucket(const long int bindex);
// create an impossible bucket if false
FGBucket(const bool is_good);
~FGBucket();
// Set the bucket params for the specified lat and lon
void set_bucket( double dlon, double dlat );
void make_bad ( void );
// Generate the unique scenery tile index for this bucket
long int gen_index();
string gen_index_str() const;
// Build the path name for this bucket
string gen_base_path() const;
// return the center lon of a tile
double get_center_lon() const;
// return width of the tile
double get_width() const;
// return the center lat of a tile
double get_center_lat() const;
// return height of the tile
double get_height() const;
// Informational methods
inline int get_lon() const { return lon; }
inline int get_lat() const { return lat; }
inline int get_x() const { return x; }
inline int get_y() const { return y; }
// friends
friend ostream& operator<< ( ostream&, const FGBucket& );
friend bool operator== ( const FGBucket&, const FGBucket& );
};
// return the horizontal tile span factor based on latitude
inline double bucket_span( double l ) {
if ( l >= 89.0 ) {
return 360.0;
} else if ( l >= 88.0 ) {
return 8.0;
} else if ( l >= 86.0 ) {
return 4.0;
} else if ( l >= 83.0 ) {
return 2.0;
} else if ( l >= 76.0 ) {
return 1.0;
} else if ( l >= 62.0 ) {
return 0.5;
} else if ( l >= 22.0 ) {
return 0.25;
} else if ( l >= -22.0 ) {
return 0.125;
} else if ( l >= -62.0 ) {
return 0.25;
} else if ( l >= -76.0 ) {
return 0.5;
} else if ( l >= -83.0 ) {
return 1.0;
} else if ( l >= -86.0 ) {
return 2.0;
} else if ( l >= -88.0 ) {
return 4.0;
} else if ( l >= -89.0 ) {
return 8.0;
} else {
return 360.0;
}
}
// Set the bucket params for the specified lat and lon
inline void FGBucket::set_bucket( double dlon, double dlat ) {
//
// latitude first
//
double span = bucket_span( dlat );
double diff = dlon - (double)(int)dlon;
// cout << "diff = " << diff << " span = " << span << endl;
if ( (dlon >= 0) || (fabs(diff) < FG_EPSILON) ) {
lon = (int)dlon;
} else {
lon = (int)dlon - 1;
}
// find subdivision or super lon if needed
if ( span < FG_EPSILON ) {
// polar cap
lon = 0;
x = 0;
} else if ( span <= 1.0 ) {
x = (int)((dlon - lon) / span);
} else {
if ( (dlon >= 0) || (fabs(diff) < FG_EPSILON) ) {
lon = (int)( (int)(lon / span) * span);
} else {
// cout << " lon = " << lon
// << " tmp = " << (int)((lon-1) / span) << endl;
lon = (int)( (int)((lon + 1) / span) * span - span);
if ( lon < -180 ) {
lon = -180;
}
}
x = 0;
}
//
// then latitude
//
diff = dlat - (double)(int)dlat;
if ( (dlat >= 0) || (fabs(diff) < FG_EPSILON) ) {
lat = (int)dlat;
} else {
lat = (int)dlat - 1;
}
y = (int)((dlat - lat) * 8);
}
// default constructor
inline FGBucket::FGBucket() {}
// constructor for specified location
inline FGBucket::FGBucket(const double dlon, const double dlat) {
set_bucket(dlon, dlat);
}
// create an impossible bucket if false
inline FGBucket::FGBucket(const bool is_good) {
set_bucket(0.0, 0.0);
if ( !is_good ) {
lon = -1000;
}
}
// Parse a unique scenery tile index and find the lon, lat, x, and y
inline FGBucket::FGBucket(const long int bindex) {
long int index = bindex;
lon = index >> 14;
index -= lon << 14;
lon -= 180;
lat = index >> 6;
index -= lat << 6;
lat -= 90;
y = index >> 3;
index -= y << 3;
x = index;
}
// default destructor
inline FGBucket::~FGBucket() {}
// Generate the unique scenery tile index for this bucket
//
// The index is constructed as follows:
//
// 9 bits - to represent 360 degrees of longitude (-180 to 179)
// 8 bits - to represent 180 degrees of latitude (-90 to 89)
//
// Each 1 degree by 1 degree tile is further broken down into an 8x8
// grid. So we also need:
//
// 3 bits - to represent x (0 to 7)
// 3 bits - to represent y (0 to 7)
inline long int FGBucket::gen_index() {
return ((lon + 180) << 14) + ((lat + 90) << 6) + (y << 3) + x;
}
inline string FGBucket::gen_index_str() const {
char tmp[20];
sprintf(tmp, "%ld",
(((long)lon + 180) << 14) + ((lat + 90) << 6) + (y << 3) + x);
return (string)tmp;
}
// return the center lon of a tile
inline double FGBucket::get_center_lon() const {
double span = bucket_span( lat + y / 8.0 + FG_HALF_BUCKET_SPAN );
if ( span >= 1.0 ) {
return lon + span / 2.0;
} else {
return lon + x * span + span / 2.0;
}
}
// return width of the tile
inline double FGBucket::get_width() const {
return bucket_span( get_center_lat() );
}
// return the center lat of a tile
inline double FGBucket::get_center_lat() const {
return lat + y / 8.0 + FG_HALF_BUCKET_SPAN;
}
// return height of the tile
inline double FGBucket::get_height() const {
return FG_BUCKET_SPAN;
}
// create an impossible bucket
inline void FGBucket::make_bad( void ) {
set_bucket(0.0, 0.0);
lon = -1000;
}
// offset a bucket struct by the specified tile units in the X & Y
// direction
FGBucket fgBucketOffset( double dlon, double dlat, int x, int y );
// calculate the offset between two buckets
void fgBucketDiff( const FGBucket& b1, const FGBucket& b2, int *dx, int *dy );
/*
// Given a lat/lon, fill in the local tile index array
void fgBucketGenIdxArray(fgBUCKET *p1, fgBUCKET *tiles, int width, int height);
*/
inline ostream&
operator<< ( ostream& out, const FGBucket& b )
{
return out << b.lon << ":" << b.x << ", " << b.lat << ":" << b.y;
}
inline bool
operator== ( const FGBucket& b1, const FGBucket& b2 )
{
return ( b1.lon == b2.lon &&
b1.lat == b2.lat &&
b1.x == b2.x &&
b1.y == b2.y );
}
#endif // _NEWBUCKET_HXX
<commit_msg>Borland portability fixes contributed by Charlie Hotchkiss.<commit_after>/**************************************************************************
* newbucket.hxx -- new bucket routines for better world modeling
*
* Written by Curtis L. Olson, started February 1999.
*
* Copyright (C) 1999 Curtis L. Olson - curt@flightgear.org
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id$
**************************************************************************/
#ifndef _NEWBUCKET_HXX
#define _NEWBUCKET_HXX
#include <Include/compiler.h>
#ifdef FG_HAVE_STD_INCLUDES
# include <cmath>
# include <cstdio> // sprintf()
# include <iostream>
#else
# include <math.h>
# include <stdio.h> // sprintf()
# include <iostream.h>
#endif
#include STL_STRING
FG_USING_STD(string);
#if ! defined( FG_HAVE_NATIVE_SGI_COMPILERS )
FG_USING_STD(ostream);
#endif
#include <Include/fg_constants.h>
#define FG_BUCKET_SPAN 0.125 // 1/8 of a degree
#define FG_HALF_BUCKET_SPAN 0.0625 // 1/2 of 1/8 of a degree = 1/16 = 0.0625
class FGBucket;
ostream& operator<< ( ostream&, const FGBucket& );
bool operator== ( const FGBucket&, const FGBucket& );
class FGBucket {
private:
double cx, cy; // centerpoint (lon, lat) in degrees of bucket
int lon; // longitude index (-180 to 179)
int lat; // latitude index (-90 to 89)
int x; // x subdivision (0 to 7)
int y; // y subdivision (0 to 7)
public:
// default constructor
FGBucket();
// create a bucket which would contain the specified lon/lat
FGBucket(const double lon, const double lat);
// create a bucket based on "long int" index
FGBucket(const long int bindex);
// create an impossible bucket if false
FGBucket(const bool is_good);
~FGBucket();
// Set the bucket params for the specified lat and lon
void set_bucket( double dlon, double dlat );
void make_bad ( void );
// Generate the unique scenery tile index for this bucket
long int gen_index();
string gen_index_str() const;
// Build the path name for this bucket
string gen_base_path() const;
// return the center lon of a tile
double get_center_lon() const;
// return width of the tile
double get_width() const;
// return the center lat of a tile
double get_center_lat() const;
// return height of the tile
double get_height() const;
// Informational methods
inline int get_lon() const { return lon; }
inline int get_lat() const { return lat; }
inline int get_x() const { return x; }
inline int get_y() const { return y; }
// friends
friend ostream& operator<< ( ostream&, const FGBucket& );
friend bool operator== ( const FGBucket&, const FGBucket& );
};
// return the horizontal tile span factor based on latitude
inline double bucket_span( double l ) {
if ( l >= 89.0 ) {
return 360.0;
} else if ( l >= 88.0 ) {
return 8.0;
} else if ( l >= 86.0 ) {
return 4.0;
} else if ( l >= 83.0 ) {
return 2.0;
} else if ( l >= 76.0 ) {
return 1.0;
} else if ( l >= 62.0 ) {
return 0.5;
} else if ( l >= 22.0 ) {
return 0.25;
} else if ( l >= -22.0 ) {
return 0.125;
} else if ( l >= -62.0 ) {
return 0.25;
} else if ( l >= -76.0 ) {
return 0.5;
} else if ( l >= -83.0 ) {
return 1.0;
} else if ( l >= -86.0 ) {
return 2.0;
} else if ( l >= -88.0 ) {
return 4.0;
} else if ( l >= -89.0 ) {
return 8.0;
} else {
return 360.0;
}
}
// Set the bucket params for the specified lat and lon
inline void FGBucket::set_bucket( double dlon, double dlat ) {
//
// latitude first
//
double span = bucket_span( dlat );
double diff = dlon - (double)(int)dlon;
// cout << "diff = " << diff << " span = " << span << endl;
if ( (dlon >= 0) || (fabs(diff) < FG_EPSILON) ) {
lon = (int)dlon;
} else {
lon = (int)dlon - 1;
}
// find subdivision or super lon if needed
if ( span < FG_EPSILON ) {
// polar cap
lon = 0;
x = 0;
} else if ( span <= 1.0 ) {
x = (int)((dlon - lon) / span);
} else {
if ( (dlon >= 0) || (fabs(diff) < FG_EPSILON) ) {
lon = (int)( (int)(lon / span) * span);
} else {
// cout << " lon = " << lon
// << " tmp = " << (int)((lon-1) / span) << endl;
lon = (int)( (int)((lon + 1) / span) * span - span);
if ( lon < -180 ) {
lon = -180;
}
}
x = 0;
}
//
// then latitude
//
diff = dlat - (double)(int)dlat;
if ( (dlat >= 0) || (fabs(diff) < FG_EPSILON) ) {
lat = (int)dlat;
} else {
lat = (int)dlat - 1;
}
y = (int)((dlat - lat) * 8);
}
// default constructor
inline FGBucket::FGBucket() {}
// constructor for specified location
inline FGBucket::FGBucket(const double dlon, const double dlat) {
set_bucket(dlon, dlat);
}
// create an impossible bucket if false
inline FGBucket::FGBucket(const bool is_good) {
set_bucket(0.0, 0.0);
if ( !is_good ) {
lon = -1000;
}
}
// Parse a unique scenery tile index and find the lon, lat, x, and y
inline FGBucket::FGBucket(const long int bindex) {
long int index = bindex;
lon = index >> 14;
index -= lon << 14;
lon -= 180;
lat = index >> 6;
index -= lat << 6;
lat -= 90;
y = index >> 3;
index -= y << 3;
x = index;
}
// default destructor
inline FGBucket::~FGBucket() {}
// Generate the unique scenery tile index for this bucket
//
// The index is constructed as follows:
//
// 9 bits - to represent 360 degrees of longitude (-180 to 179)
// 8 bits - to represent 180 degrees of latitude (-90 to 89)
//
// Each 1 degree by 1 degree tile is further broken down into an 8x8
// grid. So we also need:
//
// 3 bits - to represent x (0 to 7)
// 3 bits - to represent y (0 to 7)
inline long int FGBucket::gen_index() {
return ((lon + 180) << 14) + ((lat + 90) << 6) + (y << 3) + x;
}
inline string FGBucket::gen_index_str() const {
char tmp[20];
sprintf(tmp, "%ld",
(((long)lon + 180) << 14) + ((lat + 90) << 6) + (y << 3) + x);
return (string)tmp;
}
// return the center lon of a tile
inline double FGBucket::get_center_lon() const {
double span = bucket_span( lat + y / 8.0 + FG_HALF_BUCKET_SPAN );
if ( span >= 1.0 ) {
return lon + span / 2.0;
} else {
return lon + x * span + span / 2.0;
}
}
// return width of the tile
inline double FGBucket::get_width() const {
return bucket_span( get_center_lat() );
}
// return the center lat of a tile
inline double FGBucket::get_center_lat() const {
return lat + y / 8.0 + FG_HALF_BUCKET_SPAN;
}
// return height of the tile
inline double FGBucket::get_height() const {
return FG_BUCKET_SPAN;
}
// create an impossible bucket
inline void FGBucket::make_bad( void ) {
set_bucket(0.0, 0.0);
lon = -1000;
}
// offset a bucket struct by the specified tile units in the X & Y
// direction
FGBucket fgBucketOffset( double dlon, double dlat, int x, int y );
// calculate the offset between two buckets
void fgBucketDiff( const FGBucket& b1, const FGBucket& b2, int *dx, int *dy );
/*
// Given a lat/lon, fill in the local tile index array
void fgBucketGenIdxArray(fgBUCKET *p1, fgBUCKET *tiles, int width, int height);
*/
inline ostream&
operator<< ( ostream& out, const FGBucket& b )
{
return out << b.lon << ":" << b.x << ", " << b.lat << ":" << b.y;
}
inline bool
operator== ( const FGBucket& b1, const FGBucket& b2 )
{
return ( b1.lon == b2.lon &&
b1.lat == b2.lat &&
b1.x == b2.x &&
b1.y == b2.y );
}
#endif // _NEWBUCKET_HXX
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <fstream>
#include "../boost_tools/tls.hpp"
#include "../pp/pop3.hpp"
#include "command_line.hpp"
#include "server_name_parsing.hpp"
#include "task.hpp"
using namespace boost::program_options;
namespace utils {
p_MC mailboxEnter (const string& host, const string& port,
const string& login, const string& password)
throw(MailClientException) {
p_TLP transportLayerProvider(new TLSTransportLayerProvider());
p_PP postProvider(new POP3PostProvider(transportLayerProvider));
p_MC mailClient(new MailClient(postProvider));
mailClient->connect(host, port);
if (password != "") {
mailClient->signin(login, password);
}
else {
mailClient->sendLogin(login);
// Enter password if required
if (mailClient->isPasswordRequired()) {
// Bad method, but nothing better was found
char* tmpPassword = getpass("Enter password: ");
mailClient->sendPassword(tmpPassword);
// That method was really bad...but C-like memory design
// is not the worse thing in C++11 code, huh?
free(tmpPassword);
}
}
return mailClient;
}
int getMessagesHeaders (const p_MC& mailClient, ostream& out) {
strings headers = mailClient->getLettersHeaders();
for (auto e : mailClient->getLettersHeaders()) {
out << e << endl;
}
return headers.size();
}
int getCommandLineParameters (int argumentsCount, char* arguments[],
string& host, string& port, string& login, string& password) {
/**
* Prepare command line arguments processing.
*/
options_description description = prepareCommandLineOptions ();
variables_map variablesMap;
try {
variablesMap = parseCommandLine(argumentsCount, arguments, description);
}
catch (const unknown_option& e) {
cerr << "An error occured: " << e.what() << endl;
return EXIT_FAILURE;
}
catch (const invalid_command_line_syntax& e) {
cerr << "An error occured: " << e.what() << endl;
return EXIT_FAILURE;
}
/**
* Display help menu if it was requested.
*/
if (variablesMap.count("help")) {
displayUsage (cerr, description, arguments[0]);
return EXIT_FAILURE;
}
/**
* Process variables.
*/
string server_name;
if (!getParameters(variablesMap, login, password, server_name)) {
cerr << "Not all mandatory parameters were set." << endl
<< "Please, run `" << arguments[0]
<< " --help' for more information." << endl;
return EXIT_FAILURE;
}
parseServerName(server_name, host, port);
return EXIT_SUCCESS;
}
int task (const string& host, const string& port,
const string& login, const string& password) {
p_MC mailClient;
try {
mailClient = mailboxEnter(host, port, login, password);
}
catch (const MailClientException& e) {
cerr << "Error occured when tried to enter the mailbox: "
<< e.what() << endl;
return EXIT_FAILURE;
}
try {
string outputFilename = "letters.txt";
ofstream out(outputFilename);
if (!out.is_open()) {
throw ios_base::failure("Can't open file " +
outputFilename + ".");
}
out.exceptions(std::ofstream::failbit | std::ofstream::badbit);
cout << getMessagesHeaders(mailClient, out) << endl;
out.close();
}
catch (const ios_base::failure& e) {
cerr << "Error occured when application worked with file: "
<< e.what() << endl;
return EXIT_FAILURE;
}
catch (const MailClientException& e) {
cerr << "Mail Client error occured when tried to read messages: "
<< e.what() << endl;
return EXIT_FAILURE;
}
try {
mailClient->signout();
}
catch (const MailClientException& e) {
cerr << "Error occured when tried to sign out from mailbox: "
<< e.what() << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
}
<commit_msg>Fixed redundant function call<commit_after>#include <cstdlib>
#include <fstream>
#include "../boost_tools/tls.hpp"
#include "../pp/pop3.hpp"
#include "command_line.hpp"
#include "server_name_parsing.hpp"
#include "task.hpp"
using namespace boost::program_options;
namespace utils {
p_MC mailboxEnter (const string& host, const string& port,
const string& login, const string& password)
throw(MailClientException) {
p_TLP transportLayerProvider(new TLSTransportLayerProvider());
p_PP postProvider(new POP3PostProvider(transportLayerProvider));
p_MC mailClient(new MailClient(postProvider));
mailClient->connect(host, port);
if (password != "") {
mailClient->signin(login, password);
}
else {
mailClient->sendLogin(login);
// Enter password if required
if (mailClient->isPasswordRequired()) {
// Bad method, but nothing better was found
char* tmpPassword = getpass("Enter password: ");
mailClient->sendPassword(tmpPassword);
// That method was really bad...but C-like memory design
// is not the worse thing in C++11 code, huh?
free(tmpPassword);
}
}
return mailClient;
}
int getMessagesHeaders (const p_MC& mailClient, ostream& out) {
strings headers = mailClient->getLettersHeaders();
for (auto e : headers) {
out << e << endl;
}
return headers.size();
}
int getCommandLineParameters (int argumentsCount, char* arguments[],
string& host, string& port, string& login, string& password) {
/**
* Prepare command line arguments processing.
*/
options_description description = prepareCommandLineOptions ();
variables_map variablesMap;
try {
variablesMap = parseCommandLine(argumentsCount, arguments, description);
}
catch (const unknown_option& e) {
cerr << "An error occured: " << e.what() << endl;
return EXIT_FAILURE;
}
catch (const invalid_command_line_syntax& e) {
cerr << "An error occured: " << e.what() << endl;
return EXIT_FAILURE;
}
/**
* Display help menu if it was requested.
*/
if (variablesMap.count("help")) {
displayUsage (cerr, description, arguments[0]);
return EXIT_FAILURE;
}
/**
* Process variables.
*/
string server_name;
if (!getParameters(variablesMap, login, password, server_name)) {
cerr << "Not all mandatory parameters were set." << endl
<< "Please, run `" << arguments[0]
<< " --help' for more information." << endl;
return EXIT_FAILURE;
}
parseServerName(server_name, host, port);
return EXIT_SUCCESS;
}
int task (const string& host, const string& port,
const string& login, const string& password) {
p_MC mailClient;
try {
mailClient = mailboxEnter(host, port, login, password);
}
catch (const MailClientException& e) {
cerr << "Error occured when tried to enter the mailbox: "
<< e.what() << endl;
return EXIT_FAILURE;
}
try {
string outputFilename = "letters.txt";
ofstream out(outputFilename);
if (!out.is_open()) {
throw ios_base::failure("Can't open file " +
outputFilename + ".");
}
out.exceptions(std::ofstream::failbit | std::ofstream::badbit);
cout << getMessagesHeaders(mailClient, out) << endl;
out.close();
}
catch (const ios_base::failure& e) {
cerr << "Error occured when application worked with file: "
<< e.what() << endl;
return EXIT_FAILURE;
}
catch (const MailClientException& e) {
cerr << "Mail Client error occured when tried to read messages: "
<< e.what() << endl;
return EXIT_FAILURE;
}
try {
mailClient->signout();
}
catch (const MailClientException& e) {
cerr << "Error occured when tried to sign out from mailbox: "
<< e.what() << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////////////
// Dynamic Audio Normalizer - Audio Processing Library
// Copyright (c) 2014 LoRd_MuldeR <mulder2@gmx.de>. Some rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
// http://www.gnu.org/licenses/lgpl-2.1.txt
//////////////////////////////////////////////////////////////////////////////////
#include "DynamicAudioNormalizer.h"
//StdLib
#include <algorithm>
//JNI
#include <DynamicAudioNormalizer_JDynamicAudioNormalizer.h>
#include <DynamicAudioNormalizer_JDynamicAudioNormalizer_Error.h>
#include <DynamicAudioNormalizer_JDynamicAudioNormalizer_NativeAPI.h>
//PThread
#if defined(_WIN32) && defined(_MT)
#define PTW32_STATIC_LIB 1
#endif
#include <pthread.h>
//Internal
#include <Common.h>
//Globals
static pthread_mutex_t g_javaLock = PTHREAD_MUTEX_INITIALIZER;
static jobject g_javaLoggingHandler = NULL;
static jmethodID g_javaLoggingMethod = NULL;
///////////////////////////////////////////////////////////////////////////////
// Utility Functions
///////////////////////////////////////////////////////////////////////////////
#define JAVA_CHECK_EXCEPTION() do \
{ \
if(env->ExceptionCheck()) \
{ \
env->ExceptionClear(); \
return JNI_FALSE; \
} \
} \
while(0) \
#define JAVA_FIND_CLASS(VAR,NAME) do \
{ \
(VAR) = env->FindClass((NAME)); \
JAVA_CHECK_EXCEPTION(); \
if((VAR) == NULL) return JNI_FALSE; \
} \
while(0)
#define JAVA_GET_METHOD(VAR,CLASS,NAME,ARGS) do \
{ \
(VAR) = env->GetMethodID((CLASS), (NAME), (ARGS)); \
JAVA_CHECK_EXCEPTION(); \
if((VAR) == NULL) return JNI_FALSE; \
} \
while(0)
#define JAVA_MAP_PUT(MAP,KEY,VAL) do \
{ \
jstring _key = env->NewStringUTF((KEY)); \
jstring _val = env->NewStringUTF((VAL)); \
JAVA_CHECK_EXCEPTION(); \
\
if(_key && _val) \
{ \
jobject _ret = env->CallObjectMethod((MAP), putMethod, _key, _val); \
JAVA_CHECK_EXCEPTION(); \
if(_ret) env->DeleteLocalRef(_ret); \
} \
\
if(_key) env->DeleteLocalRef(_key); \
if(_val) env->DeleteLocalRef(_val); \
} \
while(0)
///////////////////////////////////////////////////////////////////////////////
// Logging Function
///////////////////////////////////////////////////////////////////////////////
static jboolean javaSetLoggingHandler(JNIEnv *env, jobject loggerGlobalReference, jmethodID loggerMethod)
{
MY_CRITSEC_ENTER(g_javaLock);
if(g_javaLoggingHandler)
{
env->DeleteGlobalRef(g_javaLoggingHandler);
}
g_javaLoggingMethod = loggerMethod;
g_javaLoggingHandler = loggerGlobalReference;
MY_CRITSEC_LEAVE(g_javaLock);
JAVA_CHECK_EXCEPTION();
return JNI_TRUE;
}
static jboolean javaLogMessage(JNIEnv *env, const int &level, const char *const message)
{
bool success = JNI_FALSE;
MY_CRITSEC_ENTER(g_javaLock);
if(g_javaLoggingHandler && g_javaLoggingMethod)
{
jstring text = env->NewStringUTF(message);
if(text)
{
env->CallVoidMethod(g_javaLoggingHandler, g_javaLoggingMethod, level, text);
env->DeleteLocalRef(text);
success = JNI_TRUE;
}
}
MY_CRITSEC_LEAVE(g_javaLock);
JAVA_CHECK_EXCEPTION();
return success;
}
///////////////////////////////////////////////////////////////////////////////
// JNI Functions
///////////////////////////////////////////////////////////////////////////////
extern "C"
{
JNIEXPORT jboolean JNICALL Java_DynamicAudioNormalizer_JDynamicAudioNormalizer_00024NativeAPI_getVersionInfo(JNIEnv *env, jclass, jintArray versionInfo)
{
if(versionInfo == NULL)
{
return JNI_FALSE;
}
if(env->GetArrayLength(versionInfo) == 3)
{
if(jint *versionInfoElements = env->GetIntArrayElements(versionInfo, JNI_FALSE))
{
uint32_t major, minor, patch;
MDynamicAudioNormalizer::getVersionInfo(major, minor, patch);
versionInfoElements[0] = (int32_t) std::min(major, uint32_t(INT32_MAX));
versionInfoElements[1] = (int32_t) std::min(minor, uint32_t(INT32_MAX));
versionInfoElements[2] = (int32_t) std::min(patch, uint32_t(INT32_MAX));
env->ReleaseIntArrayElements(versionInfo, versionInfoElements, 0);
JAVA_CHECK_EXCEPTION();
return JNI_TRUE;
}
}
JAVA_CHECK_EXCEPTION();
return JNI_FALSE;
}
JNIEXPORT jboolean JNICALL Java_DynamicAudioNormalizer_JDynamicAudioNormalizer_00024NativeAPI_getBuildInfo(JNIEnv *env, jclass, jobject buildInfo)
{
if(buildInfo == NULL)
{
return JNI_FALSE;
}
jclass mapClass = NULL;
jmethodID putMethod = NULL, clearMethod = NULL;
JAVA_FIND_CLASS(mapClass, "java/util/Map");
JAVA_GET_METHOD(putMethod, mapClass, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
JAVA_GET_METHOD(clearMethod, mapClass, "clear", "()V");
if(!env->IsInstanceOf(buildInfo, mapClass))
{
return JNI_FALSE;
}
env->CallVoidMethod(buildInfo, clearMethod);
JAVA_CHECK_EXCEPTION();
const char *date, *time, *compiler, *arch;
bool debug;
MDynamicAudioNormalizer::getBuildInfo(&date, &time, &compiler, &arch, debug);
JAVA_MAP_PUT(buildInfo, "BuildDate", date);
JAVA_MAP_PUT(buildInfo, "BuildTime", time);
JAVA_MAP_PUT(buildInfo, "Compiler", compiler);
JAVA_MAP_PUT(buildInfo, "Architecture", arch);
JAVA_MAP_PUT(buildInfo, "DebugBuild", debug ? "Yes" : "No");
env->DeleteLocalRef(mapClass);
JAVA_CHECK_EXCEPTION();
return JNI_TRUE;
}
JNIEXPORT jboolean JNICALL Java_DynamicAudioNormalizer_JDynamicAudioNormalizer_00024NativeAPI_setLoggingHandler(JNIEnv *env, jclass, jobject loggerObject)
{
if(loggerObject == NULL)
{
return javaSetLoggingHandler(env, NULL, NULL);
}
jclass loggerClass = NULL;
jmethodID logMethod = NULL;
JAVA_FIND_CLASS(loggerClass, "DynamicAudioNormalizer/JDynamicAudioNormalizer$Logger");
JAVA_GET_METHOD(logMethod, loggerClass, "log", "(ILjava/lang/String;)V");
if(!env->IsInstanceOf(loggerObject, loggerClass))
{
return JNI_FALSE;
}
jobject globalReference = env->NewGlobalRef(loggerObject);
JAVA_CHECK_EXCEPTION();
if(globalReference)
{
return javaSetLoggingHandler(env, globalReference, logMethod);
}
JAVA_CHECK_EXCEPTION();
return JNI_FALSE;
}
}
<commit_msg>JNI Wrapper: Some code refactoring.<commit_after>//////////////////////////////////////////////////////////////////////////////////
// Dynamic Audio Normalizer - Audio Processing Library
// Copyright (c) 2014 LoRd_MuldeR <mulder2@gmx.de>. Some rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
// http://www.gnu.org/licenses/lgpl-2.1.txt
//////////////////////////////////////////////////////////////////////////////////
#include "DynamicAudioNormalizer.h"
//StdLib
#include <algorithm>
//JNI
#include <DynamicAudioNormalizer_JDynamicAudioNormalizer.h>
#include <DynamicAudioNormalizer_JDynamicAudioNormalizer_Error.h>
#include <DynamicAudioNormalizer_JDynamicAudioNormalizer_NativeAPI.h>
//PThread
#if defined(_WIN32) && defined(_MT)
#define PTW32_STATIC_LIB 1
#endif
#include <pthread.h>
//Internal
#include <Common.h>
//Globals
static pthread_mutex_t g_javaLock = PTHREAD_MUTEX_INITIALIZER;
static jobject g_javaLoggingHandler = NULL;
static jmethodID g_javaLoggingMethod = NULL;
///////////////////////////////////////////////////////////////////////////////
// Utility Functions
///////////////////////////////////////////////////////////////////////////////
#define JAVA_CHECK_EXCEPTION() do \
{ \
if(env->ExceptionCheck()) \
{ \
env->ExceptionClear(); \
return JNI_FALSE; \
} \
} \
while(0) \
#define JAVA_FIND_CLASS(VAR,NAME) do \
{ \
(VAR) = env->FindClass((NAME)); \
if((VAR) == NULL) return JNI_FALSE; \
} \
while(0)
#define JAVA_GET_METHOD(VAR,CLASS,NAME,ARGS) do \
{ \
(VAR) = env->GetMethodID((CLASS), (NAME), (ARGS)); \
if((VAR) == NULL) return JNI_FALSE; \
} \
while(0)
#define JAVA_MAP_PUT(MAP,KEY,VAL) do \
{ \
jstring _key = env->NewStringUTF((KEY)); \
jstring _val = env->NewStringUTF((VAL)); \
\
if(_key && _val) \
{ \
jobject _ret = env->CallObjectMethod((MAP), putMethod, _key, _val); \
if(_ret) env->DeleteLocalRef(_ret); \
} \
\
if(_key) env->DeleteLocalRef(_key); \
if(_val) env->DeleteLocalRef(_val); \
} \
while(0)
///////////////////////////////////////////////////////////////////////////////
// Logging Function
///////////////////////////////////////////////////////////////////////////////
static void javaSetLoggingHandler(JNIEnv *env, jobject loggerGlobalReference, jmethodID loggerMethod)
{
MY_CRITSEC_ENTER(g_javaLock);
if(g_javaLoggingHandler)
{
env->DeleteGlobalRef(g_javaLoggingHandler);
}
g_javaLoggingMethod = loggerMethod;
g_javaLoggingHandler = loggerGlobalReference;
MY_CRITSEC_LEAVE(g_javaLock);
}
static void javaLogMessage(JNIEnv *env, const int &level, const char *const message)
{
MY_CRITSEC_ENTER(g_javaLock);
if(g_javaLoggingHandler && g_javaLoggingMethod)
{
jstring text = env->NewStringUTF(message);
if(text)
{
env->CallVoidMethod(g_javaLoggingHandler, g_javaLoggingMethod, level, text);
env->DeleteLocalRef(text);
}
}
MY_CRITSEC_LEAVE(g_javaLock);
}
///////////////////////////////////////////////////////////////////////////////
// JNI Functions
///////////////////////////////////////////////////////////////////////////////
static jboolean JNICALL Java_DynamicAudioNormalizer_JDynamicAudioNormalizer_00024NativeAPI_getVersionInfo_Impl(JNIEnv *env, jclass, jintArray versionInfo)
{
if(versionInfo == NULL)
{
return JNI_FALSE;
}
if(env->GetArrayLength(versionInfo) == 3)
{
if(jint *versionInfoElements = env->GetIntArrayElements(versionInfo, JNI_FALSE))
{
uint32_t major, minor, patch;
MDynamicAudioNormalizer::getVersionInfo(major, minor, patch);
versionInfoElements[0] = (int32_t) std::min(major, uint32_t(INT32_MAX));
versionInfoElements[1] = (int32_t) std::min(minor, uint32_t(INT32_MAX));
versionInfoElements[2] = (int32_t) std::min(patch, uint32_t(INT32_MAX));
env->ReleaseIntArrayElements(versionInfo, versionInfoElements, 0);
return JNI_TRUE;
}
}
return JNI_FALSE;
}
static jboolean JNICALL Java_DynamicAudioNormalizer_JDynamicAudioNormalizer_00024NativeAPI_getBuildInfo_Impl(JNIEnv *env, jclass, jobject buildInfo)
{
if(buildInfo == NULL)
{
return JNI_FALSE;
}
jclass mapClass = NULL;
jmethodID putMethod = NULL, clearMethod = NULL;
JAVA_FIND_CLASS(mapClass, "java/util/Map");
JAVA_GET_METHOD(putMethod, mapClass, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
JAVA_GET_METHOD(clearMethod, mapClass, "clear", "()V");
if(!env->IsInstanceOf(buildInfo, mapClass))
{
return JNI_FALSE;
}
env->CallVoidMethod(buildInfo, clearMethod);
const char *date, *time, *compiler, *arch;
bool debug;
MDynamicAudioNormalizer::getBuildInfo(&date, &time, &compiler, &arch, debug);
JAVA_MAP_PUT(buildInfo, "BuildDate", date);
JAVA_MAP_PUT(buildInfo, "BuildTime", time);
JAVA_MAP_PUT(buildInfo, "Compiler", compiler);
JAVA_MAP_PUT(buildInfo, "Architecture", arch);
JAVA_MAP_PUT(buildInfo, "DebugBuild", debug ? "Yes" : "No");
env->DeleteLocalRef(mapClass);
return JNI_TRUE;
}
static jboolean JNICALL Java_DynamicAudioNormalizer_JDynamicAudioNormalizer_00024NativeAPI_setLoggingHandler_Impl(JNIEnv *env, jclass, jobject loggerObject)
{
if(loggerObject == NULL)
{
javaSetLoggingHandler(env, NULL, NULL);
return JNI_TRUE;
}
jclass loggerClass = NULL;
jmethodID logMethod = NULL;
JAVA_FIND_CLASS(loggerClass, "DynamicAudioNormalizer/JDynamicAudioNormalizer$Logger");
JAVA_GET_METHOD(logMethod, loggerClass, "log", "(ILjava/lang/String;)V");
if(!env->IsInstanceOf(loggerObject, loggerClass))
{
return JNI_FALSE;
}
jobject globalReference = env->NewGlobalRef(loggerObject);
if(globalReference)
{
javaSetLoggingHandler(env, globalReference, logMethod);
return JNI_TRUE;
}
return JNI_FALSE;
}
///////////////////////////////////////////////////////////////////////////////
// JNI Entry Points
///////////////////////////////////////////////////////////////////////////////
extern "C"
{
JNIEXPORT jboolean JNICALL Java_DynamicAudioNormalizer_JDynamicAudioNormalizer_00024NativeAPI_getVersionInfo(JNIEnv *env, jclass clazz, jintArray versionInfo)
{
const jboolean ret = Java_DynamicAudioNormalizer_JDynamicAudioNormalizer_00024NativeAPI_getVersionInfo_Impl(env, clazz, versionInfo);
JAVA_CHECK_EXCEPTION();
return ret;
}
JNIEXPORT jboolean JNICALL Java_DynamicAudioNormalizer_JDynamicAudioNormalizer_00024NativeAPI_getBuildInfo(JNIEnv *env, jclass clazz, jobject buildInfo)
{
const jboolean ret = Java_DynamicAudioNormalizer_JDynamicAudioNormalizer_00024NativeAPI_getBuildInfo_Impl(env, clazz, buildInfo);
JAVA_CHECK_EXCEPTION();
return ret;
}
JNIEXPORT jboolean JNICALL Java_DynamicAudioNormalizer_JDynamicAudioNormalizer_00024NativeAPI_setLoggingHandler(JNIEnv *env, jclass clazz, jobject loggerObject)
{
const jboolean ret = Java_DynamicAudioNormalizer_JDynamicAudioNormalizer_00024NativeAPI_setLoggingHandler_Impl(env, clazz, loggerObject);
JAVA_CHECK_EXCEPTION();
return ret;
}
}
<|endoftext|> |
<commit_before>/*!
\copyright (c) RDO-Team, 2011
\file rdo_resource.cpp
\authors Урусов Андрей (rdo@rk9.bmstu.ru)
\authors Лущан Дмитрий (dluschan@rk9.bmstu.ru)
\date 16.04.2008
\brief RDOResource implementation
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/runtime/pch/stdpch.h"
#include "simulator/runtime/rdo_resource.h"
#include "simulator/runtime/rdo_runtime.h"
// --------------------------------------------------------------------------------
OPEN_RDO_RUNTIME_NAMESPACE
// --------------------------------------------------------------------------------
// -------------------- RDOResource
// --------------------------------------------------------------------------------
RDOResource::RDOResource(CREF(LPRDORuntime) pRuntime, CREF(ParamList) paramList, LPIResourceType pResType, ruint resID, ruint typeID, rbool trace, rbool temporary)
: RDORuntimeObject ( )
, RDOTraceableObject (trace, resID, rdo::toString(resID + 1))
, m_temporary (temporary )
, m_state (RDOResource::CS_None )
, m_type (typeID )
, m_referenceCount (0 )
, m_resType (pResType )
, m_db (pRuntime->getDB() )
{
appendParams(paramList.begin(), paramList.end());
}
/// @todo копирующий конструктор не используется - нужен ли он?
RDOResource::RDOResource(CREF(LPRDORuntime) pRuntime, CREF(RDOResource) copy)
: RDORuntimeObject ( )
, RDOTraceableObject (copy.traceable(), copy.getTraceID(), copy.traceId())
, m_paramList (copy.m_paramList )
, m_temporary (copy.m_temporary )
, m_state (copy.m_state )
, m_type (copy.m_type )
, m_referenceCount (0 )
, m_resType (copy.m_resType )
, m_typeId (copy.m_typeId )
{
UNUSED(pRuntime);
appendParams(copy.m_paramList.begin(), copy.m_paramList.end());
/// @todo посмотреть history и принять решение о комментарии
// getRuntime()->incrementResourceIdReference( getTraceID() );
}
RDOResource::~RDOResource()
{}
rbool RDOResource::operator!= (RDOResource &other)
{
if (m_type != other.m_type) return true;
if (m_paramList.size() != other.m_paramList.size()) return true;
int size = m_paramList.size();
for (int i = 0; i < size; ++i)
{
if (m_paramList.at(i) != other.m_paramList.at(i)) return true;
}
return false;
}
LPRDOResource RDOResource::clone(CREF(LPRDORuntime) pRuntime) const
{
LPRDOResource pResource = rdo::Factory<RDOResource>::create(pRuntime, m_paramList, m_resType, getTraceID(), m_type, traceable(), m_temporary);
ASSERT(pResource);
pRuntime->insertNewResource(pResource);
return pResource;
}
tstring RDOResource::getTypeId() const
{
rdo::ostringstream str;
str << m_type;
return str.str();
}
tstring RDOResource::traceParametersValue()
{
rdo::ostringstream str;
if(m_paramList.size() > 0)
{
ParamList::iterator end = m_paramList.end();
for (ParamList::iterator it = m_paramList.begin();;)
{
#ifdef RDOSIM_COMPATIBLE
rdo::ostringstream _str;
_str << *it;
tstring::size_type pos = _str.str().find("e");
if (pos != tstring::npos)
{
tstring __str = _str.str();
__str.erase(pos + 2, 1);
str << __str.c_str();
}
else
{
str << _str.str().c_str();
}
#else
str << *it;
#endif
if (++it == end)
break;
str << " ";
}
}
return str.str();
}
tstring RDOResource::traceResourceState(char prefix, CREF(LPRDORuntime) pRuntime)
{
rdo::ostringstream res;
if (traceable() || (prefix != '\0'))
{
if (m_state == RDOResource::CS_NoChange || m_state == RDOResource::CS_NonExist)
return "";
if (prefix != '\0')
res << prefix;
switch (m_state)
{
case RDOResource::CS_Create:
res << "RC ";
break;
case RDOResource::CS_Erase:
res << "RE "
#ifdef RDOSIM_COMPATIBLE
<< pRuntime->getCurrentTime() << " "
<< traceTypeId() << " "
<< traceId() << std::endl;
return res.str();
#else
;
#endif
break;
default:
res << "RK ";
break;
}
res << pRuntime->getCurrentTime() << " "
<< traceTypeId() << " "
<< traceId() << " "
<< traceParametersValue() << std::endl;
}
return res.str();
}
void RDOResource::setParam(ruint index, CREF(RDOValue) value)
{
QSqlQuery query;
query.exec(QString("select value from rss_param where rss_id=%1 and id=%2;")
.arg(getTraceID())
.arg(index));
query.next();
int value_id = query.value(query.record().indexOf("value")).toInt();
query.exec(QString("select relname from pg_class, rdo_value where pg_class.relfilenode=rdo_value.table_id and rdo_value.value_id=%1;")
.arg(value_id));
query.next();
QString table_name = query.value(query.record().indexOf("relname")).toString();
#define DEFINE_RDO_VALUE(Value) \
m_db->queryExec(QString("update %1 set vv=%2 where id=%3")\
.arg(table_name) \
.arg(Value) \
.arg(value_id));
switch (value.typeID())
{
case RDOType::t_unknow : break;
case RDOType::t_int : DEFINE_RDO_VALUE( value.getInt () ); break;
case RDOType::t_real : DEFINE_RDO_VALUE( value.getDouble () ); break;
case RDOType::t_enum : DEFINE_RDO_VALUE(QString("'%1'").arg(QString::fromStdString(value.getAsString()))); break;
case RDOType::t_bool : DEFINE_RDO_VALUE(QString("'%1'").arg(QString::fromStdString(value.getAsString()))); break;
case RDOType::t_string : DEFINE_RDO_VALUE(QString("'%1'").arg(QString::fromStdString(value.getString ()))); break;
case RDOType::t_identificator : DEFINE_RDO_VALUE(QString("'%1'").arg(QString::fromStdString(value.getAsString()))); break;
default : throw RDOValueException("Данная величина не может быть записана в базу данных");
}
ASSERT(index < m_paramList.size());
setState(CS_Keep);
m_paramList[index] = value;
}
CREF(RDOValue) RDOResource::getParam(ruint index)
{
ASSERT(index < m_paramList.size());
QSqlQuery query;
int traceID = getTraceID();
query.exec(QString("select value from rss_param where rss_id=%1 and id=%2;")
.arg(traceID)
.arg(index));
query.next();
int value_id = query.value(query.record().indexOf("value")).toInt();
query.exec(QString("select relname from pg_class, rdo_value where pg_class.relfilenode=rdo_value.table_id and rdo_value.value_id=%1;")
.arg(value_id));
query.next();
QString table_name = query.value(query.record().indexOf("relname")).toString();
query.exec(QString("select vv from %1 where id=%2;")
.arg(table_name)
.arg(value_id));
query.next();
QVariant varValue = query.value(query.record().indexOf("vv"));
if (table_name == QString("int_rv"))
{
int varValueInt = varValue.toInt();
if (varValueInt != m_paramList[index].getInt())
{
m_paramList[index] = RDOValue(varValueInt);
}
}
else if (table_name == QString("real_rv"))
{
double varValueDouble = varValue.toDouble();
if (varValueDouble != m_paramList[index].getDouble())
{
m_paramList[index] = RDOValue(varValueDouble);
}
}
else if (table_name == QString("enum_rv"))
{
tstring varValueEnum = varValue.toString().toStdString();
if (varValueEnum != m_paramList[index].getAsString())
{
m_paramList[index] = RDOValue(m_paramList[index].type().object_static_cast<RDOEnumType>(),varValueEnum);
}
}
else if (table_name == QString("bool_rv"))
{
bool varValueBool = varValue.toBool();
if (varValueBool != m_paramList[index].getBool())
{
m_paramList[index] = RDOValue(varValueBool);
}
}
else if (table_name == QString("string_rv"))
{
tstring varValueString = varValue.toString().toStdString();
if (varValueString != m_paramList[index].getString())
{
m_paramList[index] = RDOValue(varValueString);
}
}
else if (table_name == QString("identificator_rv"))
{
tstring varValueIdentificator = varValue.toString().toStdString();
if (varValueIdentificator != m_paramList[index].getIdentificator())
{
m_paramList[index] = RDOValue(varValueIdentificator);
}
}
return m_paramList[index];
}
CLOSE_RDO_RUNTIME_NAMESPACE
<commit_msg> - перенос pch в правильное место<commit_after>/*!
\copyright (c) RDO-Team, 2011
\file rdo_resource.cpp
\authors Урусов Андрей (rdo@rk9.bmstu.ru)
\authors Лущан Дмитрий (dluschan@rk9.bmstu.ru)
\date 16.04.2008
\brief RDOResource implementation
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
#include "simulator/runtime/pch/stdpch.h"
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/runtime/rdo_resource.h"
#include "simulator/runtime/rdo_runtime.h"
// --------------------------------------------------------------------------------
OPEN_RDO_RUNTIME_NAMESPACE
// --------------------------------------------------------------------------------
// -------------------- RDOResource
// --------------------------------------------------------------------------------
RDOResource::RDOResource(CREF(LPRDORuntime) pRuntime, CREF(ParamList) paramList, LPIResourceType pResType, ruint resID, ruint typeID, rbool trace, rbool temporary)
: RDORuntimeObject ( )
, RDOTraceableObject (trace, resID, rdo::toString(resID + 1))
, m_temporary (temporary )
, m_state (RDOResource::CS_None )
, m_type (typeID )
, m_referenceCount (0 )
, m_resType (pResType )
, m_db (pRuntime->getDB() )
{
appendParams(paramList.begin(), paramList.end());
}
/// @todo копирующий конструктор не используется - нужен ли он?
RDOResource::RDOResource(CREF(LPRDORuntime) pRuntime, CREF(RDOResource) copy)
: RDORuntimeObject ( )
, RDOTraceableObject (copy.traceable(), copy.getTraceID(), copy.traceId())
, m_paramList (copy.m_paramList )
, m_temporary (copy.m_temporary )
, m_state (copy.m_state )
, m_type (copy.m_type )
, m_referenceCount (0 )
, m_resType (copy.m_resType )
, m_typeId (copy.m_typeId )
{
UNUSED(pRuntime);
appendParams(copy.m_paramList.begin(), copy.m_paramList.end());
/// @todo посмотреть history и принять решение о комментарии
// getRuntime()->incrementResourceIdReference( getTraceID() );
}
RDOResource::~RDOResource()
{}
rbool RDOResource::operator!= (RDOResource &other)
{
if (m_type != other.m_type) return true;
if (m_paramList.size() != other.m_paramList.size()) return true;
int size = m_paramList.size();
for (int i = 0; i < size; ++i)
{
if (m_paramList.at(i) != other.m_paramList.at(i)) return true;
}
return false;
}
LPRDOResource RDOResource::clone(CREF(LPRDORuntime) pRuntime) const
{
LPRDOResource pResource = rdo::Factory<RDOResource>::create(pRuntime, m_paramList, m_resType, getTraceID(), m_type, traceable(), m_temporary);
ASSERT(pResource);
pRuntime->insertNewResource(pResource);
return pResource;
}
tstring RDOResource::getTypeId() const
{
rdo::ostringstream str;
str << m_type;
return str.str();
}
tstring RDOResource::traceParametersValue()
{
rdo::ostringstream str;
if(m_paramList.size() > 0)
{
ParamList::iterator end = m_paramList.end();
for (ParamList::iterator it = m_paramList.begin();;)
{
#ifdef RDOSIM_COMPATIBLE
rdo::ostringstream _str;
_str << *it;
tstring::size_type pos = _str.str().find("e");
if (pos != tstring::npos)
{
tstring __str = _str.str();
__str.erase(pos + 2, 1);
str << __str.c_str();
}
else
{
str << _str.str().c_str();
}
#else
str << *it;
#endif
if (++it == end)
break;
str << " ";
}
}
return str.str();
}
tstring RDOResource::traceResourceState(char prefix, CREF(LPRDORuntime) pRuntime)
{
rdo::ostringstream res;
if (traceable() || (prefix != '\0'))
{
if (m_state == RDOResource::CS_NoChange || m_state == RDOResource::CS_NonExist)
return "";
if (prefix != '\0')
res << prefix;
switch (m_state)
{
case RDOResource::CS_Create:
res << "RC ";
break;
case RDOResource::CS_Erase:
res << "RE "
#ifdef RDOSIM_COMPATIBLE
<< pRuntime->getCurrentTime() << " "
<< traceTypeId() << " "
<< traceId() << std::endl;
return res.str();
#else
;
#endif
break;
default:
res << "RK ";
break;
}
res << pRuntime->getCurrentTime() << " "
<< traceTypeId() << " "
<< traceId() << " "
<< traceParametersValue() << std::endl;
}
return res.str();
}
void RDOResource::setParam(ruint index, CREF(RDOValue) value)
{
QSqlQuery query;
query.exec(QString("select value from rss_param where rss_id=%1 and id=%2;")
.arg(getTraceID())
.arg(index));
query.next();
int value_id = query.value(query.record().indexOf("value")).toInt();
query.exec(QString("select relname from pg_class, rdo_value where pg_class.relfilenode=rdo_value.table_id and rdo_value.value_id=%1;")
.arg(value_id));
query.next();
QString table_name = query.value(query.record().indexOf("relname")).toString();
#define DEFINE_RDO_VALUE(Value) \
m_db->queryExec(QString("update %1 set vv=%2 where id=%3")\
.arg(table_name) \
.arg(Value) \
.arg(value_id));
switch (value.typeID())
{
case RDOType::t_unknow : break;
case RDOType::t_int : DEFINE_RDO_VALUE( value.getInt () ); break;
case RDOType::t_real : DEFINE_RDO_VALUE( value.getDouble () ); break;
case RDOType::t_enum : DEFINE_RDO_VALUE(QString("'%1'").arg(QString::fromStdString(value.getAsString()))); break;
case RDOType::t_bool : DEFINE_RDO_VALUE(QString("'%1'").arg(QString::fromStdString(value.getAsString()))); break;
case RDOType::t_string : DEFINE_RDO_VALUE(QString("'%1'").arg(QString::fromStdString(value.getString ()))); break;
case RDOType::t_identificator : DEFINE_RDO_VALUE(QString("'%1'").arg(QString::fromStdString(value.getAsString()))); break;
default : throw RDOValueException("Данная величина не может быть записана в базу данных");
}
ASSERT(index < m_paramList.size());
setState(CS_Keep);
m_paramList[index] = value;
}
CREF(RDOValue) RDOResource::getParam(ruint index)
{
ASSERT(index < m_paramList.size());
QSqlQuery query;
int traceID = getTraceID();
query.exec(QString("select value from rss_param where rss_id=%1 and id=%2;")
.arg(traceID)
.arg(index));
query.next();
int value_id = query.value(query.record().indexOf("value")).toInt();
query.exec(QString("select relname from pg_class, rdo_value where pg_class.relfilenode=rdo_value.table_id and rdo_value.value_id=%1;")
.arg(value_id));
query.next();
QString table_name = query.value(query.record().indexOf("relname")).toString();
query.exec(QString("select vv from %1 where id=%2;")
.arg(table_name)
.arg(value_id));
query.next();
QVariant varValue = query.value(query.record().indexOf("vv"));
if (table_name == QString("int_rv"))
{
int varValueInt = varValue.toInt();
if (varValueInt != m_paramList[index].getInt())
{
m_paramList[index] = RDOValue(varValueInt);
}
}
else if (table_name == QString("real_rv"))
{
double varValueDouble = varValue.toDouble();
if (varValueDouble != m_paramList[index].getDouble())
{
m_paramList[index] = RDOValue(varValueDouble);
}
}
else if (table_name == QString("enum_rv"))
{
tstring varValueEnum = varValue.toString().toStdString();
if (varValueEnum != m_paramList[index].getAsString())
{
m_paramList[index] = RDOValue(m_paramList[index].type().object_static_cast<RDOEnumType>(),varValueEnum);
}
}
else if (table_name == QString("bool_rv"))
{
bool varValueBool = varValue.toBool();
if (varValueBool != m_paramList[index].getBool())
{
m_paramList[index] = RDOValue(varValueBool);
}
}
else if (table_name == QString("string_rv"))
{
tstring varValueString = varValue.toString().toStdString();
if (varValueString != m_paramList[index].getString())
{
m_paramList[index] = RDOValue(varValueString);
}
}
else if (table_name == QString("identificator_rv"))
{
tstring varValueIdentificator = varValue.toString().toStdString();
if (varValueIdentificator != m_paramList[index].getIdentificator())
{
m_paramList[index] = RDOValue(varValueIdentificator);
}
}
return m_paramList[index];
}
CLOSE_RDO_RUNTIME_NAMESPACE
<|endoftext|> |
<commit_before><commit_msg>Fix for Root v6-26 (#1431)<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (C) 2006, 2007, 2008, 2009, 2010 Stephen F. Booth <me@sbooth.org>
* 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 Stephen F. Booth 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 <taglib/mpegfile.h>
#include <taglib/mpegproperties.h>
#include <taglib/xingheader.h>
#include "AudioEngineDefines.h"
#include "MP3Metadata.h"
#include "CreateDisplayNameForURL.h"
#include "AddID3v2TagToDictionary.h"
#include "SetID3v2TagFromMetadata.h"
#include "AddAudioPropertiesToDictionary.h"
#pragma mark Static Methods
CFArrayRef MP3Metadata::CreateSupportedFileExtensions()
{
CFStringRef supportedExtensions [] = { CFSTR("mp3") };
return CFArrayCreate(kCFAllocatorDefault, reinterpret_cast<const void **>(supportedExtensions), 1, &kCFTypeArrayCallBacks);
}
CFArrayRef MP3Metadata::CreateSupportedMIMETypes()
{
CFStringRef supportedMIMETypes [] = { CFSTR("audio/mpeg") };
return CFArrayCreate(kCFAllocatorDefault, reinterpret_cast<const void **>(supportedMIMETypes), 1, &kCFTypeArrayCallBacks);
}
bool MP3Metadata::HandlesFilesWithExtension(CFStringRef extension)
{
assert(NULL != extension);
if(kCFCompareEqualTo == CFStringCompare(extension, CFSTR("mp3"), kCFCompareCaseInsensitive))
return true;
return false;
}
bool MP3Metadata::HandlesMIMEType(CFStringRef mimeType)
{
assert(NULL != mimeType);
if(kCFCompareEqualTo == CFStringCompare(mimeType, CFSTR("audio/mpeg"), kCFCompareCaseInsensitive))
return true;
return false;
}
#pragma mark Creation and Destruction
MP3Metadata::MP3Metadata(CFURLRef url)
: AudioMetadata(url)
{}
MP3Metadata::~MP3Metadata()
{}
#pragma mark Functionality
bool MP3Metadata::ReadMetadata(CFErrorRef *error)
{
// Start from scratch
CFDictionaryRemoveAllValues(mMetadata);
CFDictionaryRemoveAllValues(mChangedMetadata);
UInt8 buf [PATH_MAX];
if(false == CFURLGetFileSystemRepresentation(mURL, false, buf, PATH_MAX))
return false;
TagLib::MPEG::File file(reinterpret_cast<const char *>(buf), TagLib::ID3v2::FrameFactory::instance());
if(!file.isValid()) {
if(NULL != error) {
CFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault,
32,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
CFStringRef displayName = CreateDisplayNameForURL(mURL);
CFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault,
NULL,
CFCopyLocalizedString(CFSTR("The file “%@” is not a valid MPEG file."), ""),
displayName);
CFDictionarySetValue(errorDictionary,
kCFErrorLocalizedDescriptionKey,
errorString);
CFDictionarySetValue(errorDictionary,
kCFErrorLocalizedFailureReasonKey,
CFCopyLocalizedString(CFSTR("Not a MPEG file"), ""));
CFDictionarySetValue(errorDictionary,
kCFErrorLocalizedRecoverySuggestionKey,
CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), ""));
CFRelease(errorString), errorString = NULL;
CFRelease(displayName), displayName = NULL;
*error = CFErrorCreate(kCFAllocatorDefault,
AudioMetadataErrorDomain,
AudioMetadataInputOutputError,
errorDictionary);
CFRelease(errorDictionary), errorDictionary = NULL;
}
return false;
}
CFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR("MP3"));
if(file.audioProperties()) {
TagLib::MPEG::Properties *properties = file.audioProperties();
AddAudioPropertiesToDictionary(mMetadata, properties);
if(properties->xingHeader() && properties->xingHeader()->totalFrames()) {
TagLib::uint frames = properties->xingHeader()->totalFrames();
CFNumberRef totalFrames = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &frames);
CFDictionaryAddValue(mMetadata, kPropertiesTotalFramesKey, totalFrames);
CFRelease(totalFrames), totalFrames = NULL;
}
}
// TODO: ID3v1 ??
if(file.ID3v2Tag())
AddID3v2TagToDictionary(mMetadata, file.ID3v2Tag());
return true;
}
bool MP3Metadata::WriteMetadata(CFErrorRef *error)
{
UInt8 buf [PATH_MAX];
if(false == CFURLGetFileSystemRepresentation(mURL, false, buf, PATH_MAX))
return false;
TagLib::MPEG::File file(reinterpret_cast<const char *>(buf), false);
if(!file.isValid()) {
if(error) {
CFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault,
32,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
CFStringRef displayName = CreateDisplayNameForURL(mURL);
CFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault,
NULL,
CFCopyLocalizedString(CFSTR("The file “%@” is not a valid MPEG file."), ""),
displayName);
CFDictionarySetValue(errorDictionary,
kCFErrorLocalizedDescriptionKey,
errorString);
CFDictionarySetValue(errorDictionary,
kCFErrorLocalizedFailureReasonKey,
CFCopyLocalizedString(CFSTR("Not a MPEG file"), ""));
CFDictionarySetValue(errorDictionary,
kCFErrorLocalizedRecoverySuggestionKey,
CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), ""));
CFRelease(errorString), errorString = NULL;
CFRelease(displayName), displayName = NULL;
*error = CFErrorCreate(kCFAllocatorDefault,
AudioMetadataErrorDomain,
AudioMetadataInputOutputError,
errorDictionary);
CFRelease(errorDictionary), errorDictionary = NULL;
}
return false;
}
SetID3v2TagFromMetadata(this, file.ID3v2Tag(true));
if(!file.save()) {
if(error) {
CFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault,
32,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
CFStringRef displayName = CreateDisplayNameForURL(mURL);
CFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault,
NULL,
CFCopyLocalizedString(CFSTR("The file “%@” is not a valid MPEG file."), ""),
displayName);
CFDictionarySetValue(errorDictionary,
kCFErrorLocalizedDescriptionKey,
errorString);
CFDictionarySetValue(errorDictionary,
kCFErrorLocalizedFailureReasonKey,
CFCopyLocalizedString(CFSTR("Unable to write metadata"), ""));
CFDictionarySetValue(errorDictionary,
kCFErrorLocalizedRecoverySuggestionKey,
CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), ""));
CFRelease(errorString), errorString = NULL;
CFRelease(displayName), displayName = NULL;
*error = CFErrorCreate(kCFAllocatorDefault,
AudioMetadataErrorDomain,
AudioMetadataInputOutputError,
errorDictionary);
CFRelease(errorDictionary), errorDictionary = NULL;
}
return false;
}
MergeChangedMetadataIntoMetadata();
return true;
}
<commit_msg>Added optional MP3 layer information<commit_after>/*
* Copyright (C) 2006, 2007, 2008, 2009, 2010 Stephen F. Booth <me@sbooth.org>
* 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 Stephen F. Booth 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 <taglib/mpegfile.h>
#include <taglib/mpegproperties.h>
#include <taglib/xingheader.h>
#include "AudioEngineDefines.h"
#include "MP3Metadata.h"
#include "CreateDisplayNameForURL.h"
#include "AddID3v2TagToDictionary.h"
#include "SetID3v2TagFromMetadata.h"
#include "AddAudioPropertiesToDictionary.h"
#pragma mark Static Methods
CFArrayRef MP3Metadata::CreateSupportedFileExtensions()
{
CFStringRef supportedExtensions [] = { CFSTR("mp3") };
return CFArrayCreate(kCFAllocatorDefault, reinterpret_cast<const void **>(supportedExtensions), 1, &kCFTypeArrayCallBacks);
}
CFArrayRef MP3Metadata::CreateSupportedMIMETypes()
{
CFStringRef supportedMIMETypes [] = { CFSTR("audio/mpeg") };
return CFArrayCreate(kCFAllocatorDefault, reinterpret_cast<const void **>(supportedMIMETypes), 1, &kCFTypeArrayCallBacks);
}
bool MP3Metadata::HandlesFilesWithExtension(CFStringRef extension)
{
assert(NULL != extension);
if(kCFCompareEqualTo == CFStringCompare(extension, CFSTR("mp3"), kCFCompareCaseInsensitive))
return true;
return false;
}
bool MP3Metadata::HandlesMIMEType(CFStringRef mimeType)
{
assert(NULL != mimeType);
if(kCFCompareEqualTo == CFStringCompare(mimeType, CFSTR("audio/mpeg"), kCFCompareCaseInsensitive))
return true;
return false;
}
#pragma mark Creation and Destruction
MP3Metadata::MP3Metadata(CFURLRef url)
: AudioMetadata(url)
{}
MP3Metadata::~MP3Metadata()
{}
#pragma mark Functionality
bool MP3Metadata::ReadMetadata(CFErrorRef *error)
{
// Start from scratch
CFDictionaryRemoveAllValues(mMetadata);
CFDictionaryRemoveAllValues(mChangedMetadata);
UInt8 buf [PATH_MAX];
if(false == CFURLGetFileSystemRepresentation(mURL, false, buf, PATH_MAX))
return false;
TagLib::MPEG::File file(reinterpret_cast<const char *>(buf), TagLib::ID3v2::FrameFactory::instance());
if(!file.isValid()) {
if(NULL != error) {
CFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault,
32,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
CFStringRef displayName = CreateDisplayNameForURL(mURL);
CFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault,
NULL,
CFCopyLocalizedString(CFSTR("The file “%@” is not a valid MPEG file."), ""),
displayName);
CFDictionarySetValue(errorDictionary,
kCFErrorLocalizedDescriptionKey,
errorString);
CFDictionarySetValue(errorDictionary,
kCFErrorLocalizedFailureReasonKey,
CFCopyLocalizedString(CFSTR("Not a MPEG file"), ""));
CFDictionarySetValue(errorDictionary,
kCFErrorLocalizedRecoverySuggestionKey,
CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), ""));
CFRelease(errorString), errorString = NULL;
CFRelease(displayName), displayName = NULL;
*error = CFErrorCreate(kCFAllocatorDefault,
AudioMetadataErrorDomain,
AudioMetadataInputOutputError,
errorDictionary);
CFRelease(errorDictionary), errorDictionary = NULL;
}
return false;
}
CFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR("MP3"));
if(file.audioProperties()) {
TagLib::MPEG::Properties *properties = file.audioProperties();
AddAudioPropertiesToDictionary(mMetadata, properties);
// TODO: Is this too much information?
#if 0
switch(properties->version()) {
case TagLib::MPEG::Header::Version1:
switch(properties->layer()) {
case 1: CFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR("MPEG-1 Layer I")); break;
case 2: CFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR("MPEG-1 Layer II")); break;
case 3: CFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR("MPEG-1 Layer III")); break;
}
break;
case TagLib::MPEG::Header::Version2:
switch(properties->layer()) {
case 1: CFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR("MPEG-2 Layer I")); break;
case 2: CFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR("MPEG-2 Layer II")); break;
case 3: CFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR("MPEG-2 Layer III")); break;
}
break;
case TagLib::MPEG::Header::Version2_5:
switch(properties->layer()) {
case 1: CFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR("MPEG-2.5 Layer I")); break;
case 2: CFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR("MPEG-2.5 Layer II")); break;
case 3: CFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR("MPEG-2.5 Layer III")); break;
}
break;
}
#endif
if(properties->xingHeader() && properties->xingHeader()->totalFrames()) {
TagLib::uint frames = properties->xingHeader()->totalFrames();
CFNumberRef totalFrames = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &frames);
CFDictionaryAddValue(mMetadata, kPropertiesTotalFramesKey, totalFrames);
CFRelease(totalFrames), totalFrames = NULL;
}
}
// TODO: ID3v1 ??
if(file.ID3v2Tag())
AddID3v2TagToDictionary(mMetadata, file.ID3v2Tag());
return true;
}
bool MP3Metadata::WriteMetadata(CFErrorRef *error)
{
UInt8 buf [PATH_MAX];
if(false == CFURLGetFileSystemRepresentation(mURL, false, buf, PATH_MAX))
return false;
TagLib::MPEG::File file(reinterpret_cast<const char *>(buf), false);
if(!file.isValid()) {
if(error) {
CFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault,
32,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
CFStringRef displayName = CreateDisplayNameForURL(mURL);
CFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault,
NULL,
CFCopyLocalizedString(CFSTR("The file “%@” is not a valid MPEG file."), ""),
displayName);
CFDictionarySetValue(errorDictionary,
kCFErrorLocalizedDescriptionKey,
errorString);
CFDictionarySetValue(errorDictionary,
kCFErrorLocalizedFailureReasonKey,
CFCopyLocalizedString(CFSTR("Not a MPEG file"), ""));
CFDictionarySetValue(errorDictionary,
kCFErrorLocalizedRecoverySuggestionKey,
CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), ""));
CFRelease(errorString), errorString = NULL;
CFRelease(displayName), displayName = NULL;
*error = CFErrorCreate(kCFAllocatorDefault,
AudioMetadataErrorDomain,
AudioMetadataInputOutputError,
errorDictionary);
CFRelease(errorDictionary), errorDictionary = NULL;
}
return false;
}
SetID3v2TagFromMetadata(this, file.ID3v2Tag(true));
if(!file.save()) {
if(error) {
CFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault,
32,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
CFStringRef displayName = CreateDisplayNameForURL(mURL);
CFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault,
NULL,
CFCopyLocalizedString(CFSTR("The file “%@” is not a valid MPEG file."), ""),
displayName);
CFDictionarySetValue(errorDictionary,
kCFErrorLocalizedDescriptionKey,
errorString);
CFDictionarySetValue(errorDictionary,
kCFErrorLocalizedFailureReasonKey,
CFCopyLocalizedString(CFSTR("Unable to write metadata"), ""));
CFDictionarySetValue(errorDictionary,
kCFErrorLocalizedRecoverySuggestionKey,
CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), ""));
CFRelease(errorString), errorString = NULL;
CFRelease(displayName), displayName = NULL;
*error = CFErrorCreate(kCFAllocatorDefault,
AudioMetadataErrorDomain,
AudioMetadataInputOutputError,
errorDictionary);
CFRelease(errorDictionary), errorDictionary = NULL;
}
return false;
}
MergeChangedMetadataIntoMetadata();
return true;
}
<|endoftext|> |
<commit_before>#include "Application.hpp"
#include "InputHandlers.hpp"
#include "renderer/RenderContext.hpp"
#include "renderer/ShaderManager.hpp"
#include "renderer/OculusVR.hpp"
#include "renderer/CameraDirector.hpp"
// application globals
extern CameraDirector g_cameraDirector;
RenderContext g_renderContext;
Application g_application;
OculusVR g_oculusVR;
int main(int argc, char **argv)
{
// initialize everything
if( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_EVENTS ) < 0 )
{
return 1;
}
if (!g_oculusVR.InitVR())
{
SDL_Quit();
return 1;
}
ovrSizei hmdResolution = g_oculusVR.GetResolution();
ovrSizei windowSize = { hmdResolution.w / 2, hmdResolution.h / 2 };
g_renderContext.Init("Oculus Rift Minimum OpenGL", 100, 100, windowSize.w, windowSize.h);
SDL_ShowCursor(SDL_DISABLE);
if (glewInit() != GLEW_OK)
{
g_oculusVR.DestroyVR();
g_renderContext.Destroy();
SDL_Quit();
return 1;
}
if (!g_oculusVR.InitVRBuffers(windowSize.w, windowSize.h))
{
g_oculusVR.DestroyVR();
g_renderContext.Destroy();
SDL_Quit();
return 1;
}
if (!g_oculusVR.InitNonDistortMirror(windowSize.w, windowSize.h))
{
g_oculusVR.DestroyVR();
g_renderContext.Destroy();
SDL_Quit();
return 1;
}
ShaderManager::GetInstance()->LoadShaders();
g_application.OnStart();
while (g_application.Running())
{
// handle key presses
processEvents();
glClearColor(0.2f, 0.2f, 0.6f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
g_oculusVR.OnRenderStart();
for (int eyeIndex = 0; eyeIndex < ovrEye_Count; eyeIndex++)
{
OVR::Matrix4f MVPMatrix = g_oculusVR.OnEyeRender(eyeIndex);
// update MVP in quad shader
const ShaderProgram &shader = ShaderManager::GetInstance()->UseShaderProgram(ShaderManager::BasicShader);
glUniformMatrix4fv(shader.uniforms[ModelViewProjectionMatrix], 1, GL_FALSE, &MVPMatrix.Transposed().M[0][0]);
g_application.OnRender();
g_oculusVR.OnEyeRenderFinish(eyeIndex);
}
g_oculusVR.SubmitFrame();
Application::VRMirrorMode mirrorMode = g_application.CurrMirrorMode();
// Standard mirror blit (both eyes, distorted)
if (mirrorMode == Application::Mirror_Regular)
{
ClearWindow(0.f, 0.f, 0.f);
g_oculusVR.BlitMirror(ovrEye_Count, 0);
}
// Standard mirror blit (left eye, distorted)
if (mirrorMode == Application::Mirror_RegularLeftEye)
{
ClearWindow(0.f, 0.f, 0.f);
g_oculusVR.BlitMirror(ovrEye_Left, windowSize.w / 4);
// rectangle indicating we're rendering left eye
ShaderManager::GetInstance()->DisableShader();
glViewport(0, 0, windowSize.w, windowSize.h);
DrawRectangle(-0.75f, 0.f, 0.1f, 0.1f, 0.f, 1.f, 0.f);
}
// Standard mirror blit (right eye, distorted)
if (mirrorMode == Application::Mirror_RegularRightEye)
{
ClearWindow(0.f, 0.f, 0.f);
g_oculusVR.BlitMirror(ovrEye_Right, windowSize.w / 4);
// rectangle indicating we're rendering right eye
ShaderManager::GetInstance()->DisableShader();
glViewport(0, 0, windowSize.w, windowSize.h);
DrawRectangle(0.75f, 0.f, 0.1f, 0.1f, 0.f, 1.f, 0.f);
}
// Both eye mirror - no distortion (requires 2 extra renders!)
if (mirrorMode == Application::Mirror_NonDistort)
{
g_oculusVR.OnNonDistortMirrorStart();
for (int eyeIndex = 0; eyeIndex < ovrEye_Count; eyeIndex++)
{
const OVR::Matrix4f MVPMatrix = g_oculusVR.GetEyeMVPMatrix(eyeIndex);
const ShaderProgram &shader = ShaderManager::GetInstance()->UseShaderProgram(ShaderManager::BasicShader);
glUniformMatrix4fv(shader.uniforms[ModelViewProjectionMatrix], 1, GL_FALSE, &MVPMatrix.Transposed().M[0][0]);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(0.2f, 0.2f, 0.6f, 0.0f);
g_application.OnRender();
g_oculusVR.BlitNonDistortMirror(eyeIndex == 0 ? 0 : windowSize.w / 2);
}
}
// Left eye - no distortion (1 extra render)
if (mirrorMode == Application::Mirror_NonDistortLeftEye)
{
ClearWindow(0.f, 0.f, 0.f);
g_oculusVR.OnNonDistortMirrorStart();
const OVR::Matrix4f MVPMatrix = g_oculusVR.GetEyeMVPMatrix(ovrEye_Left);
const ShaderProgram &shader = ShaderManager::GetInstance()->UseShaderProgram(ShaderManager::BasicShader);
glUniformMatrix4fv(shader.uniforms[ModelViewProjectionMatrix], 1, GL_FALSE, &MVPMatrix.Transposed().M[0][0]);
glClearColor(0.2f, 0.2f, 0.6f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
g_application.OnRender();
g_oculusVR.BlitNonDistortMirror(windowSize.w / 4);
ShaderManager::GetInstance()->DisableShader();
glViewport(0, 0, windowSize.w, windowSize.h);
DrawRectangle(-0.75f, 0.f, 0.1f, 0.1f, 0.f, 1.f, 0.f);
}
// Right eye - no distortion (1 extra render)
if (mirrorMode == Application::Mirror_NonDistortRightEye)
{
ClearWindow(0.f, 0.f, 0.f);
g_oculusVR.OnNonDistortMirrorStart();
const OVR::Matrix4f MVPMatrix = g_oculusVR.GetEyeMVPMatrix(ovrEye_Right);
const ShaderProgram &shader = ShaderManager::GetInstance()->UseShaderProgram(ShaderManager::BasicShader);
glUniformMatrix4fv(shader.uniforms[ModelViewProjectionMatrix], 1, GL_FALSE, &MVPMatrix.Transposed().M[0][0]);
glClearColor(0.2f, 0.2f, 0.6f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
g_application.OnRender();
g_oculusVR.BlitNonDistortMirror(windowSize.w / 4);
ShaderManager::GetInstance()->DisableShader();
glViewport(0, 0, windowSize.w, windowSize.h);
DrawRectangle(0.75f, 0.f, 0.1f, 0.1f, 0.f, 1.f, 0.f);
}
SDL_GL_SwapWindow(g_renderContext.window);
}
g_oculusVR.DestroyVR();
g_renderContext.Destroy();
SDL_Quit();
return 0;
}<commit_msg>updated title<commit_after>#include "Application.hpp"
#include "InputHandlers.hpp"
#include "renderer/RenderContext.hpp"
#include "renderer/ShaderManager.hpp"
#include "renderer/OculusVR.hpp"
#include "renderer/CameraDirector.hpp"
// application globals
extern CameraDirector g_cameraDirector;
RenderContext g_renderContext;
Application g_application;
OculusVR g_oculusVR;
int main(int argc, char **argv)
{
// initialize everything
if( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_EVENTS ) < 0 )
{
return 1;
}
if (!g_oculusVR.InitVR())
{
SDL_Quit();
return 1;
}
ovrSizei hmdResolution = g_oculusVR.GetResolution();
ovrSizei windowSize = { hmdResolution.w / 2, hmdResolution.h / 2 };
g_renderContext.Init("Oculus Rift mirror modes (press M to cycle)", 100, 100, windowSize.w, windowSize.h);
SDL_ShowCursor(SDL_DISABLE);
if (glewInit() != GLEW_OK)
{
g_oculusVR.DestroyVR();
g_renderContext.Destroy();
SDL_Quit();
return 1;
}
if (!g_oculusVR.InitVRBuffers(windowSize.w, windowSize.h))
{
g_oculusVR.DestroyVR();
g_renderContext.Destroy();
SDL_Quit();
return 1;
}
if (!g_oculusVR.InitNonDistortMirror(windowSize.w, windowSize.h))
{
g_oculusVR.DestroyVR();
g_renderContext.Destroy();
SDL_Quit();
return 1;
}
ShaderManager::GetInstance()->LoadShaders();
g_application.OnStart();
while (g_application.Running())
{
// handle key presses
processEvents();
glClearColor(0.2f, 0.2f, 0.6f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
g_oculusVR.OnRenderStart();
for (int eyeIndex = 0; eyeIndex < ovrEye_Count; eyeIndex++)
{
OVR::Matrix4f MVPMatrix = g_oculusVR.OnEyeRender(eyeIndex);
// update MVP in quad shader
const ShaderProgram &shader = ShaderManager::GetInstance()->UseShaderProgram(ShaderManager::BasicShader);
glUniformMatrix4fv(shader.uniforms[ModelViewProjectionMatrix], 1, GL_FALSE, &MVPMatrix.Transposed().M[0][0]);
g_application.OnRender();
g_oculusVR.OnEyeRenderFinish(eyeIndex);
}
g_oculusVR.SubmitFrame();
Application::VRMirrorMode mirrorMode = g_application.CurrMirrorMode();
// Standard mirror blit (both eyes, distorted)
if (mirrorMode == Application::Mirror_Regular)
{
ClearWindow(0.f, 0.f, 0.f);
g_oculusVR.BlitMirror(ovrEye_Count, 0);
}
// Standard mirror blit (left eye, distorted)
if (mirrorMode == Application::Mirror_RegularLeftEye)
{
ClearWindow(0.f, 0.f, 0.f);
g_oculusVR.BlitMirror(ovrEye_Left, windowSize.w / 4);
// rectangle indicating we're rendering left eye
ShaderManager::GetInstance()->DisableShader();
glViewport(0, 0, windowSize.w, windowSize.h);
DrawRectangle(-0.75f, 0.f, 0.1f, 0.1f, 0.f, 1.f, 0.f);
}
// Standard mirror blit (right eye, distorted)
if (mirrorMode == Application::Mirror_RegularRightEye)
{
ClearWindow(0.f, 0.f, 0.f);
g_oculusVR.BlitMirror(ovrEye_Right, windowSize.w / 4);
// rectangle indicating we're rendering right eye
ShaderManager::GetInstance()->DisableShader();
glViewport(0, 0, windowSize.w, windowSize.h);
DrawRectangle(0.75f, 0.f, 0.1f, 0.1f, 0.f, 1.f, 0.f);
}
// Both eye mirror - no distortion (requires 2 extra renders!)
if (mirrorMode == Application::Mirror_NonDistort)
{
g_oculusVR.OnNonDistortMirrorStart();
for (int eyeIndex = 0; eyeIndex < ovrEye_Count; eyeIndex++)
{
const OVR::Matrix4f MVPMatrix = g_oculusVR.GetEyeMVPMatrix(eyeIndex);
const ShaderProgram &shader = ShaderManager::GetInstance()->UseShaderProgram(ShaderManager::BasicShader);
glUniformMatrix4fv(shader.uniforms[ModelViewProjectionMatrix], 1, GL_FALSE, &MVPMatrix.Transposed().M[0][0]);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(0.2f, 0.2f, 0.6f, 0.0f);
g_application.OnRender();
g_oculusVR.BlitNonDistortMirror(eyeIndex == 0 ? 0 : windowSize.w / 2);
}
}
// Left eye - no distortion (1 extra render)
if (mirrorMode == Application::Mirror_NonDistortLeftEye)
{
ClearWindow(0.f, 0.f, 0.f);
g_oculusVR.OnNonDistortMirrorStart();
const OVR::Matrix4f MVPMatrix = g_oculusVR.GetEyeMVPMatrix(ovrEye_Left);
const ShaderProgram &shader = ShaderManager::GetInstance()->UseShaderProgram(ShaderManager::BasicShader);
glUniformMatrix4fv(shader.uniforms[ModelViewProjectionMatrix], 1, GL_FALSE, &MVPMatrix.Transposed().M[0][0]);
glClearColor(0.2f, 0.2f, 0.6f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
g_application.OnRender();
g_oculusVR.BlitNonDistortMirror(windowSize.w / 4);
ShaderManager::GetInstance()->DisableShader();
glViewport(0, 0, windowSize.w, windowSize.h);
DrawRectangle(-0.75f, 0.f, 0.1f, 0.1f, 0.f, 1.f, 0.f);
}
// Right eye - no distortion (1 extra render)
if (mirrorMode == Application::Mirror_NonDistortRightEye)
{
ClearWindow(0.f, 0.f, 0.f);
g_oculusVR.OnNonDistortMirrorStart();
const OVR::Matrix4f MVPMatrix = g_oculusVR.GetEyeMVPMatrix(ovrEye_Right);
const ShaderProgram &shader = ShaderManager::GetInstance()->UseShaderProgram(ShaderManager::BasicShader);
glUniformMatrix4fv(shader.uniforms[ModelViewProjectionMatrix], 1, GL_FALSE, &MVPMatrix.Transposed().M[0][0]);
glClearColor(0.2f, 0.2f, 0.6f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
g_application.OnRender();
g_oculusVR.BlitNonDistortMirror(windowSize.w / 4);
ShaderManager::GetInstance()->DisableShader();
glViewport(0, 0, windowSize.w, windowSize.h);
DrawRectangle(0.75f, 0.f, 0.1f, 0.1f, 0.f, 1.f, 0.f);
}
SDL_GL_SwapWindow(g_renderContext.window);
}
g_oculusVR.DestroyVR();
g_renderContext.Destroy();
SDL_Quit();
return 0;
}<|endoftext|> |
<commit_before>#include "RigidObject.h"
#include "Mass.h"
#include "robotics/Inertia.h"
#include <utils/SimpleFile.h>
#include <utils/stringutils.h>
#include <meshing/IO.h>
#include <string.h>
#include <fstream>
using namespace Math3D;
using namespace std;
RigidObject::RigidObject()
{
T.setIdentity();
mass = 1;
com.setZero();
inertia.setIdentity();
kFriction = 0.5;
kRestitution = 0.0;
kStiffness = kDamping = Inf;
}
bool RigidObject::Load(const char* fn)
{
const char* ext=FileExtension(fn);
if(!ext) {
fprintf(stderr,"Unknown (no) file extension on file %s\n",fn);
return false;
}
if(strcmp(ext,"obj")==0) {
SimpleFile f(fn);
if(!fn) return false;
if(!f.CheckSize("mesh",1,fn)) return false;
if(!f.CheckType("mesh",PrimitiveValue::String,fn)) return false;
string fnPath = GetFilePath(fn);
geomFile = f["mesh"][0].AsString();
string geomfn = fnPath + geomFile;
if(!geometry.Load(geomfn.c_str())) {
fprintf(stderr,"Error loading geometry file %s\n",geomfn.c_str());
return false;
}
else {
//fprintf(stderr,"Unable to load object %s\n",geomfn.c_str());
}
f.erase("mesh");
Matrix4 geomT; geomT.setIdentity();
if(f.count("geomscale") != 0) {
if(!f.CheckType("geomscale",PrimitiveValue::Double,fn)) return false;
vector<double> scale = f.AsDouble("geomscale");
if(scale.size()==1) { geomT(0,0)=geomT(1,1)=geomT(2,2)=scale[0]; }
else if(scale.size()==3) {
geomT(0,0)=scale[0];
geomT(1,1)=scale[1];
geomT(2,2)=scale[2];
}
else {
fprintf(stderr,"Invalid number of geomscale components in %s\n",fn);
return false;
}
f.erase("geomscale");
}
if(f.count("geomtranslate") != 0) {
if(!f.CheckType("geomtranslate",PrimitiveValue::Double,fn)) return false;
if(!f.CheckSize("geomtranslate",3,fn)) return false;
vector<double> trans = f.AsDouble("geomtranslate");
geomT(0,3)=trans[0];
geomT(1,3)=trans[1];
geomT(2,3)=trans[2];
f.erase("geomtranslate");
}
geometry.Transform(geomT);
if(f.count("T")==0) { T.setIdentity(); }
else {
if(!f.CheckType("T",PrimitiveValue::Double,fn)) return false;
vector<double> items = f.AsDouble("T");
if(items.size()==12) { //read 4 columns of 3
Vector3 x(items[0],items[1],items[2]);
Vector3 y(items[3],items[4],items[5]);
Vector3 z(items[6],items[7],items[8]);
Vector3 t(items[9],items[10],items[11]);
T.R.set(x,y,z); T.t=t;
}
else if(items.size()==16) { //read 4 columns of 4
Vector3 x(items[0],items[1],items[2]);
Vector3 y(items[4],items[5],items[6]);
Vector3 z(items[8],items[9],items[10]);
Vector3 t(items[12],items[13],items[14]);
T.R.set(x,y,z); T.t=t;
}
else {
fprintf(stderr,"Invalid number of transformation components in %s\n",fn);
return false;
}
f.erase("T");
}
if(f.count("mass")==0) { mass=1.0; }
else {
if(!f.CheckSize("mass",1)) return false;
if(!f.CheckType("mass",PrimitiveValue::Double)) return false;
mass = f["mass"][0].AsDouble();
f.erase("mass");
}
if(f.count("com")==0) { com.setZero(); }
else {
if(!f.CheckSize("com",3)) return false;
if(!f.CheckType("com",PrimitiveValue::Double)) return false;
com.set(f["com"][0].AsDouble(),f["com"][1].AsDouble(),f["com"][2].AsDouble());
f.erase("com");
}
if(f.count("inertia")==0) inertia.setIdentity();
else {
if(!f.CheckType("inertia",PrimitiveValue::Double,fn)) return false;
vector<double> items = f.AsDouble("inertia");
if(items.size() == 3) inertia.setDiagonal(Vector3(items[0],items[1],items[2]));
else if(items.size() == 9) {
inertia(0,0)=items[0]; inertia(0,1)=items[1]; inertia(0,2)=items[2];
inertia(1,0)=items[3]; inertia(1,1)=items[4]; inertia(1,2)=items[5];
inertia(2,0)=items[6]; inertia(2,1)=items[7]; inertia(2,2)=items[8];
}
else {
fprintf(stderr,"Invalid number of inertia matrix components in %s\n",fn);
return false;
}
f.erase("inertia");
}
if(f.count("kFriction")==0) kFriction = 0.5;
else {
if(!f.CheckSize("kFriction",1,fn)) return false;
if(!f.CheckType("kFriction",PrimitiveValue::Double,fn)) return false;
kFriction = f.AsDouble("kFriction")[0];
f.erase("kFriction");
}
if(f.count("kRestitution")==0) kRestitution = 0.5;
else {
if(!f.CheckSize("kRestitution",1,fn)) return false;
if(!f.CheckType("kRestitution",PrimitiveValue::Double,fn)) return false;
kRestitution = f.AsDouble("kRestitution")[0];
f.erase("kRestitution");
}
if(f.count("kStiffness")==0) kStiffness=Inf;
else {
if(!f.CheckSize("kStiffness",1,fn)) return false;
if(!f.CheckType("kStiffness",PrimitiveValue::Double,fn)) return false;
kStiffness = f.AsDouble("kStiffness")[0];
f.erase("kStiffness");
}
if(f.count("kDamping")==0) kDamping=Inf;
else {
if(!f.CheckSize("kDamping",1,fn)) return false;
if(!f.CheckType("kDamping",PrimitiveValue::Double,fn)) return false;
kDamping = f.AsDouble("kDamping")[0];
f.erase("kDamping");
}
if(f.count("autoMass")!=0) {
SetMassFromGeometry(mass);
f.erase("autoMass");
}
if(!f.empty()) {
for(map<string,vector<PrimitiveValue> >::const_iterator i=f.entries.begin();i!=f.entries.end();i++)
fprintf(stderr,"Unknown entry %s in object file %s\n",i->first.c_str(),fn);
}
geometry.InitCollisions();
return true;
}
else if(Geometry::AnyGeometry3D::CanLoadExt(ext)) {
if(!geometry.Load(fn)) return false;
geometry.InitCollisions();
T.setIdentity();
mass=1.0;
com.setZero();
inertia.setZero();
kFriction = 0.5;
kRestitution = 0.5;
kStiffness=Inf;
kDamping=Inf;
fprintf(stderr,"Warning, loading object from .%s file %s. May have zero inertia.\n",ext,fn);
return true;
}
else {
fprintf(stderr,"RigidObject: Unknown file extension %s on file %s\n",ext,fn);
return false;
}
}
bool RigidObject::Save(const char* fn)
{
ofstream out(fn);
if(!out) return false;
fprintf(stderr,"RigidObject::Save: not done yet\n");
return false;
return true;
}
void RigidObject::SetMassFromGeometry(Real totalMass)
{
mass = totalMass;
com = CenterOfMass(geometry);
inertia = Inertia(geometry,com,mass);
}
void RigidObject::SetMassFromBB(Real totalMass)
{
AABB3D bb=geometry.GetAABB();
mass = totalMass;
com = 0.5*(bb.bmin+bb.bmax);
BoxInertiaMatrix(bb.bmax.x-bb.bmin.x,bb.bmax.y-bb.bmin.y,bb.bmax.z-bb.bmin.z,mass,inertia);
}
void RigidObject::UpdateGeometry()
{
geometry.SetTransform(T);
}
<commit_msg>By default, rigid objects come with mass 1 and auto COM/inertia<commit_after>#include "RigidObject.h"
#include "Mass.h"
#include "robotics/Inertia.h"
#include <utils/SimpleFile.h>
#include <utils/stringutils.h>
#include <meshing/IO.h>
#include <string.h>
#include <fstream>
using namespace Math3D;
using namespace std;
RigidObject::RigidObject()
{
T.setIdentity();
mass = 1;
com.setZero();
inertia.setIdentity();
kFriction = 0.5;
kRestitution = 0.0;
kStiffness = kDamping = Inf;
}
bool RigidObject::Load(const char* fn)
{
const char* ext=FileExtension(fn);
if(!ext) {
fprintf(stderr,"Unknown (no) file extension on file %s\n",fn);
return false;
}
if(strcmp(ext,"obj")==0) {
SimpleFile f(fn);
if(!fn) return false;
if(!f.CheckSize("mesh",1,fn)) return false;
if(!f.CheckType("mesh",PrimitiveValue::String,fn)) return false;
string fnPath = GetFilePath(fn);
geomFile = f["mesh"][0].AsString();
string geomfn = fnPath + geomFile;
if(!geometry.Load(geomfn.c_str())) {
fprintf(stderr,"Error loading geometry file %s\n",geomfn.c_str());
return false;
}
else {
//fprintf(stderr,"Unable to load object %s\n",geomfn.c_str());
}
f.erase("mesh");
Matrix4 geomT; geomT.setIdentity();
if(f.count("geomscale") != 0) {
if(!f.CheckType("geomscale",PrimitiveValue::Double,fn)) return false;
vector<double> scale = f.AsDouble("geomscale");
if(scale.size()==1) { geomT(0,0)=geomT(1,1)=geomT(2,2)=scale[0]; }
else if(scale.size()==3) {
geomT(0,0)=scale[0];
geomT(1,1)=scale[1];
geomT(2,2)=scale[2];
}
else {
fprintf(stderr,"Invalid number of geomscale components in %s\n",fn);
return false;
}
f.erase("geomscale");
}
if(f.count("geomtranslate") != 0) {
if(!f.CheckType("geomtranslate",PrimitiveValue::Double,fn)) return false;
if(!f.CheckSize("geomtranslate",3,fn)) return false;
vector<double> trans = f.AsDouble("geomtranslate");
geomT(0,3)=trans[0];
geomT(1,3)=trans[1];
geomT(2,3)=trans[2];
f.erase("geomtranslate");
}
geometry.Transform(geomT);
if(f.count("T")==0) { T.setIdentity(); }
else {
if(!f.CheckType("T",PrimitiveValue::Double,fn)) return false;
vector<double> items = f.AsDouble("T");
if(items.size()==12) { //read 4 columns of 3
Vector3 x(items[0],items[1],items[2]);
Vector3 y(items[3],items[4],items[5]);
Vector3 z(items[6],items[7],items[8]);
Vector3 t(items[9],items[10],items[11]);
T.R.set(x,y,z); T.t=t;
}
else if(items.size()==16) { //read 4 columns of 4
Vector3 x(items[0],items[1],items[2]);
Vector3 y(items[4],items[5],items[6]);
Vector3 z(items[8],items[9],items[10]);
Vector3 t(items[12],items[13],items[14]);
T.R.set(x,y,z); T.t=t;
}
else {
fprintf(stderr,"Invalid number of transformation components in %s\n",fn);
return false;
}
f.erase("T");
}
if(f.count("mass")==0) { mass=1.0; }
else {
if(!f.CheckSize("mass",1)) return false;
if(!f.CheckType("mass",PrimitiveValue::Double)) return false;
mass = f["mass"][0].AsDouble();
f.erase("mass");
}
if(f.count("com")==0) { com.setZero(); }
else {
if(!f.CheckSize("com",3)) return false;
if(!f.CheckType("com",PrimitiveValue::Double)) return false;
com.set(f["com"][0].AsDouble(),f["com"][1].AsDouble(),f["com"][2].AsDouble());
f.erase("com");
}
if(f.count("inertia")==0) inertia.setIdentity();
else {
if(!f.CheckType("inertia",PrimitiveValue::Double,fn)) return false;
vector<double> items = f.AsDouble("inertia");
if(items.size() == 3) inertia.setDiagonal(Vector3(items[0],items[1],items[2]));
else if(items.size() == 9) {
inertia(0,0)=items[0]; inertia(0,1)=items[1]; inertia(0,2)=items[2];
inertia(1,0)=items[3]; inertia(1,1)=items[4]; inertia(1,2)=items[5];
inertia(2,0)=items[6]; inertia(2,1)=items[7]; inertia(2,2)=items[8];
}
else {
fprintf(stderr,"Invalid number of inertia matrix components in %s\n",fn);
return false;
}
f.erase("inertia");
}
if(f.count("kFriction")==0) kFriction = 0.5;
else {
if(!f.CheckSize("kFriction",1,fn)) return false;
if(!f.CheckType("kFriction",PrimitiveValue::Double,fn)) return false;
kFriction = f.AsDouble("kFriction")[0];
f.erase("kFriction");
}
if(f.count("kRestitution")==0) kRestitution = 0.5;
else {
if(!f.CheckSize("kRestitution",1,fn)) return false;
if(!f.CheckType("kRestitution",PrimitiveValue::Double,fn)) return false;
kRestitution = f.AsDouble("kRestitution")[0];
f.erase("kRestitution");
}
if(f.count("kStiffness")==0) kStiffness=Inf;
else {
if(!f.CheckSize("kStiffness",1,fn)) return false;
if(!f.CheckType("kStiffness",PrimitiveValue::Double,fn)) return false;
kStiffness = f.AsDouble("kStiffness")[0];
f.erase("kStiffness");
}
if(f.count("kDamping")==0) kDamping=Inf;
else {
if(!f.CheckSize("kDamping",1,fn)) return false;
if(!f.CheckType("kDamping",PrimitiveValue::Double,fn)) return false;
kDamping = f.AsDouble("kDamping")[0];
f.erase("kDamping");
}
if(f.count("autoMass")!=0) {
SetMassFromGeometry(mass);
f.erase("autoMass");
}
if(!f.empty()) {
for(map<string,vector<PrimitiveValue> >::const_iterator i=f.entries.begin();i!=f.entries.end();i++)
fprintf(stderr,"Unknown entry %s in object file %s\n",i->first.c_str(),fn);
}
geometry.InitCollisions();
return true;
}
else if(Geometry::AnyGeometry3D::CanLoadExt(ext)) {
if(!geometry.Load(fn)) return false;
geometry.InitCollisions();
T.setIdentity();
mass=1.0;
com.setZero();
inertia.setZero();
kFriction = 0.5;
kRestitution = 0.5;
kStiffness=Inf;
kDamping=Inf;
fprintf(stderr,"Warning, loading object from .%s file %s. Setting COM and inertia matrix from geometry.\n",ext,fn);
SetMassFromGeometry(1.0);
return true;
}
else {
fprintf(stderr,"RigidObject: Unknown file extension %s on file %s\n",ext,fn);
return false;
}
}
bool RigidObject::Save(const char* fn)
{
ofstream out(fn);
if(!out) return false;
fprintf(stderr,"RigidObject::Save: not done yet\n");
return false;
return true;
}
void RigidObject::SetMassFromGeometry(Real totalMass)
{
mass = totalMass;
com = CenterOfMass(geometry);
inertia = Inertia(geometry,com,mass);
}
void RigidObject::SetMassFromBB(Real totalMass)
{
AABB3D bb=geometry.GetAABB();
mass = totalMass;
com = 0.5*(bb.bmin+bb.bmax);
BoxInertiaMatrix(bb.bmax.x-bb.bmin.x,bb.bmax.y-bb.bmin.y,bb.bmax.z-bb.bmin.z,mass,inertia);
}
void RigidObject::UpdateGeometry()
{
geometry.SetTransform(T);
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2017 Darius Rückert
* Licensed under the MIT License.
* See LICENSE file for more information.
*/
#include "saiga/core/Core.h"
#include "saiga/core/time/all.h"
using namespace Saiga;
int sizeMB = 1000 * 1;
size_t blockSize = sizeMB * 1000UL * 1000UL;
double blockSizeGB = (blockSize / (1000.0 * 1000.0 * 1000.0));
std::atomic_int debugVar = 0;
void memcpyTest(int threads)
{
double readWriteGB = blockSizeGB * 2 * threads; // read + write
std::vector<char> src(blockSize * threads);
std::vector<char> dst(blockSize * threads);
omp_set_num_threads(threads);
auto singleThread = measureObject(5, [&]() {
#pragma omp parallel for
for (int i = 0; i < threads; ++i)
{
size_t offset = blockSize * i;
memcpy(dst.data() + offset, src.data() + offset, blockSize);
}
});
auto t = singleThread.median / 1000.0;
double bw = readWriteGB / t;
std::cout << "Threads " << threads << " Bandwidth: " << bw << " GB/s" << std::endl;
}
void latencyTest()
{
std::vector<char> src(blockSize * 8);
int N = 10000000;
int sum = 0;
auto stats = measureObject(5, [&]() {
size_t offset = 0;
for (int i = 0; i < N; ++i)
{
int* ptr = (int*)(src.data() + offset);
sum += *ptr;
// just go in 10kb steps through the memory
offset += 1000 * 10;
if (offset >= blockSize * 8) offset = 0;
}
});
debugVar += sum;
auto t = stats.median / 1000.0;
double teleNS = t / N * (1000.0 * 1000.0 * 1000.0);
std::cout << "Latency: " << teleNS << "ns" << std::endl;
}
int main(int, char**)
{
catchSegFaults();
latencyTest();
std::cout << "Starting RAM Bandwidth test with " << blockSizeGB << " GB blocks." << std::endl;
memcpyTest(1);
memcpyTest(2);
memcpyTest(4);
memcpyTest(8);
memcpyTest(16);
std::cout << "Done." << std::endl;
return 0;
}
<commit_msg>benchmark only 8 threads max<commit_after>/**
* Copyright (c) 2017 Darius Rückert
* Licensed under the MIT License.
* See LICENSE file for more information.
*/
#include "saiga/core/Core.h"
#include "saiga/core/time/all.h"
using namespace Saiga;
int sizeMB = 1000 * 1;
size_t blockSize = sizeMB * 1000UL * 1000UL;
double blockSizeGB = (blockSize / (1000.0 * 1000.0 * 1000.0));
std::atomic_int debugVar = 0;
void memcpyTest(int threads)
{
double readWriteGB = blockSizeGB * 2 * threads; // read + write
std::vector<char> src(blockSize * threads);
std::vector<char> dst(blockSize * threads);
omp_set_num_threads(threads);
auto singleThread = measureObject(5, [&]() {
#pragma omp parallel for
for (int i = 0; i < threads; ++i)
{
size_t offset = blockSize * i;
memcpy(dst.data() + offset, src.data() + offset, blockSize);
}
});
auto t = singleThread.median / 1000.0;
double bw = readWriteGB / t;
std::cout << "Threads " << threads << " Bandwidth: " << bw << " GB/s" << std::endl;
}
void latencyTest()
{
std::vector<char> src(blockSize * 8);
int N = 10000000;
int sum = 0;
auto stats = measureObject(5, [&]() {
size_t offset = 0;
for (int i = 0; i < N; ++i)
{
int* ptr = (int*)(src.data() + offset);
sum += *ptr;
// just go in 10kb steps through the memory
offset += 1000 * 10;
if (offset >= blockSize * 8) offset = 0;
}
});
debugVar += sum;
auto t = stats.median / 1000.0;
double teleNS = t / N * (1000.0 * 1000.0 * 1000.0);
std::cout << "Latency: " << teleNS << "ns" << std::endl;
}
int main(int, char**)
{
catchSegFaults();
latencyTest();
std::cout << "Starting RAM Bandwidth test with " << blockSizeGB << " GB blocks." << std::endl;
memcpyTest(1);
memcpyTest(2);
memcpyTest(4);
memcpyTest(8);
std::cout << "Done." << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: PresenterPaneBorderPainter.hxx,v $
*
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef SDEXT_PRESENTER_PRESENTER_PANE_BORDER_PAINTER_HXX
#define SDEXT_PRESENTER_PRESENTER_PANE_BORDER_PAINTER_HXX
#include <vcl/bitmap.hxx>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/awt/Rectangle.hpp>
#include <com/sun/star/drawing/framework/XPaneBorderPainter.hpp>
#include <com/sun/star/graphic/XGraphicProvider.hpp>
#include <com/sun/star/rendering/XCanvas.hpp>
#include <com/sun/star/util/XMacroExpander.hpp>
#include <com/sun/star/awt/XGraphics.hpp>
#include <cppuhelper/basemutex.hxx>
#include <cppuhelper/compbase1.hxx>
#include <boost/noncopyable.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
namespace css = ::com::sun::star;
namespace sdext { namespace tools {
class ConfigurationAccess;
} }
namespace sdext { namespace presenter {
class PresenterPane;
class PresenterTheme;
namespace {
typedef ::cppu::WeakComponentImplHelper1<
css::drawing::framework::XPaneBorderPainter
> PresenterPaneBorderPainterInterfaceBase;
}
/** This class is responsible for painting window borders of PresenterPane
objects.
*/
class PresenterPaneBorderPainter
: private ::boost::noncopyable,
protected ::cppu::BaseMutex,
public PresenterPaneBorderPainterInterfaceBase
{
public:
PresenterPaneBorderPainter (
const css::uno::Reference<css::uno::XComponentContext>& rxContext);
virtual ~PresenterPaneBorderPainter (void);
/** Transform the bounding box of the window content to the outer
bounding box of the border that is painted around it.
@param rsPaneURL
Specifies the pane style that is used to determine the border sizes.
@param rInnerBox
The rectangle of the inner window content.
*/
css::awt::Rectangle AddBorder (
const ::rtl::OUString& rsPaneURL,
const css::awt::Rectangle& rInnerBox,
const css::drawing::framework::BorderType eBorderType) const;
/** Transorm the outer bounding box of a window to the bounding box of
the inner content area.
@param rsPaneURL
Specifies the pane style that is used to determine the border sizes.
@param rOuterBox
The bounding box of the rectangle around the window.
@param bIsTitleVisible
This flag controls whether the upper part of the frame is
supposed to contain the window title.
*/
css::awt::Rectangle RemoveBorder (
const ::rtl::OUString& rsPaneURL,
const css::awt::Rectangle& rOuterBox,
const css::drawing::framework::BorderType eBorderType) const;
bool HasTheme (void) const;
void SetTheme (const ::boost::shared_ptr<PresenterTheme>& rpTheme);
class Renderer;
// XPaneBorderPainter
virtual css::awt::Rectangle SAL_CALL addBorder (
const rtl::OUString& rsPaneBorderStyleName,
const css::awt::Rectangle& rRectangle,
css::drawing::framework::BorderType eBorderType)
throw(css::uno::RuntimeException);
virtual css::awt::Rectangle SAL_CALL removeBorder (
const rtl::OUString& rsPaneBorderStyleName,
const css::awt::Rectangle& rRectangle,
css::drawing::framework::BorderType eBorderType)
throw(css::uno::RuntimeException);
virtual void SAL_CALL paintBorder(
const ::rtl::OUString& sPaneBorderStyleName,
const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XCanvas >& xCanvas,
const ::com::sun::star::awt::Rectangle& aOuterBorderRectangle,
const ::com::sun::star::awt::Rectangle& aRepaintArea,
const ::rtl::OUString& sTitle )
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL paintBorderWithCallout(
const ::rtl::OUString& sPaneBorderStyleName,
const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XCanvas >& xCanvas,
const ::com::sun::star::awt::Rectangle& aOuterBorderRectangle,
const ::com::sun::star::awt::Rectangle& aRepaintArea,
const ::rtl::OUString& sTitle,
const ::com::sun::star::awt::Point& aCalloutAnchor )
throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Point SAL_CALL getCalloutOffset(
const ::rtl::OUString& sPaneBorderStyleName )
throw (::com::sun::star::uno::RuntimeException);
private:
css::uno::Reference<css::uno::XComponentContext> mxContext;
::boost::shared_ptr<PresenterTheme> mpTheme;
::boost::scoped_ptr<Renderer> mpRenderer;
/** When the theme for the border has not yet been loaded then try again
when this method is called.
@return
Returns <TRUE/> only one time when the theme is loaded and/or the
renderer is initialized.
*/
bool ProvideTheme (
const css::uno::Reference<css::rendering::XCanvas>& rxCanvas);
bool ProvideTheme (void);
void ThrowIfDisposed (void) const
throw (::com::sun::star::lang::DisposedException);
};
} } // end of namespace ::sd::presenter
#endif
<commit_msg>INTEGRATION: CWS presenterscreen (1.2.4); FILE MERGED 2008/04/22 08:27:50 af 1.2.4.2: RESYNC: (1.2-1.3); FILE MERGED 2008/04/16 15:46:30 af 1.2.4.1: #i18486# Added support for callout.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: PresenterPaneBorderPainter.hxx,v $
*
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef SDEXT_PRESENTER_PRESENTER_PANE_BORDER_PAINTER_HXX
#define SDEXT_PRESENTER_PRESENTER_PANE_BORDER_PAINTER_HXX
#include <vcl/bitmap.hxx>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/awt/Rectangle.hpp>
#include <com/sun/star/drawing/framework/XPaneBorderPainter.hpp>
#include <com/sun/star/graphic/XGraphicProvider.hpp>
#include <com/sun/star/rendering/XCanvas.hpp>
#include <com/sun/star/util/XMacroExpander.hpp>
#include <com/sun/star/awt/XGraphics.hpp>
#include <cppuhelper/basemutex.hxx>
#include <cppuhelper/compbase1.hxx>
#include <boost/noncopyable.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
namespace css = ::com::sun::star;
namespace sdext { namespace tools {
class ConfigurationAccess;
} }
namespace sdext { namespace presenter {
class PresenterPane;
class PresenterTheme;
namespace {
typedef ::cppu::WeakComponentImplHelper1<
css::drawing::framework::XPaneBorderPainter
> PresenterPaneBorderPainterInterfaceBase;
}
/** This class is responsible for painting window borders of PresenterPane
objects.
*/
class PresenterPaneBorderPainter
: private ::boost::noncopyable,
protected ::cppu::BaseMutex,
public PresenterPaneBorderPainterInterfaceBase
{
public:
PresenterPaneBorderPainter (
const css::uno::Reference<css::uno::XComponentContext>& rxContext);
virtual ~PresenterPaneBorderPainter (void);
/** Transform the bounding box of the window content to the outer
bounding box of the border that is painted around it.
@param rsPaneURL
Specifies the pane style that is used to determine the border sizes.
@param rInnerBox
The rectangle of the inner window content.
*/
css::awt::Rectangle AddBorder (
const ::rtl::OUString& rsPaneURL,
const css::awt::Rectangle& rInnerBox,
const css::drawing::framework::BorderType eBorderType) const;
/** Transorm the outer bounding box of a window to the bounding box of
the inner content area.
@param rsPaneURL
Specifies the pane style that is used to determine the border sizes.
@param rOuterBox
The bounding box of the rectangle around the window.
@param bIsTitleVisible
This flag controls whether the upper part of the frame is
supposed to contain the window title.
*/
css::awt::Rectangle RemoveBorder (
const ::rtl::OUString& rsPaneURL,
const css::awt::Rectangle& rOuterBox,
const css::drawing::framework::BorderType eBorderType) const;
bool HasTheme (void) const;
void SetTheme (const ::boost::shared_ptr<PresenterTheme>& rpTheme);
class Renderer;
// XPaneBorderPainter
virtual css::awt::Rectangle SAL_CALL addBorder (
const rtl::OUString& rsPaneBorderStyleName,
const css::awt::Rectangle& rRectangle,
css::drawing::framework::BorderType eBorderType)
throw(css::uno::RuntimeException);
virtual css::awt::Rectangle SAL_CALL removeBorder (
const rtl::OUString& rsPaneBorderStyleName,
const css::awt::Rectangle& rRectangle,
css::drawing::framework::BorderType eBorderType)
throw(css::uno::RuntimeException);
virtual void SAL_CALL paintBorder (
const rtl::OUString& rsPaneBorderStyleName,
const css::uno::Reference<css::rendering::XCanvas>& rxCanvas,
const css::awt::Rectangle& rOuterBorderRectangle,
const css::awt::Rectangle& rRepaintArea,
const rtl::OUString& rsTitle)
throw(css::uno::RuntimeException);
virtual void SAL_CALL paintBorderWithCallout (
const rtl::OUString& rsPaneBorderStyleName,
const css::uno::Reference<css::rendering::XCanvas>& rxCanvas,
const css::awt::Rectangle& rOuterBorderRectangle,
const css::awt::Rectangle& rRepaintArea,
const rtl::OUString& rsTitle,
const css::awt::Point& rCalloutAnchor)
throw(css::uno::RuntimeException);
virtual css::awt::Point SAL_CALL getCalloutOffset (
const rtl::OUString& rsPaneBorderStyleName)
throw(css::uno::RuntimeException);
private:
css::uno::Reference<css::uno::XComponentContext> mxContext;
::boost::shared_ptr<PresenterTheme> mpTheme;
::boost::scoped_ptr<Renderer> mpRenderer;
/** When the theme for the border has not yet been loaded then try again
when this method is called.
@return
Returns <TRUE/> only one time when the theme is loaded and/or the
renderer is initialized.
*/
bool ProvideTheme (
const css::uno::Reference<css::rendering::XCanvas>& rxCanvas);
bool ProvideTheme (void);
void ThrowIfDisposed (void) const
throw (::com::sun::star::lang::DisposedException);
};
} } // end of namespace ::sd::presenter
#endif
<|endoftext|> |
<commit_before>#include "Character.h"
#include "PlayScene.h"
#include <math.h>
CCharacter::CCharacter(void)
{
/* ߰ Ͱ ƴ ijͰ ð .
Ÿ Ÿ ð ϴ , update ȿ Լ ŵǴ Ư
ȿ m_CreateTime Ű 켱 . Ф
*/
SetCreateTime(clock());
SetNowTime(clock());
m_is_iceState = false;
//sight öϰ ijͰ ġ ̱
m_sight = 100.0f + rand() % 20;
}
CCharacter::~CCharacter(void)
{
}
void CCharacter::initStatus( void )
{
}
/*
Լ : DetermineAttackTarget
: ü attack_target ϴ Լ ϸ ȴ.
Ŀ GoAttackTarget Լ ϸ
ֿ : ̱ Scene ִ Police迭 鼭 NNPoint Լ ̿
Ÿ ϰ Ÿ Ͽ شϴ idx Ÿ ȯѴ.
: 2013/11/03
: 2013/11/14
ISSUE : 1 . switch ݺǴ For ϳ ãƾ .
.
11/14 : Enemy (NULL) attackTarget Base ϵ
*/
void CCharacter::DetermineAttackTarget()
{
float return_distnace = 1000000.0f;
float next_distance;
CZombie *tmp_closer_target_zombie = NULL;
CPolice *tmp_closer_target_police = NULL;
CCharacter *return_target = NULL;
switch(this->GetIdentity())
{
case Zombie:
for(const auto& child : CPlayScene::GetInstance()->GetPoliceList())
{
next_distance = this->GetPosition().GetDistance(child->GetPosition());
if(return_distnace > next_distance)
{
return_distnace = next_distance;
m_AttackTarget = child;
}
}
if(m_AttackTarget == NULL)
m_AttackTarget = CPlayScene::GetInstance()->GetMapCreator()->GetPoliceBase();
break;
case Police:
for(const auto& child : CPlayScene::GetInstance()->GetZombieList())
{
next_distance= this->GetPosition().GetDistance(child->GetPosition());
if(return_distnace > next_distance)
{
return_distnace = next_distance;
m_AttackTarget = child;
}
}
if(m_AttackTarget == NULL)
m_AttackTarget = CPlayScene::GetInstance()->GetMapCreator()->GetZombieBase();
break;
default:
break;
}
}
void CCharacter::InitSprite( std::wstring imagePath )
{
m_Sprite = NNSprite::Create(imagePath);
// θ ġ ޱ
// θ ij ġ ϰ
// ڽ sprite (0, 0) ʱȭѴ.
// ̰Ͷ ѽð Ф
m_Sprite->SetPosition(0.0f, 0.0f);
AddChild(m_Sprite, 1);
m_pShowHP = NNLabel::Create(L"HP", L" ", 10.f);
m_pShowHP->SetPosition(m_Sprite->GetPositionX(), m_Sprite->GetPositionY()+10.f);
AddChild(m_pShowHP, 20);
}
void CCharacter::SetRandomPositionAroundBase()
{
NNPoint baseLocation;
switch (m_Identity)
{
case Zombie:
baseLocation = CPlayScene::GetInstance()->GetMapCreator()->GetZombieBase()->GetPosition();
baseLocation.SetX(baseLocation.GetX()+TILE_SIZE_X);
baseLocation.SetY(baseLocation.GetY()+TILE_SIZE_Y);
break;
case Police:
baseLocation = CPlayScene::GetInstance()->GetMapCreator()->GetPoliceBase()->GetPosition();
baseLocation.SetX(baseLocation.GetX()-TILE_SIZE_X);
break;
default:
break;
}
int random_location_x = rand() % TILE_SIZE_X;
int random_location_y = rand() % TILE_SIZE_Y;
SetPosition((baseLocation.GetX()+random_location_x),(baseLocation.GetY()+random_location_y));
}
void CCharacter::Render()
{
NNObject::Render();
}
void CCharacter::Update( float dTime )
{
//AttackTarget ϰ Attack ϸ(Ÿ üũ)
//ϰ Attack Target
ZeroMemory(temp_HP, 256);
swprintf_s(temp_HP, _countof(temp_HP), L"%d", m_HealthPoint );
m_pShowHP->SetString(temp_HP);
m_pShowHP->SetPosition(m_Sprite->GetPositionX(), m_Sprite->GetPositionY()+10.f);
int CheckTimeChange = GetNowTimeSEC();
SetNowTime(clock());
DetermineAttackTarget();
CheckIceState();
// ִ ¶ ̵/ Ұ
if(!m_is_iceState)
if(IsAttack())
{
if((GetNowTimeSEC() - GetCreateTimeSEC()) % GetAttackSpeed() == 0 && CheckTimeChange != GetNowTimeSEC()) // ʴ ð ߴ° Բ üũѴ (dTime ʹ ۾ int ȯϴ Get~TimeSEC Լ 1 dTime ȯѴ.)
Attack();
}
else
GoToAttackTarget(dTime);
}
void CCharacter::Attack()
{
CCharacter* target = this->m_AttackTarget;
int damage;
if(this->m_AttackTarget){
damage = this->GetAttackPower() - target->GetDefensivePower();
target->SetHP(target->GetHP()-damage) ;
}
//SplashӼ true Splash
if(this->m_is_splash)
SplashAttack(damage);
}
/*
ȣ. 11/14
Attack_target Ÿ Ͽ ϵ .
Issue : ϴ MakeCharacterWalk
*/
void CCharacter::GoToAttackTarget(float dTime)
{
float gap_x = m_AttackTarget->GetPositionX() - m_Position.GetX();
float gap_y = m_AttackTarget->GetPositionY() - m_Position.GetY();
float t_x = (gap_x) / (gap_x+gap_y);
float t_y = (gap_y) / (gap_x+gap_y);
float distance_attacktarget;
distance_attacktarget = this->GetPosition().GetDistance(m_AttackTarget->GetPosition());
//Character Ȱġ ϱ ڵ
if(distance_attacktarget <= m_sight)
{
MakeCharacterWalk(dTime);
return ;
}
switch (m_Identity)
{
case Zombie:
this->SetPosition(this->m_Position - NNPoint( -(m_MovingSpeed*t_x),-( m_MovingSpeed*t_y) )*dTime);
break;
case Police:
this->SetPosition(this->m_Position - NNPoint( (m_MovingSpeed*t_x),( m_MovingSpeed*t_y) )*dTime);
break;
default:
break;
}
}
/*
ȣ. 11/14
Ȳ AttackTarget Ÿ ȿ ִ üũ.
ϸ True, (־) False
*/
bool CCharacter::IsAttack()
{
float distance_attacktarget;
distance_attacktarget = this->GetPosition().GetDistance(m_AttackTarget->GetPosition());
if(distance_attacktarget <= m_AttackRange)
return true;
else
return false;
}
/*
ȣ. 11/20
ó. PlayScene Enemy Ʈ 鼭
SplashRangeο ִ ó
*/
void CCharacter::SplashAttack(int damage)
{
switch (m_Identity)
{
case Zombie:
for (const auto& child : CPlayScene::GetInstance()->GetPoliceList())
{
float distance_attacktarget;
distance_attacktarget = this->GetPosition().GetDistance(child->GetPosition());
if(this->m_splash_range >= distance_attacktarget)
child->SetHP(child->GetHP()-damage);
}
break;
case Police:
for (const auto& child : CPlayScene::GetInstance()->GetZombieList())
{
float distance_attacktarget;
distance_attacktarget = this->GetPosition().GetDistance(child->GetPosition());
if(this->m_splash_range >= distance_attacktarget)
child->SetHP(child->GetHP()-damage);
}
break;
case Base:
break;
default:
break;
}
}
/*
11.21 ȣ
ð, ð ִ ¸ üũϿ °
õ ص üũϰ ݿ.
*/
void CCharacter::CheckIceState()
{
if(!m_is_iceState)
return ;
SetIceNowTime(clock());
printf_s("ICETIME : %d, NOWTIME : %d\n", m_iceStartTime/CLOCKS_PER_SEC, m_iceNowTime/CLOCKS_PER_SEC);
if(m_iceNowTime/CLOCKS_PER_SEC - m_iceStartTime/CLOCKS_PER_SEC > ICE_TIME)
{
printf_s("UNICE\n");
m_is_iceState = false;
}
}
void CCharacter::MakeCharacterWalk(float dTime)
{
switch (m_Identity)
{
case Zombie:
this->SetPosition(this->GetPosition() + NNPoint( (this->GetMovingSpeed()), 0.0f) * dTime);
break;
case Police:
this->SetPosition(this->GetPosition() - NNPoint( (this->GetMovingSpeed()), 0.0f) * dTime);
break;
case Base:
break;
default:
break;
}
}
<commit_msg>sight일단 수정<commit_after>#include "Character.h"
#include "PlayScene.h"
#include <math.h>
CCharacter::CCharacter(void)
{
/* ߰ Ͱ ƴ ijͰ ð .
Ÿ Ÿ ð ϴ , update ȿ Լ ŵǴ Ư
ȿ m_CreateTime Ű 켱 . Ф
*/
SetCreateTime(clock());
SetNowTime(clock());
m_is_iceState = false;
//sight öϰ ijͰ ġ ̱
m_sight = 500.0f + rand() % 20;
}
CCharacter::~CCharacter(void)
{
}
void CCharacter::initStatus( void )
{
}
/*
Լ : DetermineAttackTarget
: ü attack_target ϴ Լ ϸ ȴ.
Ŀ GoAttackTarget Լ ϸ
ֿ : ̱ Scene ִ Police迭 鼭 NNPoint Լ ̿
Ÿ ϰ Ÿ Ͽ شϴ idx Ÿ ȯѴ.
: 2013/11/03
: 2013/11/14
ISSUE : 1 . switch ݺǴ For ϳ ãƾ .
.
11/14 : Enemy (NULL) attackTarget Base ϵ
*/
void CCharacter::DetermineAttackTarget()
{
float return_distnace = 1000000.0f;
float next_distance;
CZombie *tmp_closer_target_zombie = NULL;
CPolice *tmp_closer_target_police = NULL;
CCharacter *return_target = NULL;
switch(this->GetIdentity())
{
case Zombie:
for(const auto& child : CPlayScene::GetInstance()->GetPoliceList())
{
next_distance = this->GetPosition().GetDistance(child->GetPosition());
if(return_distnace > next_distance)
{
return_distnace = next_distance;
m_AttackTarget = child;
}
}
if(m_AttackTarget == NULL)
m_AttackTarget = CPlayScene::GetInstance()->GetMapCreator()->GetPoliceBase();
break;
case Police:
for(const auto& child : CPlayScene::GetInstance()->GetZombieList())
{
next_distance= this->GetPosition().GetDistance(child->GetPosition());
if(return_distnace > next_distance)
{
return_distnace = next_distance;
m_AttackTarget = child;
}
}
if(m_AttackTarget == NULL)
m_AttackTarget = CPlayScene::GetInstance()->GetMapCreator()->GetZombieBase();
break;
default:
break;
}
}
void CCharacter::InitSprite( std::wstring imagePath )
{
m_Sprite = NNSprite::Create(imagePath);
// θ ġ ޱ
// θ ij ġ ϰ
// ڽ sprite (0, 0) ʱȭѴ.
// ̰Ͷ ѽð Ф
m_Sprite->SetPosition(0.0f, 0.0f);
AddChild(m_Sprite, 1);
m_pShowHP = NNLabel::Create(L"HP", L" ", 10.f);
m_pShowHP->SetPosition(m_Sprite->GetPositionX(), m_Sprite->GetPositionY()+10.f);
AddChild(m_pShowHP, 20);
}
void CCharacter::SetRandomPositionAroundBase()
{
NNPoint baseLocation;
switch (m_Identity)
{
case Zombie:
baseLocation = CPlayScene::GetInstance()->GetMapCreator()->GetZombieBase()->GetPosition();
baseLocation.SetX(baseLocation.GetX()+TILE_SIZE_X);
baseLocation.SetY(baseLocation.GetY()+TILE_SIZE_Y);
break;
case Police:
baseLocation = CPlayScene::GetInstance()->GetMapCreator()->GetPoliceBase()->GetPosition();
baseLocation.SetX(baseLocation.GetX()-TILE_SIZE_X);
break;
default:
break;
}
int random_location_x = rand() % TILE_SIZE_X;
int random_location_y = rand() % TILE_SIZE_Y;
SetPosition((baseLocation.GetX()+random_location_x),(baseLocation.GetY()+random_location_y));
}
void CCharacter::Render()
{
NNObject::Render();
}
void CCharacter::Update( float dTime )
{
//AttackTarget ϰ Attack ϸ(Ÿ üũ)
//ϰ Attack Target
ZeroMemory(temp_HP, 256);
swprintf_s(temp_HP, _countof(temp_HP), L"%d", m_HealthPoint );
m_pShowHP->SetString(temp_HP);
m_pShowHP->SetPosition(m_Sprite->GetPositionX(), m_Sprite->GetPositionY()+10.f);
int CheckTimeChange = GetNowTimeSEC();
SetNowTime(clock());
DetermineAttackTarget();
CheckIceState();
// ִ ¶ ̵/ Ұ
if(!m_is_iceState)
if(IsAttack())
{
if((GetNowTimeSEC() - GetCreateTimeSEC()) % GetAttackSpeed() == 0 && CheckTimeChange != GetNowTimeSEC()) // ʴ ð ߴ° Բ üũѴ (dTime ʹ ۾ int ȯϴ Get~TimeSEC Լ 1 dTime ȯѴ.)
Attack();
}
else
GoToAttackTarget(dTime);
}
void CCharacter::Attack()
{
CCharacter* target = this->m_AttackTarget;
int damage;
if(this->m_AttackTarget){
damage = this->GetAttackPower() - target->GetDefensivePower();
target->SetHP(target->GetHP()-damage) ;
}
//SplashӼ true Splash
if(this->m_is_splash)
SplashAttack(damage);
}
/*
ȣ. 11/14
Attack_target Ÿ Ͽ ϵ .
Issue : ϴ MakeCharacterWalk
*/
void CCharacter::GoToAttackTarget(float dTime)
{
float gap_x = m_AttackTarget->GetPositionX() - m_Position.GetX();
float gap_y = m_AttackTarget->GetPositionY() - m_Position.GetY();
float t_x = (gap_x) / (gap_x+gap_y);
float t_y = (gap_y) / (gap_x+gap_y);
float distance_attacktarget;
distance_attacktarget = this->GetPosition().GetDistance(m_AttackTarget->GetPosition());
//Character Ȱġ ϱ ڵ
/*if(distance_attacktarget <= m_sight)
{
MakeCharacterWalk(dTime);
return ;
}
*/
switch (m_Identity)
{
case Zombie:
this->SetPosition(this->m_Position - NNPoint( -(m_MovingSpeed*t_x),-( m_MovingSpeed*t_y) )*dTime);
break;
case Police:
this->SetPosition(this->m_Position - NNPoint( (m_MovingSpeed*t_x),( m_MovingSpeed*t_y) )*dTime);
break;
default:
break;
}
}
/*
ȣ. 11/14
Ȳ AttackTarget Ÿ ȿ ִ üũ.
ϸ True, (־) False
*/
bool CCharacter::IsAttack()
{
float distance_attacktarget;
distance_attacktarget = this->GetPosition().GetDistance(m_AttackTarget->GetPosition());
if(distance_attacktarget <= m_AttackRange)
return true;
else
return false;
}
/*
ȣ. 11/20
ó. PlayScene Enemy Ʈ 鼭
SplashRangeο ִ ó
*/
void CCharacter::SplashAttack(int damage)
{
switch (m_Identity)
{
case Zombie:
for (const auto& child : CPlayScene::GetInstance()->GetPoliceList())
{
float distance_attacktarget;
distance_attacktarget = this->GetPosition().GetDistance(child->GetPosition());
if(this->m_splash_range >= distance_attacktarget)
child->SetHP(child->GetHP()-damage);
}
break;
case Police:
for (const auto& child : CPlayScene::GetInstance()->GetZombieList())
{
float distance_attacktarget;
distance_attacktarget = this->GetPosition().GetDistance(child->GetPosition());
if(this->m_splash_range >= distance_attacktarget)
child->SetHP(child->GetHP()-damage);
}
break;
case Base:
break;
default:
break;
}
}
/*
11.21 ȣ
ð, ð ִ ¸ üũϿ °
õ ص üũϰ ݿ.
*/
void CCharacter::CheckIceState()
{
if(!m_is_iceState)
return ;
SetIceNowTime(clock());
printf_s("ICETIME : %d, NOWTIME : %d\n", m_iceStartTime/CLOCKS_PER_SEC, m_iceNowTime/CLOCKS_PER_SEC);
if(m_iceNowTime/CLOCKS_PER_SEC - m_iceStartTime/CLOCKS_PER_SEC > ICE_TIME)
{
printf_s("UNICE\n");
m_is_iceState = false;
}
}
void CCharacter::MakeCharacterWalk(float dTime)
{
switch (m_Identity)
{
case Zombie:
this->SetPosition(this->GetPosition() + NNPoint( (this->GetMovingSpeed()), 0.0f) * dTime);
break;
case Police:
this->SetPosition(this->GetPosition() - NNPoint( (this->GetMovingSpeed()), 0.0f) * dTime);
break;
case Base:
break;
default:
break;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlConnectionResource.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2007-11-09 08:13:31 $
*
* 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_dbaccess.hxx"
#ifndef DBA_XMLCONNECTIONRESOURCE_HXX_INCLUDED
#include "xmlConnectionResource.hxx"
#endif
#ifndef DBA_XMLFILTER_HXX
#include "xmlfilter.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef DBA_XMLENUMS_HXX
#include "xmlEnums.hxx"
#endif
#ifndef DBACCESS_SHARED_XMLSTRINGS_HRC
#include "xmlstrings.hrc"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef TOOLS_DIAGNOSE_EX_H
#include <tools/diagnose_ex.h>
#endif
namespace dbaxml
{
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
DBG_NAME(OXMLConnectionResource)
OXMLConnectionResource::OXMLConnectionResource( ODBFilter& rImport,
sal_uInt16 nPrfx, const ::rtl::OUString& _sLocalName,
const Reference< XAttributeList > & _xAttrList) :
SvXMLImportContext( rImport, nPrfx, _sLocalName )
{
DBG_CTOR(OXMLConnectionResource,NULL);
OSL_ENSURE(_xAttrList.is(),"Attribute list is NULL!");
const SvXMLNamespaceMap& rMap = rImport.GetNamespaceMap();
const SvXMLTokenMap& rTokenMap = rImport.GetComponentElemTokenMap();
Reference<XPropertySet> xDataSource = rImport.getDataSource();
PropertyValue aProperty;
const sal_Int16 nLength = (xDataSource.is() && _xAttrList.is()) ? _xAttrList->getLength() : 0;
for(sal_Int16 i = 0; i < nLength; ++i)
{
::rtl::OUString sLocalName;
const rtl::OUString sAttrName = _xAttrList->getNameByIndex( i );
const sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName );
const rtl::OUString sValue = _xAttrList->getValueByIndex( i );
aProperty.Name = ::rtl::OUString();
aProperty.Value = Any();
switch( rTokenMap.Get( nPrefix, sLocalName ) )
{
case XML_TOK_HREF:
try
{
xDataSource->setPropertyValue(PROPERTY_URL,makeAny(sValue));
}
catch(Exception)
{
DBG_UNHANDLED_EXCEPTION();
}
break;
case XML_TOK_TYPE:
aProperty.Name = PROPERTY_TYPE;
break;
case XML_TOK_SHOW:
aProperty.Name = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Show"));
break;
case XML_TOK_ACTUATE:
aProperty.Name = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Actuate"));
break;
}
if ( aProperty.Name.getLength() )
{
if ( !aProperty.Value.hasValue() )
aProperty.Value <<= sValue;
rImport.addInfo(aProperty);
}
}
}
// -----------------------------------------------------------------------------
OXMLConnectionResource::~OXMLConnectionResource()
{
DBG_DTOR(OXMLConnectionResource,NULL);
}
// -----------------------------------------------------------------------------
ODBFilter& OXMLConnectionResource::GetOwnImport()
{
return static_cast<ODBFilter&>(GetImport());
}
// -----------------------------------------------------------------------------
//----------------------------------------------------------------------------
} // namespace dbaxml
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS dba30a (1.2.36); FILE MERGED 2008/02/20 21:31:54 fs 1.2.36.1: remove unused code Issue number: #i86284# Submitted by: cmc@openoffice.org Reviewed by: fs@openoffice.org<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlConnectionResource.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2008-03-05 16:50:12 $
*
* 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_dbaccess.hxx"
#ifndef DBA_XMLCONNECTIONRESOURCE_HXX_INCLUDED
#include "xmlConnectionResource.hxx"
#endif
#ifndef DBA_XMLFILTER_HXX
#include "xmlfilter.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef DBA_XMLENUMS_HXX
#include "xmlEnums.hxx"
#endif
#ifndef DBACCESS_SHARED_XMLSTRINGS_HRC
#include "xmlstrings.hrc"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef TOOLS_DIAGNOSE_EX_H
#include <tools/diagnose_ex.h>
#endif
namespace dbaxml
{
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
DBG_NAME(OXMLConnectionResource)
OXMLConnectionResource::OXMLConnectionResource( ODBFilter& rImport,
sal_uInt16 nPrfx, const ::rtl::OUString& _sLocalName,
const Reference< XAttributeList > & _xAttrList) :
SvXMLImportContext( rImport, nPrfx, _sLocalName )
{
DBG_CTOR(OXMLConnectionResource,NULL);
OSL_ENSURE(_xAttrList.is(),"Attribute list is NULL!");
const SvXMLNamespaceMap& rMap = rImport.GetNamespaceMap();
const SvXMLTokenMap& rTokenMap = rImport.GetComponentElemTokenMap();
Reference<XPropertySet> xDataSource = rImport.getDataSource();
PropertyValue aProperty;
const sal_Int16 nLength = (xDataSource.is() && _xAttrList.is()) ? _xAttrList->getLength() : 0;
for(sal_Int16 i = 0; i < nLength; ++i)
{
::rtl::OUString sLocalName;
const rtl::OUString sAttrName = _xAttrList->getNameByIndex( i );
const sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName );
const rtl::OUString sValue = _xAttrList->getValueByIndex( i );
aProperty.Name = ::rtl::OUString();
aProperty.Value = Any();
switch( rTokenMap.Get( nPrefix, sLocalName ) )
{
case XML_TOK_HREF:
try
{
xDataSource->setPropertyValue(PROPERTY_URL,makeAny(sValue));
}
catch(Exception)
{
DBG_UNHANDLED_EXCEPTION();
}
break;
case XML_TOK_TYPE:
aProperty.Name = PROPERTY_TYPE;
break;
case XML_TOK_SHOW:
aProperty.Name = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Show"));
break;
case XML_TOK_ACTUATE:
aProperty.Name = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Actuate"));
break;
}
if ( aProperty.Name.getLength() )
{
if ( !aProperty.Value.hasValue() )
aProperty.Value <<= sValue;
rImport.addInfo(aProperty);
}
}
}
// -----------------------------------------------------------------------------
OXMLConnectionResource::~OXMLConnectionResource()
{
DBG_DTOR(OXMLConnectionResource,NULL);
}
// -----------------------------------------------------------------------------
//----------------------------------------------------------------------------
} // namespace dbaxml
// -----------------------------------------------------------------------------
<|endoftext|> |
<commit_before>#include <iostream>
#include <stack>
using namespace std;
struct Node{
int data;
Node* next;
Node(int d) :data(d), next(nullptr){};
};
int listLen(Node *head) {
Node *p = head;
int ret = 0;
while (p) {
ret++;
p = p->next;
}
return ret;
}
bool isPalindrome(Node *head) {
if (!head) return false;
int len = listLen(head);
Node *p = head;
stack<int> stk;
for (int i = 0; i < len/2; i++) {
stk.push(p->data);
p = p->next;
}
if (len % 2) p = p->next;
for (; p; p = p->next) {
if (stk.top() != p->data) return false;
stk.pop();
}
return true;
}
void printList(Node *head) {
Node *p = head;
while (p) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
void test(Node *head) {
printList(head);
cout << (isPalindrome(head) ? "Yes" : "No") << endl;
}
int main() {
Node *head = new Node(0);
head->next = new Node(1);
head->next->next = new Node(4);
head->next->next->next = new Node(1);
head->next->next->next->next = new Node(0);
test(head);
head = new Node(1);
head->next = new Node(1);
head->next->next = new Node(4);
head->next->next->next = new Node(1);
head->next->next->next->next = new Node(0);
test(head);
head = new Node(1);
head->next = new Node(0);
head->next->next = new Node(0);
head->next->next->next = new Node(1);
test(head);
head = new Node(0);
head->next = new Node(0);
head->next->next = new Node(0);
head->next->next->next = new Node(1);
test(head);
head = nullptr;
test(head);
}<commit_msg>2.7 another solution<commit_after>#include <iostream>
#include <stack>
using namespace std;
struct Node{
int data;
Node* next;
Node(int d) :data(d), next(nullptr){};
};
int listLen(Node *head) {
Node *p = head;
int ret = 0;
while (p) {
ret++;
p = p->next;
}
return ret;
}
/* Iterate list twice */
bool isPalindrome(Node *head) {
if (!head) return false;
int len = listLen(head);
Node *p = head;
stack<int> stk;
for (int i = 0; i < len/2; i++) {
stk.push(p->data);
p = p->next;
}
if (len % 2) p = p->next;
for (; p; p = p->next) {
if (stk.top() != p->data) return false;
stk.pop();
}
return true;
}
/* Use runner */
bool isPalindrome2(Node *head) {
if (!head) return false;
Node *slow = head, *fast = head;
stack<int> stk;
while (fast && fast->next) {
stk.push(slow->data);
slow = slow->next;
fast = fast->next->next;
}
if (fast) slow = slow->next;
while (slow) {
if (stk.top() != slow->data) return false;
slow = slow->next;
stk.pop();
}
return true;
}
void printList(Node *head) {
Node *p = head;
while (p) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
void test(Node *head) {
printList(head);
cout << (isPalindrome(head) ? "Yes" : "No") << " " << (isPalindrome2(head) ? "Yes" : "No") << endl;
}
int main() {
Node *head = new Node(0);
head->next = new Node(1);
head->next->next = new Node(4);
head->next->next->next = new Node(1);
head->next->next->next->next = new Node(0);
test(head);
head = new Node(1);
head->next = new Node(1);
head->next->next = new Node(4);
head->next->next->next = new Node(1);
head->next->next->next->next = new Node(0);
test(head);
head = new Node(1);
head->next = new Node(0);
head->next->next = new Node(0);
head->next->next->next = new Node(1);
test(head);
head = new Node(0);
head->next = new Node(0);
head->next->next = new Node(0);
head->next->next->next = new Node(1);
test(head);
head = nullptr;
test(head);
}<|endoftext|> |
<commit_before>AliEmcalAodTrackFilterTask* AddTaskEmcalAodTrackFilter(
const char *name = "FilterTracks",
const char *inname = "tracks",
const char *runperiod = "",
const char *taskName = "AliEmcalAodTrackFilterTask"
)
{
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
::Error("AddTaskAodTrackFilter", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler())
{
::Error("AddTaskAodTrackFilter", "This task requires an input event handler");
return NULL;
}
TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
if (inputDataType != "AOD")) {
::Info("AddTaskEmcalAodTpcTrack", "This task is only needed for AOD analysis. No task added.");
return NULL;
}
//-------------------------------------------------------
// Init the task and do settings
//-------------------------------------------------------
AliEmcalAodTrackFilterTask *aodTask = new AliEmcalAodTrackFilterTask(taskName);
aodTask->SetTracksOutName(name);
aodTask->SetTracksInName(inname);
aodTask->SetMC(kFALSE);
Bool_t includeNoITS = kFALSE;
Bool_t doProp = kFALSE;
TString runPeriod(runperiod);
runPeriod.ToLower();
std::cout << "run period" << runPeriod.Data() << std::endl;
if (runPeriod == "lhc10d" || runPeriod == "lhc10e" || runPeriod == "lhc10h" ||
runPeriod == "lhc11h" || runPeriod == "lhc12a" || runPeriod == "lhc12b" ||
runPeriod == "lhc12c" || runPeriod == "lhc12d" || runPeriod == "lhc12e" ||
runPeriod == "lhc12f" || runPeriod == "lhc12g" || runPeriod == "lhc12h" ||
runPeriod == "lhc12i" || runPeriod == "lhc13b" || runPeriod == "lhc13c" ||
runPeriod == "lhc13d" || runPeriod == "lhc13e" || runPeriod == "lhc13f" ||
runPeriod == "lhc13g"
) {
aodTask->SetAODfilterBits(256,512); // hybrid tracks
if (runPeriod == "lhc10d" || runPeriod == "lhc10e" || runPeriod == "lhc10h")
includeNoITS = kTRUE;
else if (runPeriod == "lhc11h") // fix cascade bug in LHC11h AOD145
aodTask->SetAttemptProp(kTRUE);
} else if (runPeriod == "lhc12a15e" || runPeriod.Contains("lhc12a17") || runPeriod == "lhc13b4" ||
runPeriod == "lhc13b4_fix" || runPeriod == "lhc13b4_plus" || runPeriod.Contains("lhc14a1") || runPeriod.Contains("lhc13b2_efix")
) {
aodTask->SetAODfilterBits(256,512); // hybrid tracks
aodTask->SetMC(kTRUE);
} else if (runPeriod == "lhc11a" || runPeriod == "lhc10hold") {
aodTask->SetAODfilterBits(256,16); // hybrid tracks
includeNoITS = kTRUE;
} else if(runPeriod == "lhc11d") {
aodTask->SetAODfilterBits(256,16); // hybrid tracks (MV: not 100% sure)
includeNoITS = kFALSE;
} else if (runPeriod.Contains("lhc12a15a") || runPeriod == "lhc12a15f" || runPeriod == "lhc12a15g") {
aodTask->SetAODfilterBits(256,16); // hybrid tracks
aodTask->SetMC(kTRUE);
includeNoITS = kTRUE;
} else if (runPeriod.Contains(":")) {
TObjArray *arr = runPeriod.Tokenize(":");
TString arg1(arr->At(0)->GetName());
TString arg2("-1");
if (arr->GetEntries()>1)
arg2 = arr->At(1)->GetName();
if (arr->GetEntries()>2) {
TString arg3 = arr->At(2)->GetName();
if (arg3.Contains("includeNoITS=kTRUE"))
includeNoITS=kTRUE;
if (arg3.Contains("doProp=kTRUE"))
doProp=kTRUE;
}
aodTask->SetAODfilterBits(arg1.Atoi(),arg2.Atoi());
delete arr;
} else {
if (!runPeriod.IsNull())
::Warning("Run period %s not known. It will use IsHybridGlobalConstrainedGlobal.", runPeriod.Data());
}
aodTask->SetIncludeNoITS(includeNoITS);
aodTask->SetDoPropagation(doProp);
//-------------------------------------------------------
// Final settings, pass to manager and set the containers
//-------------------------------------------------------
mgr->AddTask(aodTask);
// Create containers for input/output
AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
mgr->ConnectInput(aodTask, 0, cinput1 );
return aodTask;
}
<commit_msg>remove cout<commit_after>AliEmcalAodTrackFilterTask* AddTaskEmcalAodTrackFilter(
const char *name = "FilterTracks",
const char *inname = "tracks",
const char *runperiod = "",
const char *taskName = "AliEmcalAodTrackFilterTask"
)
{
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
::Error("AddTaskAodTrackFilter", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler())
{
::Error("AddTaskAodTrackFilter", "This task requires an input event handler");
return NULL;
}
TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
if (inputDataType != "AOD")) {
::Info("AddTaskEmcalAodTpcTrack", "This task is only needed for AOD analysis. No task added.");
return NULL;
}
//-------------------------------------------------------
// Init the task and do settings
//-------------------------------------------------------
AliEmcalAodTrackFilterTask *aodTask = new AliEmcalAodTrackFilterTask(taskName);
aodTask->SetTracksOutName(name);
aodTask->SetTracksInName(inname);
aodTask->SetMC(kFALSE);
Bool_t includeNoITS = kFALSE;
Bool_t doProp = kFALSE;
TString runPeriod(runperiod);
runPeriod.ToLower();
if (runPeriod == "lhc10d" || runPeriod == "lhc10e" || runPeriod == "lhc10h" ||
runPeriod == "lhc11h" || runPeriod == "lhc12a" || runPeriod == "lhc12b" ||
runPeriod == "lhc12c" || runPeriod == "lhc12d" || runPeriod == "lhc12e" ||
runPeriod == "lhc12f" || runPeriod == "lhc12g" || runPeriod == "lhc12h" ||
runPeriod == "lhc12i" || runPeriod == "lhc13b" || runPeriod == "lhc13c" ||
runPeriod == "lhc13d" || runPeriod == "lhc13e" || runPeriod == "lhc13f" ||
runPeriod == "lhc13g"
) {
aodTask->SetAODfilterBits(256,512); // hybrid tracks
if (runPeriod == "lhc10d" || runPeriod == "lhc10e" || runPeriod == "lhc10h")
includeNoITS = kTRUE;
else if (runPeriod == "lhc11h") // fix cascade bug in LHC11h AOD145
aodTask->SetAttemptProp(kTRUE);
} else if (runPeriod == "lhc12a15e" || runPeriod.Contains("lhc12a17") || runPeriod == "lhc13b4" ||
runPeriod == "lhc13b4_fix" || runPeriod == "lhc13b4_plus" || runPeriod.Contains("lhc14a1") || runPeriod.Contains("lhc13b2_efix")
) {
aodTask->SetAODfilterBits(256,512); // hybrid tracks
aodTask->SetMC(kTRUE);
} else if (runPeriod == "lhc11a" || runPeriod == "lhc10hold") {
aodTask->SetAODfilterBits(256,16); // hybrid tracks
includeNoITS = kTRUE;
} else if(runPeriod == "lhc11d") {
aodTask->SetAODfilterBits(256,16); // hybrid tracks (MV: not 100% sure)
includeNoITS = kFALSE;
} else if (runPeriod.Contains("lhc12a15a") || runPeriod == "lhc12a15f" || runPeriod == "lhc12a15g") {
aodTask->SetAODfilterBits(256,16); // hybrid tracks
aodTask->SetMC(kTRUE);
includeNoITS = kTRUE;
} else if (runPeriod.Contains(":")) {
TObjArray *arr = runPeriod.Tokenize(":");
TString arg1(arr->At(0)->GetName());
TString arg2("-1");
if (arr->GetEntries()>1)
arg2 = arr->At(1)->GetName();
if (arr->GetEntries()>2) {
TString arg3 = arr->At(2)->GetName();
if (arg3.Contains("includeNoITS=kTRUE"))
includeNoITS=kTRUE;
if (arg3.Contains("doProp=kTRUE"))
doProp=kTRUE;
}
aodTask->SetAODfilterBits(arg1.Atoi(),arg2.Atoi());
delete arr;
} else {
if (!runPeriod.IsNull())
::Warning("Run period %s not known. It will use IsHybridGlobalConstrainedGlobal.", runPeriod.Data());
}
aodTask->SetIncludeNoITS(includeNoITS);
aodTask->SetDoPropagation(doProp);
//-------------------------------------------------------
// Final settings, pass to manager and set the containers
//-------------------------------------------------------
mgr->AddTask(aodTask);
// Create containers for input/output
AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
mgr->ConnectInput(aodTask, 0, cinput1 );
return aodTask;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: XMLTextPropertySetContext.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: dvo $ $Date: 2002-09-09 17:12:18 $
*
* 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 _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _XMLOFF_XMLTEXTPROPERTYSETCONTEXT_HXX
#include "XMLTextPropertySetContext.hxx"
#endif
#ifndef _XMLTEXTCOLUMNSCONTEXT_HXX
#include "XMLTextColumnsContext.hxx"
#endif
#ifndef _XMLBACKGROUNDIMAGECONTEXT_HXX
#include "XMLBackgroundImageContext.hxx"
#endif
#ifndef _XMLOFF_XMLSECTIONFOOTNOTECONFIGIMPORT_HXX
#include "XMLSectionFootnoteConfigImport.hxx"
#endif
#ifndef _XMLOFF_TXTPRMAP_HXX
#include "txtprmap.hxx"
#endif
#ifndef _XMLOFF_XMLTABI_HXX
#include "xmltabi.hxx"
#endif
#ifndef _XMLOFF_TXTDROPI_HXX
#include "txtdropi.hxx"
#endif
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star;
XMLTextPropertySetContext::XMLTextPropertySetContext(
SvXMLImport& rImport, sal_uInt16 nPrfx,
const OUString& rLName,
const Reference< xml::sax::XAttributeList > & xAttrList,
::std::vector< XMLPropertyState > &rProps,
const UniReference < SvXMLImportPropertyMapper > &rMap,
OUString& rDCTextStyleName ) :
SvXMLPropertySetContext( rImport, nPrfx, rLName, xAttrList, rProps, rMap ),
rDropCapTextStyleName( rDCTextStyleName )
{
}
XMLTextPropertySetContext::~XMLTextPropertySetContext()
{
}
SvXMLImportContext *XMLTextPropertySetContext::CreateChildContext(
sal_uInt16 nPrefix,
const OUString& rLocalName,
const Reference< xml::sax::XAttributeList > & xAttrList,
::std::vector< XMLPropertyState > &rProperties,
const XMLPropertyState& rProp )
{
SvXMLImportContext *pContext = 0;
switch( xMapper->getPropertySetMapper()
->GetEntryContextId( rProp.mnIndex ) )
{
case CTF_TABSTOP:
pContext = new SvxXMLTabStopImportContext( GetImport(), nPrefix,
rLocalName, rProp,
rProperties );
break;
case CTF_TEXTCOLUMNS:
#ifndef SVX_LIGHT
pContext = new XMLTextColumnsContext( GetImport(), nPrefix,
rLocalName, xAttrList, rProp,
rProperties );
#else
// create default context to skip content
pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
#endif // #ifndef SVX_LIGHT
break;
case CTF_DROPCAPFORMAT:
{
DBG_ASSERT( rProp.mnIndex >= 2 &&
CTF_DROPCAPWHOLEWORD == xMapper->getPropertySetMapper()
->GetEntryContextId( rProp.mnIndex-2 ),
"invalid property map!");
XMLTextDropCapImportContext *pDCContext =
new XMLTextDropCapImportContext( GetImport(), nPrefix,
rLocalName, xAttrList,
rProp,
rProp.mnIndex-2,
rProperties );
rDropCapTextStyleName = pDCContext->GetStyleName();
pContext = pDCContext;
}
break;
case CTF_BACKGROUND_URL:
{
DBG_ASSERT( rProp.mnIndex >= 2 &&
CTF_BACKGROUND_POS == xMapper->getPropertySetMapper()
->GetEntryContextId( rProp.mnIndex-2 ) &&
CTF_BACKGROUND_FILTER == xMapper->getPropertySetMapper()
->GetEntryContextId( rProp.mnIndex-1 ),
"invalid property map!");
// #99657# Transparency might be there as well... but doesn't have
// to. Thus, this is checked with an if, rather than with an assertion.
sal_Int32 nTranspIndex = -1;
if( (rProp.mnIndex >= 3) &&
( CTF_BACKGROUND_TRANSPARENCY ==
xMapper->getPropertySetMapper()->GetEntryContextId(
rProp.mnIndex-3 ) ) )
nTranspIndex = rProp.mnIndex-3;
pContext =
new XMLBackgroundImageContext( GetImport(), nPrefix,
rLocalName, xAttrList,
rProp,
rProp.mnIndex-2,
rProp.mnIndex-1,
nTranspIndex,
rProperties );
}
break;
#ifndef SVX_LIGHT
case CTF_SECTION_FOOTNOTE_END:
pContext = new XMLSectionFootnoteConfigImport(
GetImport(), nPrefix, rLocalName, rProperties,
xMapper->getPropertySetMapper(), rProp.mnIndex);
break;
case CTF_SECTION_ENDNOTE_END:
pContext = new XMLSectionFootnoteConfigImport(
GetImport(), nPrefix, rLocalName, rProperties,
xMapper->getPropertySetMapper(), rProp.mnIndex);
break;
#endif // #ifndef SVX_LIGHT
}
if( !pContext )
pContext = SvXMLPropertySetContext::CreateChildContext( nPrefix, rLocalName,
xAttrList,
rProperties, rProp );
return pContext;
}
<commit_msg>INTEGRATION: CWS oasis (1.8.250); FILE MERGED 2004/04/21 07:27:25 mib 1.8.250.1: - separated attribute lists for <*-properties> elements on import (#i20153#) - replaced "style:text-backgroubnd-color" with "fo:background-color"<commit_after>/*************************************************************************
*
* $RCSfile: XMLTextPropertySetContext.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2004-07-13 08:38:40 $
*
* 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 _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _XMLOFF_XMLTEXTPROPERTYSETCONTEXT_HXX
#include "XMLTextPropertySetContext.hxx"
#endif
#ifndef _XMLTEXTCOLUMNSCONTEXT_HXX
#include "XMLTextColumnsContext.hxx"
#endif
#ifndef _XMLBACKGROUNDIMAGECONTEXT_HXX
#include "XMLBackgroundImageContext.hxx"
#endif
#ifndef _XMLOFF_XMLSECTIONFOOTNOTECONFIGIMPORT_HXX
#include "XMLSectionFootnoteConfigImport.hxx"
#endif
#ifndef _XMLOFF_TXTPRMAP_HXX
#include "txtprmap.hxx"
#endif
#ifndef _XMLOFF_XMLTABI_HXX
#include "xmltabi.hxx"
#endif
#ifndef _XMLOFF_TXTDROPI_HXX
#include "txtdropi.hxx"
#endif
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star;
XMLTextPropertySetContext::XMLTextPropertySetContext(
SvXMLImport& rImport, sal_uInt16 nPrfx,
const OUString& rLName,
const Reference< xml::sax::XAttributeList > & xAttrList,
sal_uInt32 nFamily,
::std::vector< XMLPropertyState > &rProps,
const UniReference < SvXMLImportPropertyMapper > &rMap,
OUString& rDCTextStyleName ) :
SvXMLPropertySetContext( rImport, nPrfx, rLName, xAttrList, nFamily,
rProps, rMap ),
rDropCapTextStyleName( rDCTextStyleName )
{
}
XMLTextPropertySetContext::~XMLTextPropertySetContext()
{
}
SvXMLImportContext *XMLTextPropertySetContext::CreateChildContext(
sal_uInt16 nPrefix,
const OUString& rLocalName,
const Reference< xml::sax::XAttributeList > & xAttrList,
::std::vector< XMLPropertyState > &rProperties,
const XMLPropertyState& rProp )
{
SvXMLImportContext *pContext = 0;
switch( xMapper->getPropertySetMapper()
->GetEntryContextId( rProp.mnIndex ) )
{
case CTF_TABSTOP:
pContext = new SvxXMLTabStopImportContext( GetImport(), nPrefix,
rLocalName, rProp,
rProperties );
break;
case CTF_TEXTCOLUMNS:
#ifndef SVX_LIGHT
pContext = new XMLTextColumnsContext( GetImport(), nPrefix,
rLocalName, xAttrList, rProp,
rProperties );
#else
// create default context to skip content
pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
#endif // #ifndef SVX_LIGHT
break;
case CTF_DROPCAPFORMAT:
{
DBG_ASSERT( rProp.mnIndex >= 2 &&
CTF_DROPCAPWHOLEWORD == xMapper->getPropertySetMapper()
->GetEntryContextId( rProp.mnIndex-2 ),
"invalid property map!");
XMLTextDropCapImportContext *pDCContext =
new XMLTextDropCapImportContext( GetImport(), nPrefix,
rLocalName, xAttrList,
rProp,
rProp.mnIndex-2,
rProperties );
rDropCapTextStyleName = pDCContext->GetStyleName();
pContext = pDCContext;
}
break;
case CTF_BACKGROUND_URL:
{
DBG_ASSERT( rProp.mnIndex >= 2 &&
CTF_BACKGROUND_POS == xMapper->getPropertySetMapper()
->GetEntryContextId( rProp.mnIndex-2 ) &&
CTF_BACKGROUND_FILTER == xMapper->getPropertySetMapper()
->GetEntryContextId( rProp.mnIndex-1 ),
"invalid property map!");
// #99657# Transparency might be there as well... but doesn't have
// to. Thus, this is checked with an if, rather than with an assertion.
sal_Int32 nTranspIndex = -1;
if( (rProp.mnIndex >= 3) &&
( CTF_BACKGROUND_TRANSPARENCY ==
xMapper->getPropertySetMapper()->GetEntryContextId(
rProp.mnIndex-3 ) ) )
nTranspIndex = rProp.mnIndex-3;
pContext =
new XMLBackgroundImageContext( GetImport(), nPrefix,
rLocalName, xAttrList,
rProp,
rProp.mnIndex-2,
rProp.mnIndex-1,
nTranspIndex,
rProperties );
}
break;
#ifndef SVX_LIGHT
case CTF_SECTION_FOOTNOTE_END:
pContext = new XMLSectionFootnoteConfigImport(
GetImport(), nPrefix, rLocalName, rProperties,
xMapper->getPropertySetMapper(), rProp.mnIndex);
break;
case CTF_SECTION_ENDNOTE_END:
pContext = new XMLSectionFootnoteConfigImport(
GetImport(), nPrefix, rLocalName, rProperties,
xMapper->getPropertySetMapper(), rProp.mnIndex);
break;
#endif // #ifndef SVX_LIGHT
}
if( !pContext )
pContext = SvXMLPropertySetContext::CreateChildContext( nPrefix, rLocalName,
xAttrList,
rProperties, rProp );
return pContext;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <array>
#include <vector>
#include <cassert>
#include <iterator>
#include "days.hpp"
namespace {
std::array<int, 4> base_pattern{0, 1, 0, -1};
int get_modifier(int rank, int pos) {
pos += 1;
pos /= rank + 1;
return base_pattern[pos % 4];
}
std::vector<int> read_input(std::istream &input) {
std::vector<int> result;
for (char c; input >> c;) {
assert(std::isdigit(c));
result.push_back(c - '0');
}
return result;
}
std::vector<int> advance(const std::vector<int>& numbers) {
std::vector<int> new_numbers;
new_numbers.reserve(numbers.size());
for (int rank = 0; rank < numbers.size(); ++rank) {
int n = 0;
for (int pos = rank; pos < numbers.size(); ++pos) {
n += get_modifier(rank, pos) * numbers[pos];
}
n = std::abs(n % 10);
new_numbers.push_back(n);
}
return new_numbers;
}
}
void aoc2019::day16_part1(std::istream &input, std::ostream &output) {
auto numbers = read_input(input);
for (int i = 0; i < 100; ++i) {
std::vector<int> new_numbers;
new_numbers.reserve(numbers.size());
for (int rank = 0; rank < numbers.size(); ++rank) {
int n = 0;
for (int pos = rank; pos < numbers.size(); ++pos) {
n += get_modifier(rank, pos) * numbers[pos];
}
n = std::abs(n % 10);
new_numbers.push_back(n);
}
numbers = new_numbers;
}
std::copy(numbers.begin(), numbers.begin() + 8, std::ostream_iterator<int>(output));
output << std::endl;
}
void aoc2019::day16_part2(std::istream &input, std::ostream &output) {
auto numbers = read_input(input);
const auto initial_size = numbers.size();
constexpr auto repetitions = 10000;
numbers.reserve(repetitions * numbers.size());
int offset = 0;
for (int i = 0; i < 7; ++i) {
offset *= 10;
offset += numbers[i];
}
for (int i = 1; i < repetitions; ++i) {
std::copy(numbers.begin(), numbers.begin() + initial_size, std::back_inserter(numbers));
}
numbers = std::vector(numbers.begin() + offset, numbers.end());
for (int i = 0; i < 100; ++i) {
std::vector<int> partial_sums(numbers.size());
std::vector<int> new_numbers(numbers.size());
partial_sums[0] = numbers[0];
for (int j = 1; j < numbers.size(); ++j) {
partial_sums[j] = partial_sums[j - 1] + numbers[j];
}
for (int j = 0; j < numbers.size(); ++j) {
new_numbers[j] = partial_sums.back() - partial_sums[j] + numbers[j];
}
}
std::copy(numbers.begin(), numbers.begin() + 8, std::ostream_iterator<int>(output));
}
<commit_msg>Implement day 16 part 2.<commit_after>#include <iostream>
#include <array>
#include <vector>
#include <cassert>
#include <iterator>
#include "days.hpp"
namespace {
std::array<int, 4> base_pattern{0, 1, 0, -1};
int get_modifier(int rank, int pos) {
pos += 1;
pos /= rank + 1;
return base_pattern[pos % 4];
}
std::vector<int> read_input(std::istream &input) {
std::vector<int> result;
for (char c; input >> c;) {
assert(std::isdigit(c));
result.push_back(c - '0');
}
return result;
}
std::vector<int> partial_sum(const std::vector<int> &numbers) {
std::vector<int> partial_sums(numbers.size());
partial_sums[0] = numbers[0];
for (int j = 1; j < numbers.size(); ++j) {
partial_sums[j] = partial_sums[j - 1] + numbers[j];
}
return partial_sums;
}
std::vector<int> advance(const std::vector<int>& numbers) {
std::vector<int> new_numbers;
new_numbers.reserve(numbers.size());
for (int rank = 0; rank < numbers.size(); ++rank) {
int n = 0;
for (int pos = rank; pos < numbers.size(); ++pos) {
n += get_modifier(rank, pos) * numbers[pos];
}
n = std::abs(n % 10);
new_numbers.push_back(n);
}
return new_numbers;
}
}
void aoc2019::day16_part1(std::istream &input, std::ostream &output) {
auto numbers = read_input(input);
for (int i = 0; i < 100; ++i) {
std::vector<int> new_numbers;
new_numbers.reserve(numbers.size());
for (int rank = 0; rank < numbers.size(); ++rank) {
int n = 0;
for (int pos = rank; pos < numbers.size(); ++pos) {
n += get_modifier(rank, pos) * numbers[pos];
}
n = std::abs(n % 10);
new_numbers.push_back(n);
}
numbers = new_numbers;
}
std::copy(numbers.begin(), numbers.begin() + 8, std::ostream_iterator<int>(output));
output << std::endl;
}
void aoc2019::day16_part2(std::istream &input, std::ostream &output) {
auto numbers = read_input(input);
const auto initial_size = numbers.size();
constexpr auto repetitions = 10000;
numbers.reserve(repetitions * numbers.size());
int offset = 0;
for (int i = 0; i < 7; ++i) {
offset *= 10;
offset += numbers[i];
}
for (int i = 1; i < repetitions; ++i) {
std::copy(numbers.begin(), numbers.begin() + initial_size, std::back_inserter(numbers));
}
numbers = std::vector(numbers.begin() + offset, numbers.end());
for (int i = 0; i < 100; ++i) {
std::vector<int> partial_sums = partial_sum(numbers);
std::vector<int> new_numbers(numbers.size());
for (int j = 0; j < numbers.size(); ++j) {
int n = partial_sums.back() - partial_sums[j] + numbers[j];
new_numbers[j] = std::abs(n % 10);
}
numbers = new_numbers;
}
std::copy(numbers.begin(), numbers.begin() + 8, std::ostream_iterator<int>(output));
output << std::endl;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: basicmigration.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-01-27 14:26:27 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _DESKTOP_BASICMIGRATION_HXX_
#include "basicmigration.hxx"
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _UTL_BOOTSTRAP_HXX
#include <unotools/bootstrap.hxx>
#endif
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
//.........................................................................
namespace migration
{
//.........................................................................
static ::rtl::OUString sSourceUserBasic = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/user/basic" ) );
static ::rtl::OUString sTargetUserBasic = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/user/__basic_70" ) );
// =============================================================================
// component operations
// =============================================================================
::rtl::OUString BasicMigration_getImplementationName()
{
static ::rtl::OUString* pImplName = 0;
if ( !pImplName )
{
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if ( !pImplName )
{
static ::rtl::OUString aImplName( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.desktop.migration.Basic" ) );
pImplName = &aImplName;
}
}
return *pImplName;
}
// -----------------------------------------------------------------------------
Sequence< ::rtl::OUString > BasicMigration_getSupportedServiceNames()
{
static Sequence< ::rtl::OUString >* pNames = 0;
if ( !pNames )
{
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if ( !pNames )
{
static Sequence< ::rtl::OUString > aNames(1);
aNames.getArray()[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.migration.Basic" ) );
pNames = &aNames;
}
}
return *pNames;
}
// =============================================================================
// BasicMigration
// =============================================================================
BasicMigration::BasicMigration()
{
}
// -----------------------------------------------------------------------------
BasicMigration::~BasicMigration()
{
}
// -----------------------------------------------------------------------------
TStringVectorPtr BasicMigration::getFiles( const ::rtl::OUString& rBaseURL ) const
{
TStringVectorPtr aResult( new TStringVector );
::osl::Directory aDir( rBaseURL);
if ( aDir.open() == ::osl::FileBase::E_None )
{
// iterate over directory content
TStringVector aSubDirs;
::osl::DirectoryItem aItem;
while ( aDir.getNextItem( aItem ) == ::osl::FileBase::E_None )
{
::osl::FileStatus aFileStatus( FileStatusMask_FileURL );
if ( aItem.getFileStatus( aFileStatus ) == ::osl::FileBase::E_None )
{
if ( aFileStatus.getFileType() == ::osl::FileStatus::Directory )
aSubDirs.push_back( aFileStatus.getFileURL() );
else
aResult->push_back( aFileStatus.getFileURL() );
}
}
// iterate recursive over subfolders
TStringVector::const_iterator aI = aSubDirs.begin();
while ( aI != aSubDirs.end() )
{
TStringVectorPtr aSubResult = getFiles( *aI );
aResult->insert( aResult->end(), aSubResult->begin(), aSubResult->end() );
++aI;
}
}
return aResult;
}
// -----------------------------------------------------------------------------
::osl::FileBase::RC BasicMigration::checkAndCreateDirectory( INetURLObject& rDirURL )
{
::osl::FileBase::RC aResult = ::osl::Directory::create( rDirURL.GetMainURL( INetURLObject::DECODE_TO_IURI ) );
if ( aResult == ::osl::FileBase::E_NOENT )
{
INetURLObject aBaseURL( rDirURL );
aBaseURL.removeSegment();
checkAndCreateDirectory( aBaseURL );
return ::osl::Directory::create( rDirURL.GetMainURL( INetURLObject::DECODE_TO_IURI ) );
}
else
{
return aResult;
}
}
// -----------------------------------------------------------------------------
void BasicMigration::copyFiles()
{
::rtl::OUString sTargetDir;
::utl::Bootstrap::PathStatus aStatus = ::utl::Bootstrap::locateUserInstallation( sTargetDir );
if ( aStatus == ::utl::Bootstrap::PATH_EXISTS )
{
sTargetDir += sTargetUserBasic;
TStringVectorPtr aFileList = getFiles( m_sSourceDir );
TStringVector::const_iterator aI = aFileList->begin();
while ( aI != aFileList->end() )
{
::rtl::OUString sLocalName = aI->copy( m_sSourceDir.getLength() );
::rtl::OUString sTargetName = sTargetDir + sLocalName;
INetURLObject aURL( sTargetName );
aURL.removeSegment();
checkAndCreateDirectory( aURL );
::osl::FileBase::RC aResult = ::osl::File::copy( *aI, sTargetName );
if ( aResult != ::osl::FileBase::E_None )
{
::rtl::OString aMsg( "BasicMigration::copyFiles: cannot copy " );
aMsg += ::rtl::OUStringToOString( *aI, RTL_TEXTENCODING_UTF8 ) + " to "
+ ::rtl::OUStringToOString( sTargetName, RTL_TEXTENCODING_UTF8 );
OSL_ENSURE( sal_False, aMsg.getStr() );
}
++aI;
}
}
else
{
OSL_ENSURE( sal_False, "BasicMigration::copyFiles: no user installation!" );
}
}
// -----------------------------------------------------------------------------
// XServiceInfo
// -----------------------------------------------------------------------------
::rtl::OUString BasicMigration::getImplementationName() throw (RuntimeException)
{
return BasicMigration_getImplementationName();
}
// -----------------------------------------------------------------------------
sal_Bool BasicMigration::supportsService( const ::rtl::OUString& rServiceName ) throw (RuntimeException)
{
Sequence< ::rtl::OUString > aNames( getSupportedServiceNames() );
const ::rtl::OUString* pNames = aNames.getConstArray();
const ::rtl::OUString* pEnd = pNames + aNames.getLength();
for ( ; pNames != pEnd && !pNames->equals( rServiceName ); ++pNames )
;
return pNames != pEnd;
}
// -----------------------------------------------------------------------------
Sequence< ::rtl::OUString > BasicMigration::getSupportedServiceNames() throw (RuntimeException)
{
return BasicMigration_getSupportedServiceNames();
}
// -----------------------------------------------------------------------------
// XInitialization
// -----------------------------------------------------------------------------
void BasicMigration::initialize( const Sequence< Any >& aArguments ) throw (Exception, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
const Any* pIter = aArguments.getConstArray();
const Any* pEnd = pIter + aArguments.getLength();
for ( ; pIter != pEnd ; ++pIter )
{
beans::NamedValue aValue;
*pIter >>= aValue;
if ( aValue.Name.equalsAscii( "UserData" ) )
{
sal_Bool bSuccess = aValue.Value >>= m_sSourceDir;
OSL_ENSURE( bSuccess == sal_True, "BasicMigration::initialize: argument UserData has wrong type!" );
m_sSourceDir += sSourceUserBasic;
break;
}
}
}
// -----------------------------------------------------------------------------
// XJob
// -----------------------------------------------------------------------------
Any BasicMigration::execute( const Sequence< beans::NamedValue >& Arguments )
throw (lang::IllegalArgumentException, Exception, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
copyFiles();
return Any();
}
// =============================================================================
// component operations
// =============================================================================
Reference< XInterface > SAL_CALL BasicMigration_create(
Reference< XComponentContext > const & xContext )
SAL_THROW( () )
{
return static_cast< lang::XTypeProvider * >( new BasicMigration() );
}
// -----------------------------------------------------------------------------
//.........................................................................
} // namespace migration
//.........................................................................
<commit_msg>INTEGRATION: CWS fwkfinal8 (1.2.68); FILE MERGED 2005/04/05 15:28:42 tbe 1.2.68.1: #i45987# import of settings from 1.1.x fails<commit_after>/*************************************************************************
*
* $RCSfile: basicmigration.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2005-04-18 12:22:55 $
*
* 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 _DESKTOP_BASICMIGRATION_HXX_
#include "basicmigration.hxx"
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _UTL_BOOTSTRAP_HXX
#include <unotools/bootstrap.hxx>
#endif
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
//.........................................................................
namespace migration
{
//.........................................................................
static ::rtl::OUString sSourceUserBasic = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/user/basic" ) );
static ::rtl::OUString sTargetUserBasic = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/user/__basic_70" ) );
// =============================================================================
// component operations
// =============================================================================
::rtl::OUString BasicMigration_getImplementationName()
{
static ::rtl::OUString* pImplName = 0;
if ( !pImplName )
{
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if ( !pImplName )
{
static ::rtl::OUString aImplName( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.desktop.migration.Basic" ) );
pImplName = &aImplName;
}
}
return *pImplName;
}
// -----------------------------------------------------------------------------
Sequence< ::rtl::OUString > BasicMigration_getSupportedServiceNames()
{
static Sequence< ::rtl::OUString >* pNames = 0;
if ( !pNames )
{
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if ( !pNames )
{
static Sequence< ::rtl::OUString > aNames(1);
aNames.getArray()[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.migration.Basic" ) );
pNames = &aNames;
}
}
return *pNames;
}
// =============================================================================
// BasicMigration
// =============================================================================
BasicMigration::BasicMigration()
{
}
// -----------------------------------------------------------------------------
BasicMigration::~BasicMigration()
{
}
// -----------------------------------------------------------------------------
TStringVectorPtr BasicMigration::getFiles( const ::rtl::OUString& rBaseURL ) const
{
TStringVectorPtr aResult( new TStringVector );
::osl::Directory aDir( rBaseURL);
if ( aDir.open() == ::osl::FileBase::E_None )
{
// iterate over directory content
TStringVector aSubDirs;
::osl::DirectoryItem aItem;
while ( aDir.getNextItem( aItem ) == ::osl::FileBase::E_None )
{
::osl::FileStatus aFileStatus( FileStatusMask_Type | FileStatusMask_FileURL );
if ( aItem.getFileStatus( aFileStatus ) == ::osl::FileBase::E_None )
{
if ( aFileStatus.getFileType() == ::osl::FileStatus::Directory )
aSubDirs.push_back( aFileStatus.getFileURL() );
else
aResult->push_back( aFileStatus.getFileURL() );
}
}
// iterate recursive over subfolders
TStringVector::const_iterator aI = aSubDirs.begin();
while ( aI != aSubDirs.end() )
{
TStringVectorPtr aSubResult = getFiles( *aI );
aResult->insert( aResult->end(), aSubResult->begin(), aSubResult->end() );
++aI;
}
}
return aResult;
}
// -----------------------------------------------------------------------------
::osl::FileBase::RC BasicMigration::checkAndCreateDirectory( INetURLObject& rDirURL )
{
::osl::FileBase::RC aResult = ::osl::Directory::create( rDirURL.GetMainURL( INetURLObject::DECODE_TO_IURI ) );
if ( aResult == ::osl::FileBase::E_NOENT )
{
INetURLObject aBaseURL( rDirURL );
aBaseURL.removeSegment();
checkAndCreateDirectory( aBaseURL );
return ::osl::Directory::create( rDirURL.GetMainURL( INetURLObject::DECODE_TO_IURI ) );
}
else
{
return aResult;
}
}
// -----------------------------------------------------------------------------
void BasicMigration::copyFiles()
{
::rtl::OUString sTargetDir;
::utl::Bootstrap::PathStatus aStatus = ::utl::Bootstrap::locateUserInstallation( sTargetDir );
if ( aStatus == ::utl::Bootstrap::PATH_EXISTS )
{
sTargetDir += sTargetUserBasic;
TStringVectorPtr aFileList = getFiles( m_sSourceDir );
TStringVector::const_iterator aI = aFileList->begin();
while ( aI != aFileList->end() )
{
::rtl::OUString sLocalName = aI->copy( m_sSourceDir.getLength() );
::rtl::OUString sTargetName = sTargetDir + sLocalName;
INetURLObject aURL( sTargetName );
aURL.removeSegment();
checkAndCreateDirectory( aURL );
::osl::FileBase::RC aResult = ::osl::File::copy( *aI, sTargetName );
if ( aResult != ::osl::FileBase::E_None )
{
::rtl::OString aMsg( "BasicMigration::copyFiles: cannot copy " );
aMsg += ::rtl::OUStringToOString( *aI, RTL_TEXTENCODING_UTF8 ) + " to "
+ ::rtl::OUStringToOString( sTargetName, RTL_TEXTENCODING_UTF8 );
OSL_ENSURE( sal_False, aMsg.getStr() );
}
++aI;
}
}
else
{
OSL_ENSURE( sal_False, "BasicMigration::copyFiles: no user installation!" );
}
}
// -----------------------------------------------------------------------------
// XServiceInfo
// -----------------------------------------------------------------------------
::rtl::OUString BasicMigration::getImplementationName() throw (RuntimeException)
{
return BasicMigration_getImplementationName();
}
// -----------------------------------------------------------------------------
sal_Bool BasicMigration::supportsService( const ::rtl::OUString& rServiceName ) throw (RuntimeException)
{
Sequence< ::rtl::OUString > aNames( getSupportedServiceNames() );
const ::rtl::OUString* pNames = aNames.getConstArray();
const ::rtl::OUString* pEnd = pNames + aNames.getLength();
for ( ; pNames != pEnd && !pNames->equals( rServiceName ); ++pNames )
;
return pNames != pEnd;
}
// -----------------------------------------------------------------------------
Sequence< ::rtl::OUString > BasicMigration::getSupportedServiceNames() throw (RuntimeException)
{
return BasicMigration_getSupportedServiceNames();
}
// -----------------------------------------------------------------------------
// XInitialization
// -----------------------------------------------------------------------------
void BasicMigration::initialize( const Sequence< Any >& aArguments ) throw (Exception, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
const Any* pIter = aArguments.getConstArray();
const Any* pEnd = pIter + aArguments.getLength();
for ( ; pIter != pEnd ; ++pIter )
{
beans::NamedValue aValue;
*pIter >>= aValue;
if ( aValue.Name.equalsAscii( "UserData" ) )
{
sal_Bool bSuccess = aValue.Value >>= m_sSourceDir;
OSL_ENSURE( bSuccess == sal_True, "BasicMigration::initialize: argument UserData has wrong type!" );
m_sSourceDir += sSourceUserBasic;
break;
}
}
}
// -----------------------------------------------------------------------------
// XJob
// -----------------------------------------------------------------------------
Any BasicMigration::execute( const Sequence< beans::NamedValue >& Arguments )
throw (lang::IllegalArgumentException, Exception, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
copyFiles();
return Any();
}
// =============================================================================
// component operations
// =============================================================================
Reference< XInterface > SAL_CALL BasicMigration_create(
Reference< XComponentContext > const & xContext )
SAL_THROW( () )
{
return static_cast< lang::XTypeProvider * >( new BasicMigration() );
}
// -----------------------------------------------------------------------------
//.........................................................................
} // namespace migration
//.........................................................................
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright RTK Consortium
*
* 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.txt
*
* 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.
*
*=========================================================================*/
#ifndef __rtkCudaSARTConeBeamReconstructionFilter_cxx
#define __rtkCudaSARTConeBeamReconstructionFilter_cxx
#include "rtkJosephForwardProjectionImageFilter.h"
#include "rtkJosephBackProjectionImageFilter.h"
#include "rtkCudaForwardProjectionImageFilter.h"
#include "rtkCudaBackProjectionImageFilter.h"
#include "rtkCudaSARTConeBeamReconstructionFilter.h"
#include "itkImageFileWriter.h"
namespace rtk
{
CudaSARTConeBeamReconstructionFilter
::CudaSARTConeBeamReconstructionFilter():
m_ExplicitGPUMemoryManagementFlag(false)
{
// Create each filter which are specific for cuda
m_ForwardProjectionFilter = ForwardProjectionFilterType::New();
BackProjectionFilterType::Pointer p = BackProjectionFilterType::New();
this->SetBackProjectionFilter(p.GetPointer());
//Permanent internal connections
m_ForwardProjectionFilter->SetInput( 0, m_ZeroMultiplyFilter->GetOutput() );
m_SubtractFilter->SetInput(1, m_ForwardProjectionFilter->GetOutput() );
}
void
CudaSARTConeBeamReconstructionFilter
::GenerateData()
{
// Init GPU memory
if(!m_ExplicitGPUMemoryManagementFlag);
this->InitDevice();
// Run reconstruction
this->Superclass::GenerateData();
// Transfer result to CPU image
if(!m_ExplicitGPUMemoryManagementFlag);
this->CleanUpDevice();
}
void
CudaSARTConeBeamReconstructionFilter
::InitDevice()
{
//Nothing to do, memory control internally managed
}
void
CudaSARTConeBeamReconstructionFilter
::CleanUpDevice()
{
//Nothing to do, memory control internally managed
}
} // end namespace rtk
#endif // __rtkCudaSARTConeBeamReconstructionFilter_cxx
<commit_msg>Remove erroneous semi-colons<commit_after>/*=========================================================================
*
* Copyright RTK Consortium
*
* 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.txt
*
* 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.
*
*=========================================================================*/
#ifndef __rtkCudaSARTConeBeamReconstructionFilter_cxx
#define __rtkCudaSARTConeBeamReconstructionFilter_cxx
#include "rtkJosephForwardProjectionImageFilter.h"
#include "rtkJosephBackProjectionImageFilter.h"
#include "rtkCudaForwardProjectionImageFilter.h"
#include "rtkCudaBackProjectionImageFilter.h"
#include "rtkCudaSARTConeBeamReconstructionFilter.h"
#include "itkImageFileWriter.h"
namespace rtk
{
CudaSARTConeBeamReconstructionFilter
::CudaSARTConeBeamReconstructionFilter():
m_ExplicitGPUMemoryManagementFlag(false)
{
// Create each filter which are specific for cuda
m_ForwardProjectionFilter = ForwardProjectionFilterType::New();
BackProjectionFilterType::Pointer p = BackProjectionFilterType::New();
this->SetBackProjectionFilter(p.GetPointer());
//Permanent internal connections
m_ForwardProjectionFilter->SetInput( 0, m_ZeroMultiplyFilter->GetOutput() );
m_SubtractFilter->SetInput(1, m_ForwardProjectionFilter->GetOutput() );
}
void
CudaSARTConeBeamReconstructionFilter
::GenerateData()
{
// Init GPU memory
if(!m_ExplicitGPUMemoryManagementFlag)
this->InitDevice();
// Run reconstruction
this->Superclass::GenerateData();
// Transfer result to CPU image
if(!m_ExplicitGPUMemoryManagementFlag)
this->CleanUpDevice();
}
void
CudaSARTConeBeamReconstructionFilter
::InitDevice()
{
//Nothing to do, memory control internally managed
}
void
CudaSARTConeBeamReconstructionFilter
::CleanUpDevice()
{
//Nothing to do, memory control internally managed
}
} // end namespace rtk
#endif // __rtkCudaSARTConeBeamReconstructionFilter_cxx
<|endoftext|> |
<commit_before>//
// websocket.hpp
// fibio-http
//
// Created by Chen Xu on 15/08/28.
// Copyright (c) 2015 0d0a.com. All rights reserved.
//
#ifndef fibio_http_common_websocket_hpp
#define fibio_http_common_websocket_hpp
#include <cstdint>
#include <iostream>
namespace fibio { namespace http { namespace websocket {
constexpr size_t DEFAULT_MAX_PAYLOAD_LEN=4096;
constexpr size_t DEFAULT_MAX_MESSAGE_SIZE=65536;
enum class OPCODE : uint8_t {
CONTINUATION = 0,
TEXT = 1,
BINARY = 2,
CLOSE = 8,
PING = 9,
PONG = 10,
INVALID = 255,
};
typedef std::array<uint8_t, 4> mask_type;
struct frame_header {
bool fin() const { return (data_[0] & 0x80)!=0; }
void fin(bool v) { if(v) { data_[0] |= 0x80; } else { data_[0] &= 0x7F; } }
bool rsv1() const { return (data_[0] & 0x40)!=0; }
void rsv1(bool v) { if(v) { data_[0] |= 0x40; } else { data_[0] &= 0xBF; } }
bool rsv2() const { return (data_[0] & 0x20)!=0; }
void rsv2(bool v) { if(v) { data_[0] |= 0x20; } else { data_[0] &= 0xDF; } }
bool rsv3() const { return (data_[0] & 0x10)!=0; }
void rsv3(bool v) { if(v) { data_[0] |= 0x10; } else { data_[0] &= 0xEF; } }
OPCODE opcode() const { return OPCODE(data_[0] & 0x0F); }
void opcode(OPCODE v) { data_[0] &= 0xF0; data_[0] |= uint8_t(v)&0x0F; }
bool mask() const { return (data_[1] & 0x80)!=0; }
void mask(bool v) { if(v) { data_[1] |= 0x80; } else { data_[1] &= 0x7F; } }
uint8_t payload_len_7() const { return data_[1] & 0x7F; }
void payload_len_7(uint8_t v) { data_[1] &= 0x80; data_[1] |= v&0x7F; }
uint16_t ext_payload_len_16() const { return data_[2]<<8 | data_[3]; }
void ext_payload_len_16(uint16_t v) { data_[2] = v>>8; data_[3] = v&0xFF; }
uint64_t ext_payload_len_64() const {
uint64_t ret = uint64_t(data_[2]) << 56
| uint64_t(data_[3]) << 48
| uint64_t(data_[4]) << 40
| uint64_t(data_[5]) << 32
| uint64_t(data_[6]) << 24
| uint64_t(data_[7]) << 16
| uint64_t(data_[8]) << 8
| uint64_t(data_[9]);
return ret;
}
void ext_payload_len_64(uint64_t v) {
data_[2] = v>>56 & 0xFF;
data_[3] = v>>48 & 0xFF;
data_[4] = v>>40 & 0xFF;
data_[5] = v>>32 & 0xFF;
data_[6] = v>>24 & 0xFF;
data_[7] = v>>16 & 0xFF;
data_[8] = v>>8 & 0xFF;
data_[9] = v & 0xFF;
}
uint64_t payload_len() const {
uint64_t ret=payload_len_7();
if(ret==126) return ext_payload_len_16();
if(ret==127) return ext_payload_len_64();
return ret;
}
void internal_set_payload_len(uint64_t v) {
if(v>0xFFFF) {
// 8 bytes
payload_len_7(127);
ext_payload_len_64(v);
} else if(v>=126) {
// 2 bytes
payload_len_7(126);
ext_payload_len_16(v);
} else {
payload_len_7(v);
}
}
void payload_len(uint64_t v) {
if(mask()) {
// Preserve masking key
mask_type m=masking_key();
internal_set_payload_len(v);
masking_key(m);
} else {
internal_set_payload_len(v);
}
}
uint8_t payload_len_end_idx() const {
uint8_t pl=payload_len_7();
if(pl<126) return 2;
if(pl<127) return 4;
return 10;
}
mask_type masking_key() const {
uint8_t idx=payload_len_end_idx();
return mask_type{{
data_[idx],
data_[idx+1],
data_[idx+2],
data_[idx+3]
}};
}
void masking_key(const mask_type &v) {
mask(true);
uint8_t idx=payload_len_end_idx();
data_[idx] =v[0];
data_[idx+1]=v[1];
data_[idx+2]=v[2];
data_[idx+3]=v[3];
}
size_t size() const {
return payload_len_end_idx() + (mask()?4:0);
}
void clear() { memset(data_, 0, sizeof(data_)); }
uint8_t data_[14];
};
inline std::ostream& operator<<(std::ostream &os, const frame_header &hdr) {
os.write((char *)(hdr.data_), hdr.size());
return os;
}
inline std::istream& operator>>(std::istream &is, frame_header &hdr) {
is.read((char *)(hdr.data_), 2);
std::streamsize sz=hdr.payload_len_end_idx()-2;
if (hdr.mask()) { sz+=4; }
if (sz>0) {
is.read((char *)(hdr.data_)+2, sz);
}
return is;
}
struct connection {
connection(std::istream &is,std::ostream &os)
: is_(is)
, os_(os)
, max_payload_len_(DEFAULT_MAX_PAYLOAD_LEN)
, max_message_size_(DEFAULT_MAX_MESSAGE_SIZE)
, masked_(false)
{}
connection(std::istream &is,std::ostream &os, const mask_type &masking_key)
: is_(is)
, os_(os)
, max_payload_len_(DEFAULT_MAX_PAYLOAD_LEN)
, max_message_size_(DEFAULT_MAX_MESSAGE_SIZE)
, masked_(true)
, masking_key_(masking_key)
{}
size_t max_payload_len() const { return max_payload_len_; }
void max_payload_len(size_t v) { max_payload_len_=v; }
size_t max_message_size() const { return max_message_size_; }
void max_message_size(size_t v) { max_message_size_=v; }
bool masked() const { return masked_; }
void masking_key(const mask_type &mask) { masked_=true; masking_key_=mask; }
void masking_key() { masked_=false; }
template<typename RandomIterator>
void send_one_frame(OPCODE op, RandomIterator begin, RandomIterator end, bool last=true) {
static_assert(sizeof(typename std::iterator_traits<RandomIterator>::value_type)==1,
"Byte buffer required");
static_assert(std::is_same<
typename std::iterator_traits<RandomIterator>::iterator_category,
std::random_access_iterator_tag
>::value,
"Random iterator required");
frame_header hdr;
hdr.clear();
hdr.fin(last);
hdr.opcode(op);
size_t sz=end-begin;
hdr.payload_len(sz);
if(masked_) hdr.masking_key(masking_key_);
os_ << hdr;
for (size_t i=0; i<sz; ++i) {
uint8_t d=*(begin+i);
if (masked_) {
d ^= masking_key_[i%4];
}
os_.write((char *)(&d), 1);
}
os_.flush();
}
template<typename RandomIterator>
void send(OPCODE op, RandomIterator begin, RandomIterator end) {
bool first=true;
while(begin<end) {
if(!first) {
op=OPCODE::CONTINUATION;
}
RandomIterator frame_end=begin+max_payload_len_;
if(frame_end>end) {
frame_end=end;
}
send_one_frame(op, begin, frame_end, frame_end==end);
begin=frame_end;
first=false;
}
}
template<typename RandomIterator>
void send_binary(RandomIterator begin, RandomIterator end) {
send(OPCODE::BINARY, begin, end);
}
template<typename RandomIterator>
void send_text(RandomIterator begin, RandomIterator end) {
send(OPCODE::TEXT, begin, end);
}
template<typename CharT, typename Traits, typename Allocator>
void send_text(const std::basic_string<CharT, Traits, Allocator> &s) {
static_assert(sizeof(CharT)==1, "Text message cannot contain wide char");
send_text(s.cbegin(), s.cend());
}
template<typename RandomIterator>
void ping(RandomIterator begin, RandomIterator end) {
send(OPCODE::PING, begin, end);
}
template<typename RandomIterator>
void pong(RandomIterator begin, RandomIterator end) {
send(OPCODE::PONG, begin, end);
}
template<typename RandomIterator>
void close(RandomIterator begin, RandomIterator end) {
send(OPCODE::CLOSE, begin, end);
}
void close() {
std::string s;
close(s.begin(), s.end());
}
template<typename OutputIterator>
std::pair<uint8_t, size_t> recv_one_frame(OutputIterator it) {
//static_assert(sizeof(typename std::iterator_traits<OutputIterator>::value_type)==1, "Byte buffer required");
frame_header hdr;
hdr.clear();
is_ >> hdr;
size_t sz=hdr.payload_len();
if(sz>max_payload_len_) {
return {0xFF, 0};
}
mask_type m;
if(hdr.mask()) { m=hdr.masking_key(); }
for(size_t i=0; i<sz; ++i) {
char d;
is_.read(&d, 1);
if(hdr.mask()) {
d ^= m[i%4];
}
*it++=d;
}
return {hdr.data_[0], sz};
}
template<typename OutputIterator>
std::pair<uint8_t, size_t> recv_one_frame(OPCODE op, OutputIterator it) {
//static_assert(sizeof(typename std::iterator_traits<OutputIterator>::value_type)==1, "Byte buffer required");
frame_header hdr;
hdr.clear();
is_ >> hdr;
if(hdr.opcode()!=op && hdr.opcode()!=OPCODE::CONTINUATION) {
return {0xFF, 0};
}
size_t sz=hdr.payload_len();
if(sz>max_payload_len_) {
return {0xFF, 0};
}
mask_type m;
if(hdr.mask()) { m=hdr.masking_key(); }
for(size_t i=0; i<sz; ++i) {
char d;
is_.read(&d, 1);
if(hdr.mask()) {
d ^= m[i%4];
}
*it++=d;
}
return {hdr.data_[0], sz};
}
template<typename OutputIterator>
OPCODE recv_msg(OutputIterator it) {
size_t msg_sz=0;
std::pair<uint8_t, size_t> ret;
bool first=true;
OPCODE op=OPCODE::INVALID;
do {
ret=recv_one_frame(it);
op=OPCODE(ret.first & 0x0F);
msg_sz+=ret.second;
if(msg_sz>max_message_size_) return OPCODE::INVALID;
first=false;
} while((ret.first&0x80)==0);
return op;
}
template<typename OutputIterator>
bool recv_msg(OPCODE op, OutputIterator it) {
size_t msg_sz=0;
std::pair<uint8_t, size_t> ret;
bool first=true;
do {
ret=recv_one_frame(op, it);
if(ret.first==0xFF) return false;
msg_sz+=ret.second;
if(msg_sz>max_message_size_) return false;
first=false;
} while((ret.first&0x80)==0);
return true;
}
std::istream &is_;
std::ostream &os_;
size_t max_payload_len_;
size_t max_message_size_;
bool masked_;
mask_type masking_key_;
};
typedef std::function<void(websocket::connection &)> connection_handler;
}}} // End of namespace fibio::http::websocket
#endif // !defined(fibio_http_common_websocket_hpp)<commit_msg>Cleanup<commit_after>//
// websocket.hpp
// fibio-http
//
// Created by Chen Xu on 15/08/28.
// Copyright (c) 2015 0d0a.com. All rights reserved.
//
#ifndef fibio_http_common_websocket_hpp
#define fibio_http_common_websocket_hpp
#include <array>
#include <cstdint>
#include <iostream>
namespace fibio { namespace http { namespace websocket {
constexpr size_t DEFAULT_MAX_PAYLOAD_LEN=4096;
constexpr size_t DEFAULT_MAX_MESSAGE_SIZE=65536;
enum class OPCODE : uint8_t {
CONTINUATION = 0,
TEXT = 1,
BINARY = 2,
CLOSE = 8,
PING = 9,
PONG = 10,
INVALID = 255,
};
typedef std::array<uint8_t, 4> mask_type;
struct frame_header {
bool fin() const { return (data_[0] & 0x80)!=0; }
void fin(bool v) { if(v) { data_[0] |= 0x80; } else { data_[0] &= 0x7F; } }
bool rsv1() const { return (data_[0] & 0x40)!=0; }
void rsv1(bool v) { if(v) { data_[0] |= 0x40; } else { data_[0] &= 0xBF; } }
bool rsv2() const { return (data_[0] & 0x20)!=0; }
void rsv2(bool v) { if(v) { data_[0] |= 0x20; } else { data_[0] &= 0xDF; } }
bool rsv3() const { return (data_[0] & 0x10)!=0; }
void rsv3(bool v) { if(v) { data_[0] |= 0x10; } else { data_[0] &= 0xEF; } }
OPCODE opcode() const { return OPCODE(data_[0] & 0x0F); }
void opcode(OPCODE v) { data_[0] &= 0xF0; data_[0] |= uint8_t(v)&0x0F; }
bool mask() const { return (data_[1] & 0x80)!=0; }
void mask(bool v) { if(v) { data_[1] |= 0x80; } else { data_[1] &= 0x7F; } }
uint8_t payload_len_7() const { return data_[1] & 0x7F; }
void payload_len_7(uint8_t v) { data_[1] &= 0x80; data_[1] |= v&0x7F; }
uint16_t ext_payload_len_16() const { return data_[2]<<8 | data_[3]; }
void ext_payload_len_16(uint16_t v) { data_[2] = v>>8; data_[3] = v&0xFF; }
uint64_t ext_payload_len_64() const {
uint64_t ret = uint64_t(data_[2]) << 56
| uint64_t(data_[3]) << 48
| uint64_t(data_[4]) << 40
| uint64_t(data_[5]) << 32
| uint64_t(data_[6]) << 24
| uint64_t(data_[7]) << 16
| uint64_t(data_[8]) << 8
| uint64_t(data_[9]);
return ret;
}
void ext_payload_len_64(uint64_t v) {
data_[2] = v>>56 & 0xFF;
data_[3] = v>>48 & 0xFF;
data_[4] = v>>40 & 0xFF;
data_[5] = v>>32 & 0xFF;
data_[6] = v>>24 & 0xFF;
data_[7] = v>>16 & 0xFF;
data_[8] = v>>8 & 0xFF;
data_[9] = v & 0xFF;
}
uint64_t payload_len() const {
uint64_t ret=payload_len_7();
if(ret==126) return ext_payload_len_16();
if(ret==127) return ext_payload_len_64();
return ret;
}
void internal_set_payload_len(uint64_t v) {
if(v>0xFFFF) {
// 8 bytes
payload_len_7(127);
ext_payload_len_64(v);
} else if(v>=126) {
// 2 bytes
payload_len_7(126);
ext_payload_len_16(v);
} else {
payload_len_7(v);
}
}
void payload_len(uint64_t v) {
if(mask()) {
// Preserve masking key
mask_type m=masking_key();
internal_set_payload_len(v);
masking_key(m);
} else {
internal_set_payload_len(v);
}
}
uint8_t payload_len_end_idx() const {
uint8_t pl=payload_len_7();
if(pl<126) return 2;
if(pl<127) return 4;
return 10;
}
mask_type masking_key() const {
uint8_t idx=payload_len_end_idx();
return mask_type{{
data_[idx],
data_[idx+1],
data_[idx+2],
data_[idx+3]
}};
}
void masking_key(const mask_type &v) {
mask(true);
uint8_t idx=payload_len_end_idx();
data_[idx] =v[0];
data_[idx+1]=v[1];
data_[idx+2]=v[2];
data_[idx+3]=v[3];
}
size_t size() const {
return payload_len_end_idx() + (mask()?4:0);
}
void clear() { memset(data_, 0, sizeof(data_)); }
uint8_t data_[14];
};
inline std::ostream& operator<<(std::ostream &os, const frame_header &hdr) {
os.write((char *)(hdr.data_), hdr.size());
return os;
}
inline std::istream& operator>>(std::istream &is, frame_header &hdr) {
is.read((char *)(hdr.data_), 2);
std::streamsize sz=hdr.payload_len_end_idx()-2;
if (hdr.mask()) { sz+=4; }
if (sz>0) {
is.read((char *)(hdr.data_)+2, sz);
}
return is;
}
struct connection {
connection(std::istream &is,std::ostream &os)
: is_(is)
, os_(os)
, max_payload_len_(DEFAULT_MAX_PAYLOAD_LEN)
, max_message_size_(DEFAULT_MAX_MESSAGE_SIZE)
, masked_(false)
{}
connection(std::istream &is,std::ostream &os, const mask_type &masking_key)
: is_(is)
, os_(os)
, max_payload_len_(DEFAULT_MAX_PAYLOAD_LEN)
, max_message_size_(DEFAULT_MAX_MESSAGE_SIZE)
, masked_(true)
, masking_key_(masking_key)
{}
size_t max_payload_len() const { return max_payload_len_; }
void max_payload_len(size_t v) { max_payload_len_=v; }
size_t max_message_size() const { return max_message_size_; }
void max_message_size(size_t v) { max_message_size_=v; }
bool masked() const { return masked_; }
void masking_key(const mask_type &mask) { masked_=true; masking_key_=mask; }
void masking_key() { masked_=false; }
template<typename RandomIterator>
void send_one_frame(OPCODE op, RandomIterator begin, RandomIterator end, bool last=true) {
static_assert(sizeof(typename std::iterator_traits<RandomIterator>::value_type)==1,
"Byte buffer required");
static_assert(std::is_same<
typename std::iterator_traits<RandomIterator>::iterator_category,
std::random_access_iterator_tag
>::value,
"Random iterator required");
frame_header hdr;
hdr.clear();
hdr.fin(last);
hdr.opcode(op);
size_t sz=end-begin;
hdr.payload_len(sz);
if(masked_) hdr.masking_key(masking_key_);
os_ << hdr;
for (size_t i=0; i<sz; ++i) {
uint8_t d=*(begin+i);
if (masked_) {
d ^= masking_key_[i%4];
}
os_.write((char *)(&d), 1);
}
os_.flush();
}
template<typename RandomIterator>
void send(OPCODE op, RandomIterator begin, RandomIterator end) {
bool first=true;
while(begin<end) {
if(!first) {
op=OPCODE::CONTINUATION;
}
RandomIterator frame_end=begin+max_payload_len_;
if(frame_end>end) {
frame_end=end;
}
send_one_frame(op, begin, frame_end, frame_end==end);
begin=frame_end;
first=false;
}
}
template<typename Container>
void send(OPCODE op, const Container &c) {
send(op, std::begin(c), std::end(c));
}
template<typename RandomIterator>
void send_binary(RandomIterator begin, RandomIterator end) {
send(OPCODE::BINARY, begin, end);
}
template<typename Container>
void send_binary(const Container &c) {
send_binary(std::begin(c), std::end(c));
}
template<typename RandomIterator>
void send_text(RandomIterator begin, RandomIterator end) {
send(OPCODE::TEXT, begin, end);
}
template<typename Container>
void send_text(const Container &c) {
send_text(std::begin(c), std::end(c));
}
template<typename RandomIterator>
void ping(RandomIterator begin, RandomIterator end) {
send(OPCODE::PING, begin, end);
}
template<typename Container>
void ping(const Container &c) {
ping(std::begin(c), std::end(c));
}
template<typename RandomIterator>
void pong(RandomIterator begin, RandomIterator end) {
send(OPCODE::PONG, begin, end);
}
template<typename Container>
void pong(const Container &c) {
pong(std::begin(c), std::end(c));
}
template<typename RandomIterator>
void close(RandomIterator begin, RandomIterator end) {
send(OPCODE::CLOSE, begin, end);
}
template<typename Container>
void close(const Container &c) {
close(std::begin(c), std::end(c));
}
void close() {
close(std::string());
}
template<typename OutputIterator>
std::pair<uint8_t, size_t> recv_one_frame(OutputIterator it) {
//static_assert(sizeof(typename std::iterator_traits<OutputIterator>::value_type)==1, "Byte buffer required");
frame_header hdr;
hdr.clear();
is_ >> hdr;
size_t sz=hdr.payload_len();
if(sz>max_payload_len_) {
return {0xFF, 0};
}
mask_type m;
if(hdr.mask()) { m=hdr.masking_key(); }
for(size_t i=0; i<sz; ++i) {
char d;
is_.read(&d, 1);
if(hdr.mask()) {
d ^= m[i%4];
}
*it++=d;
}
return {hdr.data_[0], sz};
}
template<typename OutputIterator>
std::pair<uint8_t, size_t> recv_one_frame(OPCODE op, OutputIterator it) {
//static_assert(sizeof(typename std::iterator_traits<OutputIterator>::value_type)==1, "Byte buffer required");
frame_header hdr;
hdr.clear();
is_ >> hdr;
if(hdr.opcode()!=op && hdr.opcode()!=OPCODE::CONTINUATION) {
return {0xFF, 0};
}
size_t sz=hdr.payload_len();
if(sz>max_payload_len_) {
return {0xFF, 0};
}
mask_type m;
if(hdr.mask()) { m=hdr.masking_key(); }
for(size_t i=0; i<sz; ++i) {
char d;
is_.read(&d, 1);
if(hdr.mask()) {
d ^= m[i%4];
}
*it++=d;
}
return {hdr.data_[0], sz};
}
template<typename OutputIterator>
OPCODE recv_msg(OutputIterator it) {
size_t msg_sz=0;
std::pair<uint8_t, size_t> ret;
bool first=true;
OPCODE op=OPCODE::INVALID;
do {
ret=recv_one_frame(it);
op=OPCODE(ret.first & 0x0F);
msg_sz+=ret.second;
if(msg_sz>max_message_size_) return OPCODE::INVALID;
first=false;
} while((ret.first&0x80)==0);
return op;
}
template<typename OutputIterator>
bool recv_msg(OPCODE op, OutputIterator it) {
size_t msg_sz=0;
std::pair<uint8_t, size_t> ret;
bool first=true;
do {
ret=recv_one_frame(op, it);
if(ret.first==0xFF) return false;
msg_sz+=ret.second;
if(msg_sz>max_message_size_) return false;
first=false;
} while((ret.first&0x80)==0);
return true;
}
std::istream &is_;
std::ostream &os_;
size_t max_payload_len_;
size_t max_message_size_;
bool masked_;
mask_type masking_key_;
};
typedef std::function<void(websocket::connection &)> connection_handler;
}}} // End of namespace fibio::http::websocket
#endif // !defined(fibio_http_common_websocket_hpp)
<|endoftext|> |
<commit_before>#ifdef __APPLE__
#define USE_KQUEUE
#endif
#ifdef USE_KQUEUE
#include <sys/event.h>
#else
#include <sys/epoll.h>
#endif
#include <unordered_map>
#include <unordered_set>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include "utils.h"
#include "polling.h"
using namespace std;
namespace rpc {
class PollMgr::PollThread {
friend class PollMgr;
PollMgr* poll_mgr_;
// guard mode_ and poll_set_
SpinLock l_;
std::unordered_map<int, int> mode_;
std::unordered_set<Pollable*> poll_set_;
int poll_fd_;
std::unordered_set<Pollable*> pending_remove_;
SpinLock pending_remove_l_;
pthread_t th_;
bool stop_flag_;
static void* start_poll_loop(void* arg) {
PollThread* thiz = (PollThread *) arg;
thiz->poll_loop();
pthread_exit(nullptr);
return nullptr;
}
void poll_loop();
void start(PollMgr* poll_mgr) {
poll_mgr_ = poll_mgr;
Pthread_create(&th_, nullptr, PollMgr::PollThread::start_poll_loop, this);
}
public:
PollThread(): poll_mgr_(nullptr), stop_flag_(false) {
#ifdef USE_KQUEUE
poll_fd_ = kqueue();
#else
poll_fd_ = epoll_create(10); // arg ignored, any value > 0 will do
#endif
verify(poll_fd_ != -1);
}
~PollThread() {
l_.lock();
unordered_set<Pollable*> poll_set_copy = poll_set_;
l_.unlock();
// NOTE: do NOT clear poll_set_, as when doing this->remove(it)
// the code will check if the Pollable is still in poll_set_
for (auto& it: poll_set_copy) {
this->remove(it);
}
stop_flag_ = true;
Pthread_join(th_, nullptr);
}
void add(Pollable*);
void remove(Pollable*);
void update_mode(Pollable*, int new_mode);
};
PollMgr::PollMgr(const poll_options& opts /* =... */): opts_(opts) {
poll_threads_ = new PollThread[opts_.n_threads];
for (int i = 0; i < opts_.n_threads; i++) {
poll_threads_[i].start(this);
}
//Log_debug("rpc::PollMgr: start with %d thread", opts_.n_threads);
}
PollMgr::~PollMgr() {
delete[] poll_threads_;
//Log_debug("rpc::PollMgr: destroyed");
}
void PollMgr::PollThread::poll_loop() {
while (!stop_flag_) {
const int max_nev = 100;
#ifdef USE_KQUEUE
struct kevent evlist[max_nev];
struct timespec timeout;
timeout.tv_sec = 0;
timeout.tv_nsec = 50 * 1000 * 1000; // 0.05 sec
int nev = kevent(poll_fd_, nullptr, 0, evlist, max_nev, &timeout);
for (int i = 0; i < nev; i++) {
Pollable* poll = (Pollable *) evlist[i].udata;
verify(poll != nullptr);
if (evlist[i].filter == EVFILT_READ) {
poll->handle_read();
}
if (evlist[i].filter == EVFILT_WRITE) {
poll->handle_write();
}
// handle error after handle IO, so that we can at least process something
if (evlist[i].flags & EV_EOF) {
poll->handle_error();
}
}
#else
struct epoll_event evlist[max_nev];
int timeout = 50; // milli, 0.05 sec
int nev = epoll_wait(poll_fd_, evlist, max_nev, timeout);
if (stop_flag_) {
break;
}
for (int i = 0; i < nev; i++) {
Pollable* poll = (Pollable *) evlist[i].data.ptr;
verify(poll != nullptr);
if (evlist[i].events & EPOLLIN) {
poll->handle_read();
}
if (evlist[i].events & EPOLLOUT) {
poll->handle_write();
}
// handle error after handle IO, so that we can at least process something
if (evlist[i].events & (EPOLLERR | EPOLLHUP | EPOLLRDHUP)) {
poll->handle_error();
}
}
#endif
// after each poll loop, remove uninterested pollables
pending_remove_l_.lock();
list<Pollable*> remove_poll(pending_remove_.begin(), pending_remove_.end());
pending_remove_.clear();
pending_remove_l_.unlock();
for (auto& poll: remove_poll) {
int fd = poll->fd();
l_.lock();
if (mode_.find(fd) == mode_.end()) {
// NOTE: only remove the fd when it is not immediately added again
// if the same fd is used again, mode_ will contains its info
#ifdef USE_KQUEUE
struct kevent ev;
bzero(&ev, sizeof(ev));
ev.ident = fd;
ev.flags = EV_DELETE;
ev.filter = EVFILT_READ;
kevent(poll_fd_, &ev, 1, nullptr, 0, nullptr);
bzero(&ev, sizeof(ev));
ev.ident = fd;
ev.flags = EV_DELETE;
ev.filter = EVFILT_WRITE;
kevent(poll_fd_, &ev, 1, nullptr, 0, nullptr);
#else
struct epoll_event ev;
memset(&ev, 0, sizeof(ev));
epoll_ctl(poll_fd_, EPOLL_CTL_DEL, fd, &ev);
#endif
}
l_.unlock();
poll->release();
}
}
// when stopping, release anything registered in pollmgr
for (auto& it: poll_set_) {
it->release();
}
close(poll_fd_);
}
void PollMgr::PollThread::add(Pollable* poll) {
poll->ref_copy(); // increase ref count
int poll_mode = poll->poll_mode();
int fd = poll->fd();
l_.lock();
// verify not exists
verify(poll_set_.find(poll) == poll_set_.end());
verify(mode_.find(fd) == mode_.end());
// register pollable
poll_set_.insert(poll);
mode_[fd] = poll_mode;
l_.unlock();
#ifdef USE_KQUEUE
struct kevent ev;
if (poll_mode & Pollable::READ) {
bzero(&ev, sizeof(ev));
ev.ident = fd;
ev.flags = EV_ADD;
ev.filter = EVFILT_READ;
ev.udata = poll;
verify(kevent(poll_fd_, &ev, 1, nullptr, 0, nullptr) == 0);
}
if (poll_mode & Pollable::WRITE) {
bzero(&ev, sizeof(ev));
ev.ident = fd;
ev.flags = EV_ADD;
ev.filter = EVFILT_WRITE;
ev.udata = poll;
verify(kevent(poll_fd_, &ev, 1, nullptr, 0, nullptr) == 0);
}
#else
struct epoll_event ev;
memset(&ev, 0, sizeof(ev));
ev.data.ptr = poll;
ev.events = EPOLLIN | EPOLLRDHUP; // EPOLLERR and EPOLLHUP are included by default
if (poll_mgr_->opts_.rate.min_size <= 0 && poll_mgr_->opts_.rate.interval <= 0.0) {
// only enable EPOLLET when not batching
ev.events |= EPOLLET;
}
if (poll_mode & Pollable::WRITE) {
ev.events |= EPOLLOUT;
}
verify(epoll_ctl(poll_fd_, EPOLL_CTL_ADD, fd, &ev) == 0);
#endif
}
void PollMgr::PollThread::remove(Pollable* poll) {
bool found = false;
l_.lock();
unordered_set<Pollable*>::iterator it = poll_set_.find(poll);
if (it != poll_set_.end()) {
found = true;
assert(mode_.find(poll->fd()) != mode_.end());
poll_set_.erase(poll);
mode_.erase(poll->fd());
} else {
assert(mode_.find(poll->fd()) == mode_.end());
}
l_.unlock();
if (found) {
pending_remove_l_.lock();
pending_remove_.insert(poll);
pending_remove_l_.unlock();
}
}
void PollMgr::PollThread::update_mode(Pollable* poll, int new_mode) {
int fd = poll->fd();
l_.lock();
if (poll_set_.find(poll) == poll_set_.end()) {
l_.unlock();
return;
}
unordered_map<int, int>::iterator it = mode_.find(fd);
verify(it != mode_.end());
int old_mode = it->second;
it->second = new_mode;
if (new_mode != old_mode) {
#ifdef USE_KQUEUE
struct kevent ev;
if ((new_mode & Pollable::READ) && !(old_mode & Pollable::READ)) {
// add READ
bzero(&ev, sizeof(ev));
ev.ident = fd;
ev.udata = poll;
ev.flags = EV_ADD;
ev.filter = EVFILT_READ;
verify(kevent(poll_fd_, &ev, 1, nullptr, 0, nullptr) == 0);
}
if (!(new_mode & Pollable::READ) && (old_mode & Pollable::READ)) {
// del READ
bzero(&ev, sizeof(ev));
ev.ident = fd;
ev.udata = poll;
ev.flags = EV_DELETE;
ev.filter = EVFILT_READ;
verify(kevent(poll_fd_, &ev, 1, nullptr, 0, nullptr) == 0);
}
if ((new_mode & Pollable::WRITE) && !(old_mode & Pollable::WRITE)) {
// add WRITE
bzero(&ev, sizeof(ev));
ev.ident = fd;
ev.udata = poll;
ev.flags = EV_ADD;
ev.filter = EVFILT_WRITE;
verify(kevent(poll_fd_, &ev, 1, nullptr, 0, nullptr) == 0);
}
if (!(new_mode & Pollable::WRITE) && (old_mode & Pollable::WRITE)) {
// del WRITE
bzero(&ev, sizeof(ev));
ev.ident = fd;
ev.udata = poll;
ev.flags = EV_DELETE;
ev.filter = EVFILT_WRITE;
verify(kevent(poll_fd_, &ev, 1, nullptr, 0, nullptr) == 0);
}
#else
struct epoll_event ev;
memset(&ev, 0, sizeof(ev));
ev.data.ptr = poll;
ev.events = EPOLLRDHUP;
if (poll_mgr_->opts_.rate.min_size <= 0 && poll_mgr_->opts_.rate.interval <= 0.0) {
// only enable EPOLLET when not batching
ev.events |= EPOLLET;
}
if (new_mode & Pollable::READ) {
ev.events |= EPOLLIN;
}
if (new_mode & Pollable::WRITE) {
ev.events |= EPOLLOUT;
}
verify(epoll_ctl(poll_fd_, EPOLL_CTL_MOD, fd, &ev) == 0);
#endif
}
l_.unlock();
}
void PollMgr::add(Pollable* poll) {
int fd = poll->fd();
if (fd >= 0) {
int tid = fd % opts_.n_threads;
poll_threads_[tid].add(poll);
}
}
void PollMgr::remove(Pollable* poll) {
int fd = poll->fd();
if (fd >= 0) {
int tid = fd % opts_.n_threads;
poll_threads_[tid].remove(poll);
}
}
void PollMgr::update_mode(Pollable* poll, int new_mode) {
int fd = poll->fd();
if (fd >= 0) {
int tid = fd % opts_.n_threads;
poll_threads_[tid].update_mode(poll, new_mode);
}
}
}
<commit_msg>minor update for epoll<commit_after>#ifdef __APPLE__
#define USE_KQUEUE
#endif
#ifdef USE_KQUEUE
#include <sys/event.h>
#else
#include <sys/epoll.h>
#endif
#include <unordered_map>
#include <unordered_set>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include "utils.h"
#include "polling.h"
using namespace std;
namespace rpc {
class PollMgr::PollThread {
friend class PollMgr;
PollMgr* poll_mgr_;
// guard mode_ and poll_set_
SpinLock l_;
std::unordered_map<int, int> mode_;
std::unordered_set<Pollable*> poll_set_;
int poll_fd_;
std::unordered_set<Pollable*> pending_remove_;
SpinLock pending_remove_l_;
pthread_t th_;
bool stop_flag_;
static void* start_poll_loop(void* arg) {
PollThread* thiz = (PollThread *) arg;
thiz->poll_loop();
pthread_exit(nullptr);
return nullptr;
}
void poll_loop();
void start(PollMgr* poll_mgr) {
poll_mgr_ = poll_mgr;
Pthread_create(&th_, nullptr, PollMgr::PollThread::start_poll_loop, this);
}
public:
PollThread(): poll_mgr_(nullptr), stop_flag_(false) {
#ifdef USE_KQUEUE
poll_fd_ = kqueue();
#else
poll_fd_ = epoll_create(10); // arg ignored, any value > 0 will do
#endif
verify(poll_fd_ != -1);
}
~PollThread() {
l_.lock();
unordered_set<Pollable*> poll_set_copy = poll_set_;
l_.unlock();
// NOTE: do NOT clear poll_set_, as when doing this->remove(it)
// the code will check if the Pollable is still in poll_set_
for (auto& it: poll_set_copy) {
this->remove(it);
}
stop_flag_ = true;
Pthread_join(th_, nullptr);
}
void add(Pollable*);
void remove(Pollable*);
void update_mode(Pollable*, int new_mode);
};
PollMgr::PollMgr(const poll_options& opts /* =... */): opts_(opts) {
poll_threads_ = new PollThread[opts_.n_threads];
for (int i = 0; i < opts_.n_threads; i++) {
poll_threads_[i].start(this);
}
//Log_debug("rpc::PollMgr: start with %d thread", opts_.n_threads);
}
PollMgr::~PollMgr() {
delete[] poll_threads_;
//Log_debug("rpc::PollMgr: destroyed");
}
void PollMgr::PollThread::poll_loop() {
while (!stop_flag_) {
const int max_nev = 100;
#ifdef USE_KQUEUE
struct kevent evlist[max_nev];
struct timespec timeout;
timeout.tv_sec = 0;
timeout.tv_nsec = 50 * 1000 * 1000; // 0.05 sec
int nev = kevent(poll_fd_, nullptr, 0, evlist, max_nev, &timeout);
for (int i = 0; i < nev; i++) {
Pollable* poll = (Pollable *) evlist[i].udata;
verify(poll != nullptr);
if (evlist[i].filter == EVFILT_READ) {
poll->handle_read();
}
if (evlist[i].filter == EVFILT_WRITE) {
poll->handle_write();
}
// handle error after handle IO, so that we can at least process something
if (evlist[i].flags & EV_EOF) {
poll->handle_error();
}
}
#else
struct epoll_event evlist[max_nev];
int timeout = 50; // milli, 0.05 sec
int nev = epoll_wait(poll_fd_, evlist, max_nev, timeout);
if (stop_flag_) {
break;
}
for (int i = 0; i < nev; i++) {
Pollable* poll = (Pollable *) evlist[i].data.ptr;
verify(poll != nullptr);
if (evlist[i].events & EPOLLIN) {
poll->handle_read();
}
if (evlist[i].events & EPOLLOUT) {
poll->handle_write();
}
// handle error after handle IO, so that we can at least process something
if (evlist[i].events & (EPOLLERR | EPOLLHUP | EPOLLRDHUP)) {
poll->handle_error();
}
}
#endif
// after each poll loop, remove uninterested pollables
pending_remove_l_.lock();
list<Pollable*> remove_poll(pending_remove_.begin(), pending_remove_.end());
pending_remove_.clear();
pending_remove_l_.unlock();
for (auto& poll: remove_poll) {
int fd = poll->fd();
l_.lock();
if (mode_.find(fd) == mode_.end()) {
// NOTE: only remove the fd when it is not immediately added again
// if the same fd is used again, mode_ will contains its info
#ifdef USE_KQUEUE
struct kevent ev;
bzero(&ev, sizeof(ev));
ev.ident = fd;
ev.flags = EV_DELETE;
ev.filter = EVFILT_READ;
kevent(poll_fd_, &ev, 1, nullptr, 0, nullptr);
bzero(&ev, sizeof(ev));
ev.ident = fd;
ev.flags = EV_DELETE;
ev.filter = EVFILT_WRITE;
kevent(poll_fd_, &ev, 1, nullptr, 0, nullptr);
#else
struct epoll_event ev;
memset(&ev, 0, sizeof(ev));
epoll_ctl(poll_fd_, EPOLL_CTL_DEL, fd, &ev);
#endif
}
l_.unlock();
poll->release();
}
}
// when stopping, release anything registered in pollmgr
for (auto& it: poll_set_) {
it->release();
}
close(poll_fd_);
}
void PollMgr::PollThread::add(Pollable* poll) {
poll->ref_copy(); // increase ref count
int poll_mode = poll->poll_mode();
int fd = poll->fd();
l_.lock();
// verify not exists
verify(poll_set_.find(poll) == poll_set_.end());
verify(mode_.find(fd) == mode_.end());
// register pollable
poll_set_.insert(poll);
mode_[fd] = poll_mode;
l_.unlock();
#ifdef USE_KQUEUE
struct kevent ev;
if (poll_mode & Pollable::READ) {
bzero(&ev, sizeof(ev));
ev.ident = fd;
ev.flags = EV_ADD;
ev.filter = EVFILT_READ;
ev.udata = poll;
verify(kevent(poll_fd_, &ev, 1, nullptr, 0, nullptr) == 0);
}
if (poll_mode & Pollable::WRITE) {
bzero(&ev, sizeof(ev));
ev.ident = fd;
ev.flags = EV_ADD;
ev.filter = EVFILT_WRITE;
ev.udata = poll;
verify(kevent(poll_fd_, &ev, 1, nullptr, 0, nullptr) == 0);
}
#else
struct epoll_event ev;
memset(&ev, 0, sizeof(ev));
ev.data.ptr = poll;
ev.events = EPOLLET | EPOLLIN | EPOLLRDHUP; // EPOLLERR and EPOLLHUP are included by default
if (poll_mode & Pollable::WRITE) {
ev.events |= EPOLLOUT;
}
verify(epoll_ctl(poll_fd_, EPOLL_CTL_ADD, fd, &ev) == 0);
#endif
}
void PollMgr::PollThread::remove(Pollable* poll) {
bool found = false;
l_.lock();
unordered_set<Pollable*>::iterator it = poll_set_.find(poll);
if (it != poll_set_.end()) {
found = true;
assert(mode_.find(poll->fd()) != mode_.end());
poll_set_.erase(poll);
mode_.erase(poll->fd());
} else {
assert(mode_.find(poll->fd()) == mode_.end());
}
l_.unlock();
if (found) {
pending_remove_l_.lock();
pending_remove_.insert(poll);
pending_remove_l_.unlock();
}
}
void PollMgr::PollThread::update_mode(Pollable* poll, int new_mode) {
int fd = poll->fd();
l_.lock();
if (poll_set_.find(poll) == poll_set_.end()) {
l_.unlock();
return;
}
unordered_map<int, int>::iterator it = mode_.find(fd);
verify(it != mode_.end());
int old_mode = it->second;
it->second = new_mode;
if (new_mode != old_mode) {
#ifdef USE_KQUEUE
struct kevent ev;
if ((new_mode & Pollable::READ) && !(old_mode & Pollable::READ)) {
// add READ
bzero(&ev, sizeof(ev));
ev.ident = fd;
ev.udata = poll;
ev.flags = EV_ADD;
ev.filter = EVFILT_READ;
verify(kevent(poll_fd_, &ev, 1, nullptr, 0, nullptr) == 0);
}
if (!(new_mode & Pollable::READ) && (old_mode & Pollable::READ)) {
// del READ
bzero(&ev, sizeof(ev));
ev.ident = fd;
ev.udata = poll;
ev.flags = EV_DELETE;
ev.filter = EVFILT_READ;
verify(kevent(poll_fd_, &ev, 1, nullptr, 0, nullptr) == 0);
}
if ((new_mode & Pollable::WRITE) && !(old_mode & Pollable::WRITE)) {
// add WRITE
bzero(&ev, sizeof(ev));
ev.ident = fd;
ev.udata = poll;
ev.flags = EV_ADD;
ev.filter = EVFILT_WRITE;
verify(kevent(poll_fd_, &ev, 1, nullptr, 0, nullptr) == 0);
}
if (!(new_mode & Pollable::WRITE) && (old_mode & Pollable::WRITE)) {
// del WRITE
bzero(&ev, sizeof(ev));
ev.ident = fd;
ev.udata = poll;
ev.flags = EV_DELETE;
ev.filter = EVFILT_WRITE;
verify(kevent(poll_fd_, &ev, 1, nullptr, 0, nullptr) == 0);
}
#else
struct epoll_event ev;
memset(&ev, 0, sizeof(ev));
ev.data.ptr = poll;
ev.events = EPOLLET | EPOLLRDHUP;
if (new_mode & Pollable::READ) {
ev.events |= EPOLLIN;
}
if (new_mode & Pollable::WRITE) {
ev.events |= EPOLLOUT;
}
verify(epoll_ctl(poll_fd_, EPOLL_CTL_MOD, fd, &ev) == 0);
#endif
}
l_.unlock();
}
void PollMgr::add(Pollable* poll) {
int fd = poll->fd();
if (fd >= 0) {
int tid = fd % opts_.n_threads;
poll_threads_[tid].add(poll);
}
}
void PollMgr::remove(Pollable* poll) {
int fd = poll->fd();
if (fd >= 0) {
int tid = fd % opts_.n_threads;
poll_threads_[tid].remove(poll);
}
}
void PollMgr::update_mode(Pollable* poll, int new_mode) {
int fd = poll->fd();
if (fd >= 0) {
int tid = fd % opts_.n_threads;
poll_threads_[tid].update_mode(poll, new_mode);
}
}
}
<|endoftext|> |
<commit_before>/*
* SpatLib
* Extension Class for Jamoma DSP
* Copyright © 2011 by Trond Lossius, Nils Peters, and Timothy Place
*
* License: This code is licensed under the terms of the "New BSD License"
* http://creativecommons.org/licenses/BSD/
*/
#include "SpatLib.h"
#include "SpatMatrix.h"
#include "SpatThru.h"
#include "TTSpat.h"
extern "C" TT_EXTENSION_EXPORT TTErr loadTTExtension(void)
{
TTDSPInit();
SpatMatrix::registerClass();
SpatThru::registerClass();
TTSpat::registerClass();
return kTTErrNone;
}
<commit_msg>SpatLib: updating extension so that it will be loadable by the new JamomaFoundation.<commit_after>/*
* SpatLib
* Extension Class for Jamoma DSP
* Copyright © 2011 by Trond Lossius, Nils Peters, and Timothy Place
*
* License: This code is licensed under the terms of the "New BSD License"
* http://creativecommons.org/licenses/BSD/
*/
#include "SpatLib.h"
#include "SpatMatrix.h"
#include "SpatThru.h"
#include "TTSpat.h"
extern "C" TT_EXTENSION_EXPORT TTErr TTLoadJamomaExtension_SpatLib(void)
{
TTDSPInit();
SpatMatrix::registerClass();
SpatThru::registerClass();
TTSpat::registerClass();
return kTTErrNone;
}
<|endoftext|> |
<commit_before>// Copyright (C) 2015 Elviss Strazdins
// This file is part of the Ouzel engine.
#include "RendererD3D11.h"
#include "Utils.h"
static LRESULT CALLBACK WindowProc(HWND window, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_DESTROY:
{
PostQuitMessage(0);
return 0;
}
}
return DefWindowProcW(window, msg, wParam, lParam);
}
namespace ouzel
{
RendererD3D11::RendererD3D11(const Size2& size, bool fullscreen, Engine* engine):
Renderer(size, fullscreen, engine, Driver::DIRECT3D11)
{
initWindow();
initD3D11();
recalculateProjection();
}
RendererD3D11::~RendererD3D11()
{
if (_depthStencilState) _depthStencilState->Release();
if (_blendState) _blendState->Release();
if (_rasterizerState) _rasterizerState->Release();
if (_samplerState) _samplerState->Release();
if (_rtView) _rtView->Release();
if (_backBuffer) _backBuffer->Release();
if (_swapChain) _swapChain->Release();
}
void RendererD3D11::initWindow()
{
HINSTANCE hInstance = GetModuleHandle(NULL);
WNDCLASSEXW wc;
memset(&wc, 0, sizeof(wc));
wc.cbSize = sizeof(wc);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wc.lpszClassName = L"OuzelWindow";
RegisterClassExW(&wc);
DWORD style = WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
int x = CW_USEDEFAULT;
int y = CW_USEDEFAULT;
if (_fullscreen)
{
style = WS_POPUP;
x = 0;
y = 0;
}
RECT windowRect = { 0, 0, (int)_size.width, (int)_size.height };
AdjustWindowRect(&windowRect, style, FALSE);
_window = CreateWindowExW(
NULL,
L"OuzelWindow",
L"Ouzel",
style,
x,
y,
windowRect.right - windowRect.left,
windowRect.bottom - windowRect.top,
NULL,
NULL,
hInstance,
NULL);
SetWindowLongPtrW(_window, GWLP_USERDATA, (LONG_PTR)this);
ShowWindow(_window, SW_SHOW);
}
void RendererD3D11::initD3D11()
{
DXGI_SWAP_CHAIN_DESC swapChainDesc;
memset(&swapChainDesc, 0, sizeof(swapChainDesc));
swapChainDesc.BufferDesc.Width = (int)_size.width;
swapChainDesc.BufferDesc.Height = (int)_size.height;
swapChainDesc.BufferDesc.RefreshRate.Numerator = _fullscreen ? 60 : 0; // TODO refresh rate?
swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE;
swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_STRETCHED;
swapChainDesc.SampleDesc.Count = 1; // TODO MSAA?
swapChainDesc.SampleDesc.Quality = 0;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.BufferCount = 1;
swapChainDesc.OutputWindow = _window;
swapChainDesc.Windowed = _fullscreen == false;
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
UINT deviceCreationFlags = 0;
#if D3D11_DEBUG
deviceCreationFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
HRESULT hr = D3D11CreateDeviceAndSwapChain(
NULL, // adapter
D3D_DRIVER_TYPE_HARDWARE,
NULL, // software rasterizer (unused)
deviceCreationFlags,
NULL, // feature levels
0, // ^^
D3D11_SDK_VERSION,
&swapChainDesc,
&_swapChain,
&_device,
NULL,
&_context
);
if (FAILED(hr))
{
log("Failed to create the D3D11 device");
return;
}
// Backbuffer
hr = _swapChain->GetBuffer(0, IID_ID3D11Texture2D, (void**)&_backBuffer);
if (FAILED(hr) || _backBuffer == NULL)
{
log("Failed to retrieve D3D11 backbuffer");
return;
}
hr = _device->CreateRenderTargetView(_backBuffer, NULL, &_rtView);
if (FAILED(hr) || _rtView == NULL)
{
log("Failed to create D3D11 render target view");
return;
}
// Sampler state
D3D11_SAMPLER_DESC samplerStateDesc =
{
D3D11_FILTER_MIN_MAG_MIP_LINEAR,
D3D11_TEXTURE_ADDRESS_WRAP,
D3D11_TEXTURE_ADDRESS_WRAP,
D3D11_TEXTURE_ADDRESS_WRAP,
0, 1, D3D11_COMPARISON_NEVER,{ 0,0,0,0 }, 0, D3D11_FLOAT32_MAX
};
hr = _device->CreateSamplerState(&samplerStateDesc, &_samplerState);
if (FAILED(hr) || !_samplerState)
{
log("Failed to create D3D11 sampler state");
return;
}
// Rasterizer state
D3D11_RASTERIZER_DESC rasterStateDesc =
{
D3D11_FILL_SOLID,
D3D11_CULL_NONE,
FALSE, // front = ccw?
0, 0, 0, // depth bias, clamp, slope scale
FALSE, // depth clip
FALSE, // scissor test
FALSE, // TODO MSAA enable?
TRUE, // AA lines
};
hr = _device->CreateRasterizerState(&rasterStateDesc, &_rasterizerState);
if (FAILED(hr) || !_rasterizerState)
{
log("Failed to create D3D11 rasterizer state");
return;
}
// Blending state
D3D11_BLEND_DESC blendStateDesc = { FALSE, FALSE }; // alpha to coverage, independent blend
D3D11_RENDER_TARGET_BLEND_DESC targetBlendDesc =
{
TRUE, // enable blending
D3D11_BLEND_SRC_ALPHA, D3D11_BLEND_INV_SRC_ALPHA, D3D11_BLEND_OP_ADD, // color blend source/dest factors, op
D3D11_BLEND_SRC_ALPHA, D3D11_BLEND_INV_SRC_ALPHA, D3D11_BLEND_OP_ADD, // alpha blend source/dest factors, op
D3D11_COLOR_WRITE_ENABLE_ALL, // color write mask
};
blendStateDesc.RenderTarget[0] = targetBlendDesc;
hr = _device->CreateBlendState(&blendStateDesc, &_blendState);
if (FAILED(hr) || !_blendState)
{
log("Failed to create D3D11 blend state");
return;
}
// Depth/stencil state
D3D11_DEPTH_STENCIL_DESC depthStencilStateDesc =
{
FALSE, // enable depth?
// ...
};
hr = _device->CreateDepthStencilState(&depthStencilStateDesc, &_depthStencilState);
if (FAILED(hr) || !_depthStencilState)
{
log("Failed to create D3D11 depth stencil state");
return;
}
Shader* textureShader = loadShaderFromFiles("ps_texture.cso", "vs_common.cso");
assert(textureShader && "Failed to load texture shader");
_shaders[SHADER_TEXTURE] = textureShader;
D3D11_VIEWPORT viewport = { 0, 0, _size.width, _size.height, 0.0f, 1.0f };
_context->RSSetViewports(1, &viewport);
_context->OMSetRenderTargets(1, &_rtView, nullptr);
}
void RendererD3D11::clear()
{
float color[4] = { _clearColor.getR(), _clearColor.getG(), _clearColor.getB(), _clearColor.getA() };
_context->ClearRenderTargetView(_rtView, color);
}
void RendererD3D11::flush()
{
_swapChain->Present(1 /* TODO vsync off? */, 0);
}
bool RendererD3D11::activateTexture(Texture* texture, uint32_t layer)
{
return true;
}
}
<commit_msg>Change casing of window procedure<commit_after>// Copyright (C) 2015 Elviss Strazdins
// This file is part of the Ouzel engine.
#include "RendererD3D11.h"
#include "Utils.h"
static LRESULT CALLBACK windowProc(HWND window, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_DESTROY:
{
PostQuitMessage(0);
return 0;
}
}
return DefWindowProcW(window, msg, wParam, lParam);
}
namespace ouzel
{
RendererD3D11::RendererD3D11(const Size2& size, bool fullscreen, Engine* engine):
Renderer(size, fullscreen, engine, Driver::DIRECT3D11)
{
initWindow();
initD3D11();
recalculateProjection();
}
RendererD3D11::~RendererD3D11()
{
if (_depthStencilState) _depthStencilState->Release();
if (_blendState) _blendState->Release();
if (_rasterizerState) _rasterizerState->Release();
if (_samplerState) _samplerState->Release();
if (_rtView) _rtView->Release();
if (_backBuffer) _backBuffer->Release();
if (_swapChain) _swapChain->Release();
}
void RendererD3D11::initWindow()
{
HINSTANCE hInstance = GetModuleHandle(NULL);
WNDCLASSEXW wc;
memset(&wc, 0, sizeof(wc));
wc.cbSize = sizeof(wc);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = windowProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wc.lpszClassName = L"OuzelWindow";
RegisterClassExW(&wc);
DWORD style = WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
int x = CW_USEDEFAULT;
int y = CW_USEDEFAULT;
if (_fullscreen)
{
style = WS_POPUP;
x = 0;
y = 0;
}
RECT windowRect = { 0, 0, (int)_size.width, (int)_size.height };
AdjustWindowRect(&windowRect, style, FALSE);
_window = CreateWindowExW(
NULL,
L"OuzelWindow",
L"Ouzel",
style,
x,
y,
windowRect.right - windowRect.left,
windowRect.bottom - windowRect.top,
NULL,
NULL,
hInstance,
NULL);
SetWindowLongPtrW(_window, GWLP_USERDATA, (LONG_PTR)this);
ShowWindow(_window, SW_SHOW);
}
void RendererD3D11::initD3D11()
{
DXGI_SWAP_CHAIN_DESC swapChainDesc;
memset(&swapChainDesc, 0, sizeof(swapChainDesc));
swapChainDesc.BufferDesc.Width = (int)_size.width;
swapChainDesc.BufferDesc.Height = (int)_size.height;
swapChainDesc.BufferDesc.RefreshRate.Numerator = _fullscreen ? 60 : 0; // TODO refresh rate?
swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE;
swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_STRETCHED;
swapChainDesc.SampleDesc.Count = 1; // TODO MSAA?
swapChainDesc.SampleDesc.Quality = 0;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.BufferCount = 1;
swapChainDesc.OutputWindow = _window;
swapChainDesc.Windowed = _fullscreen == false;
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
UINT deviceCreationFlags = 0;
#if D3D11_DEBUG
deviceCreationFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
HRESULT hr = D3D11CreateDeviceAndSwapChain(
NULL, // adapter
D3D_DRIVER_TYPE_HARDWARE,
NULL, // software rasterizer (unused)
deviceCreationFlags,
NULL, // feature levels
0, // ^^
D3D11_SDK_VERSION,
&swapChainDesc,
&_swapChain,
&_device,
NULL,
&_context
);
if (FAILED(hr))
{
log("Failed to create the D3D11 device");
return;
}
// Backbuffer
hr = _swapChain->GetBuffer(0, IID_ID3D11Texture2D, (void**)&_backBuffer);
if (FAILED(hr) || _backBuffer == NULL)
{
log("Failed to retrieve D3D11 backbuffer");
return;
}
hr = _device->CreateRenderTargetView(_backBuffer, NULL, &_rtView);
if (FAILED(hr) || _rtView == NULL)
{
log("Failed to create D3D11 render target view");
return;
}
// Sampler state
D3D11_SAMPLER_DESC samplerStateDesc =
{
D3D11_FILTER_MIN_MAG_MIP_LINEAR,
D3D11_TEXTURE_ADDRESS_WRAP,
D3D11_TEXTURE_ADDRESS_WRAP,
D3D11_TEXTURE_ADDRESS_WRAP,
0, 1, D3D11_COMPARISON_NEVER,{ 0,0,0,0 }, 0, D3D11_FLOAT32_MAX
};
hr = _device->CreateSamplerState(&samplerStateDesc, &_samplerState);
if (FAILED(hr) || !_samplerState)
{
log("Failed to create D3D11 sampler state");
return;
}
// Rasterizer state
D3D11_RASTERIZER_DESC rasterStateDesc =
{
D3D11_FILL_SOLID,
D3D11_CULL_NONE,
FALSE, // front = ccw?
0, 0, 0, // depth bias, clamp, slope scale
FALSE, // depth clip
FALSE, // scissor test
FALSE, // TODO MSAA enable?
TRUE, // AA lines
};
hr = _device->CreateRasterizerState(&rasterStateDesc, &_rasterizerState);
if (FAILED(hr) || !_rasterizerState)
{
log("Failed to create D3D11 rasterizer state");
return;
}
// Blending state
D3D11_BLEND_DESC blendStateDesc = { FALSE, FALSE }; // alpha to coverage, independent blend
D3D11_RENDER_TARGET_BLEND_DESC targetBlendDesc =
{
TRUE, // enable blending
D3D11_BLEND_SRC_ALPHA, D3D11_BLEND_INV_SRC_ALPHA, D3D11_BLEND_OP_ADD, // color blend source/dest factors, op
D3D11_BLEND_SRC_ALPHA, D3D11_BLEND_INV_SRC_ALPHA, D3D11_BLEND_OP_ADD, // alpha blend source/dest factors, op
D3D11_COLOR_WRITE_ENABLE_ALL, // color write mask
};
blendStateDesc.RenderTarget[0] = targetBlendDesc;
hr = _device->CreateBlendState(&blendStateDesc, &_blendState);
if (FAILED(hr) || !_blendState)
{
log("Failed to create D3D11 blend state");
return;
}
// Depth/stencil state
D3D11_DEPTH_STENCIL_DESC depthStencilStateDesc =
{
FALSE, // enable depth?
// ...
};
hr = _device->CreateDepthStencilState(&depthStencilStateDesc, &_depthStencilState);
if (FAILED(hr) || !_depthStencilState)
{
log("Failed to create D3D11 depth stencil state");
return;
}
Shader* textureShader = loadShaderFromFiles("ps_texture.cso", "vs_common.cso");
assert(textureShader && "Failed to load texture shader");
_shaders[SHADER_TEXTURE] = textureShader;
D3D11_VIEWPORT viewport = { 0, 0, _size.width, _size.height, 0.0f, 1.0f };
_context->RSSetViewports(1, &viewport);
_context->OMSetRenderTargets(1, &_rtView, nullptr);
}
void RendererD3D11::clear()
{
float color[4] = { _clearColor.getR(), _clearColor.getG(), _clearColor.getB(), _clearColor.getA() };
_context->ClearRenderTargetView(_rtView, color);
}
void RendererD3D11::flush()
{
_swapChain->Present(1 /* TODO vsync off? */, 0);
}
bool RendererD3D11::activateTexture(Texture* texture, uint32_t layer)
{
return true;
}
}
<|endoftext|> |
<commit_before>#ifndef VSMC_UTILITY_PROGRAM_OPTION_HPP
#define VSMC_UTILITY_PROGRAM_OPTION_HPP
#include <vsmc/internal/common.hpp>
namespace vsmc {
/// \brief Program option base class
/// \ingroup Option
class ProgramOptionBase
{
public :
ProgramOptionBase () {}
ProgramOptionBase (const ProgramOptionBase &) {}
ProgramOptionBase &operator= (const ProgramOptionBase &) {return *this;}
virtual bool set (const std::string &) = 0;
virtual void print_help () const = 0;
virtual ProgramOptionBase *clone () const = 0;
virtual ~ProgramOptionBase () {}
}; // class ProgramOptionBase
/// \brief Class that store an option and its default value
/// \ingroup Option
template <typename T>
class ProgramOption : public ProgramOptionBase
{
public :
/// \brief Value type of this option
typedef T value_type;
/// \brief Construct an option that can store a single value
///
/// \param oname Name of the option in the format `--name`
/// \param desc A descritpion stream of the option
/// \param ptr The destination that store the option value
ProgramOption (const std::string &oname, const std::string &desc, T *ptr) :
oname_(oname), desc_(desc), ptr_(ptr), vec_ptr_(VSMC_NULLPTR),
has_default_(false) {}
/// \brief Construct an option that can store multiple values
///
/// \param oname Name of the option in the format `--name`. The option can
/// be specified multiple times on the command line. Each value will be
/// stored within the vector
/// \param desc A descritpion stream of the option
/// \param ptr The destination that store the option value
ProgramOption (const std::string &oname, const std::string &desc,
std::vector<T> *ptr) :
oname_(oname), desc_(desc), ptr_(VSMC_NULLPTR), vec_ptr_(ptr),
has_default_(false) {}
/// \brief Construct an option that can store a single value with a default
/// value
template <typename V>
ProgramOption (const std::string &oname, const std::string &desc,
T *ptr, const V &val) :
oname_(oname), desc_(desc), ptr_(ptr), vec_ptr_(VSMC_NULLPTR),
default_(static_cast<T>(val)), has_default_(true) {*ptr = default_;}
/// \brief Construct an option that can store multiple values with a
/// default value
template <typename V>
ProgramOption (const std::string &oname, const std::string &desc,
std::vector<T> *ptr, const V &val) :
oname_(oname), desc_(desc), ptr_(VSMC_NULLPTR), vec_ptr_(ptr),
default_(static_cast<T>(val)), has_default_(true)
{vec_ptr_->push_back(default_);}
bool set (const std::string &sval)
{
std::stringstream ss;
ss << sval;
T tval;
ss >> tval;
if (ss.fail()) {
std::fprintf(stderr, "Invalid value for option %s: %s\n",
oname_.c_str(), sval.c_str());
return false;
}
if (ptr_) *ptr_ = tval;
if (vec_ptr_) vec_ptr_->push_back(tval);
return true;
}
/// \brief Print help information
void print_help () const
{
std::cout << " " << std::setw(20) << std::left << oname_ << desc_;
if (has_default_)
std::cout << " (default: " << default_ << ")";
std::cout << std::endl;
}
ProgramOptionBase *clone () const
{
ProgramOptionBase *ptr = new ProgramOption<T>(*this);
return ptr;
}
private :
std::string oname_;
std::string desc_;
T *const ptr_;
std::vector<T> *const vec_ptr_;
T default_;
bool has_default_;
}; // class ProgramOption
/// \brief A map of ProgramOption
/// \ingroup Option
///
/// \details
/// Basic example:
/// \code
/// int main (int argc, char **argv)
/// {
/// double Value1;
/// double Value2;
/// std::vector<double> Value3;
/// std::vector<double> Value4;
/// ProgramOptionMap Map;
/// Map.add<double>("option1", "option description string 1", &Value1);
/// Map.add<double>("option2", "option description string 2", &Value2);
/// Map.add<double>("option3", "option description string 3", &Value3);
/// Map.add<double>("option4", "option description string 4", &Value4, 401);
/// if (Map.process(argc, argv)) // Help info was printed
/// return 0;
///
/// std::cout << Value1 << std::endl;
/// std::cout << Value2 << std::endl;
/// for (std::size_t i = 0; i != Value3.size(); ++i)
/// std::cout << Value3[i] << std::endl;
/// for (std::size_t i = 0; i != Value4.size(); ++i)
/// std::cout << Value4[i] << std::endl;
/// }
/// \endcode
/// And if on the command line,
/// \code
/// ./prog --option1 101 --option2 201 --option2 202 --option3 301 --option3 202 --option4 402
/// \end
/// will produce the output
/// \code
/// 101
/// 202
/// 301
/// 302
/// 401
/// 402
/// \endcode
/// An option may be specified multiple times on the command line. If the
/// option's value type is a specialization of std::vector, then all values
/// will be stored. Otherwise only the last one will be stored. A default value
/// may be specified for an option. If an option's value type is a
/// specializaiton of std::vector, then values specified on the command line
/// will be appended to the destination vector instead of override the defualt
/// value.
///
/// If add an option with a name that already exists, then it overrides the
/// previous one
class ProgramOptionMap
{
public :
typedef std::map<std::string, std::pair<ProgramOptionBase *, std::size_t> >
option_map_type;
ProgramOptionMap () {}
ProgramOptionMap (const ProgramOptionMap &other) :
option_map_(other.option_map_)
{
for (option_map_type::iterator iter = option_map_.begin();
iter != option_map_.end(); ++iter) {
if (iter->second.first)
iter->second.first = iter->second.first->clone();
}
}
ProgramOptionMap &operator= (const ProgramOptionMap &other)
{
if (this != &other) {
for (option_map_type::iterator iter = option_map_.begin();
iter != option_map_.end(); ++iter) {
if (iter->second.first)
delete iter->second.first;
}
option_map_ = other.option_map_;
for (option_map_type::iterator iter = option_map_.begin();
iter != option_map_.end(); ++iter) {
if (iter->second.first)
iter->second.first = iter->second.first->clone();
}
}
return *this;
}
~ProgramOptionMap ()
{
for (option_map_type::iterator iter = option_map_.begin();
iter != option_map_.end(); ++iter) {
if (iter->second.first)
delete iter->second.first;
}
}
/// \brief Add an option
///
/// \param name Name of the option, on command name it shall be specified
/// by --name
/// \param desc A descritpion stream of the option
/// \param ptr The destination that store the option value
template <typename T, typename Dest>
ProgramOptionMap &add (const std::string &name, const std::string &desc,
Dest *ptr)
{
const std::string oname("--" + name);
ProgramOptionBase *optr = new ProgramOption<T>(oname, desc, ptr);
add_option(oname, optr);
return *this;
}
/// \brief Add an option with a default value
template <typename T, typename Dest, typename V>
ProgramOptionMap &add (const std::string &name, const std::string &desc,
Dest *ptr, const V &val)
{
const std::string oname("--" + name);
ProgramOptionBase *optr = new ProgramOption<T>(oname, desc, ptr, val);
add_option(oname, optr);
return *this;
}
ProgramOptionMap &remove (const std::string &name)
{
option_map_type::iterator iter = option_map_.find("--" + name);
if (iter != option_map_.end()) {
if (iter->second.first)
delete iter->second.first;
option_map_.erase(iter);
}
return *this;
}
/// \brief Process the options
///
/// \details
/// If the option "--help" is given at the commad line, then this function
/// does not process any other options. It merely process the options
/// --help by printing the help information.
///
/// \param argc The first argument of the `main` function
/// \param argv The second argument of the `main` function
///
/// \return `true` If the option `--help` has been specified on the command
/// line. Otherwise `false`.
bool process (int argc, const char **argv)
{
for (int ac = 1; ac != argc; ++ac) {
if (!std::strcmp(argv[ac], "--help")) {
for (option_map_type::iterator iter = option_map_.begin();
iter != option_map_.end(); ++iter) {
iter->second.first->print_help();
}
return true;
}
}
for (int ac = 1; ac < argc - 1; ++ac) {
if (process_option(argv[ac], argv[ac + 1]))
++ac;
}
return false;
}
/// \brief Process the options
bool process (int argc, char **argv)
{
const char **cargv = new const char *[argc];
for (int i = 0; i != argc; ++i)
cargv[i] = argv[i];
return process(argc, cargv);
}
/// \brief Count the number of occurence of an option on the command line
/// given its name
std::size_t count (const std::string &name) const
{
option_map_type::const_iterator iter = option_map_.find("--" + name);
if (iter != option_map_.end())
return iter->second.second;
else
return 0;
}
private :
option_map_type option_map_;
void add_option (const std::string &oname, ProgramOptionBase *optr)
{
std::pair<option_map_type::iterator, bool> set =
option_map_.insert(std::make_pair(oname,
std::make_pair(optr, static_cast<std::size_t>(0))));
if (!set.second) {
if (set.first->second.first)
delete set.first->second.first;
set.first->second.first = optr;
}
}
bool process_option (const std::string &oname, const std::string &sval)
{
option_map_type::iterator iter = option_map_.find(oname);
if (iter == option_map_.end())
return false;
if (!iter->second.first->set(sval))
return false;
++iter->second.second;
return true;
}
}; // class ProgramOptionMap
} // namespace vsmc
#endif // VSMC_UTILITY_PROGRAM_OPTION_HPP
<commit_msg>avoid construction of stringstream<commit_after>#ifndef VSMC_UTILITY_PROGRAM_OPTION_HPP
#define VSMC_UTILITY_PROGRAM_OPTION_HPP
#include <vsmc/internal/common.hpp>
namespace vsmc {
/// \brief Program option base class
/// \ingroup Option
class ProgramOptionBase
{
public :
ProgramOptionBase () {}
ProgramOptionBase (const ProgramOptionBase &) {}
ProgramOptionBase &operator= (const ProgramOptionBase &) {return *this;}
virtual bool set (std::stringstream &ss, const std::string &) = 0;
virtual void print_help () const = 0;
virtual ProgramOptionBase *clone () const = 0;
virtual ~ProgramOptionBase () {}
}; // class ProgramOptionBase
/// \brief Class that store an option and its default value
/// \ingroup Option
template <typename T>
class ProgramOption : public ProgramOptionBase
{
public :
typedef T value_type;
ProgramOption (const std::string &oname, const std::string &desc, T *ptr) :
oname_(oname), desc_(desc), ptr_(ptr), vec_ptr_(VSMC_NULLPTR),
default_(T()), has_default_(false) {}
ProgramOption (const std::string &oname, const std::string &desc,
std::vector<T> *ptr) :
oname_(oname), desc_(desc), ptr_(VSMC_NULLPTR), vec_ptr_(ptr),
default_(T()), has_default_(false) {}
template <typename V>
ProgramOption (const std::string &oname, const std::string &desc,
T *ptr, const V &val) :
oname_(oname), desc_(desc), ptr_(ptr), vec_ptr_(VSMC_NULLPTR),
default_(static_cast<T>(val)), has_default_(true) {*ptr = default_;}
template <typename V>
ProgramOption (const std::string &oname, const std::string &desc,
std::vector<T> *ptr, const V &val) :
oname_(oname), desc_(desc), ptr_(VSMC_NULLPTR), vec_ptr_(ptr),
default_(static_cast<T>(val)), has_default_(true)
{vec_ptr_->push_back(default_);}
bool set (std::stringstream &ss, const std::string &sval)
{
ss.clear();
ss.str(std::string());
ss << sval;
if (ss.fail()) {
std::fprintf(stderr, "Failed to read input of option '%s': %s\n",
oname_.c_str(), sval.c_str());
ss.clear();
return false;
}
T tval;
ss >> tval;
if (ss.fail()) {
std::fprintf(stderr, "Failed to set value of option '%s': %s\n",
oname_.c_str(), sval.c_str());
ss.clear();
return false;
}
if (ptr_) *ptr_ = tval;
if (vec_ptr_) vec_ptr_->push_back(tval);
return true;
}
void print_help () const
{
std::cout << " " << std::setw(20) << std::left << oname_ << desc_;
if (has_default_)
std::cout << " (default: " << default_ << ")";
std::cout << std::endl;
}
ProgramOptionBase *clone () const
{
ProgramOptionBase *ptr = new ProgramOption<T>(*this);
return ptr;
}
private :
std::string oname_;
std::string desc_;
T *const ptr_;
std::vector<T> *const vec_ptr_;
T default_;
bool has_default_;
}; // class ProgramOption
/// \brief A map of ProgramOption
/// \ingroup Option
///
/// \details
/// Basic example:
/// \code
/// int main (int argc, char **argv)
/// {
/// double Value1;
/// double Value2;
/// std::vector<double> Value3;
/// std::vector<double> Value4;
/// ProgramOptionMap Map;
/// Map.add<double>("option1", "option description string 1", &Value1);
/// Map.add<double>("option2", "option description string 2", &Value2);
/// Map.add<double>("option3", "option description string 3", &Value3);
/// Map.add<double>("option4", "option description string 4", &Value4, 401);
/// if (Map.process(argc, argv)) // Help info was printed
/// return 0;
///
/// std::cout << Value1 << std::endl;
/// std::cout << Value2 << std::endl;
/// for (std::size_t i = 0; i != Value3.size(); ++i)
/// std::cout << Value3[i] << std::endl;
/// for (std::size_t i = 0; i != Value4.size(); ++i)
/// std::cout << Value4[i] << std::endl;
/// }
/// \endcode
/// And if on the command line,
/// \code
/// ./prog --option1 101 --option2 201 --option2 202 --option3 301 --option3 202 --option4 402
/// \end
/// will produce the output
/// \code
/// 101
/// 202
/// 301
/// 302
/// 401
/// 402
/// \endcode
/// An option may be specified multiple times on the command line. If the
/// option's value type is a specialization of std::vector, then all values
/// will be stored. Otherwise only the last one will be stored. A default value
/// may be specified for an option. If an option's value type is a
/// specializaiton of std::vector, then values specified on the command line
/// will be appended to the destination vector instead of override the defualt
/// value.
///
/// If add an option with a name that already exists, then it overrides the
/// previous one
class ProgramOptionMap
{
public :
typedef std::map<std::string, std::pair<ProgramOptionBase *, std::size_t> >
option_map_type;
ProgramOptionMap () {}
ProgramOptionMap (const ProgramOptionMap &other) :
option_map_(other.option_map_)
{
for (option_map_type::iterator iter = option_map_.begin();
iter != option_map_.end(); ++iter) {
if (iter->second.first)
iter->second.first = iter->second.first->clone();
}
}
ProgramOptionMap &operator= (const ProgramOptionMap &other)
{
if (this != &other) {
for (option_map_type::iterator iter = option_map_.begin();
iter != option_map_.end(); ++iter) {
if (iter->second.first)
delete iter->second.first;
}
option_map_ = other.option_map_;
for (option_map_type::iterator iter = option_map_.begin();
iter != option_map_.end(); ++iter) {
if (iter->second.first)
iter->second.first = iter->second.first->clone();
}
}
return *this;
}
~ProgramOptionMap ()
{
for (option_map_type::iterator iter = option_map_.begin();
iter != option_map_.end(); ++iter) {
if (iter->second.first)
delete iter->second.first;
}
}
/// \brief Add an option
///
/// \param name Name of the option, on command name it shall be specified
/// by --name
/// \param desc A descritpion stream of the option
/// \param ptr The destination that store the option value
template <typename T, typename Dest>
ProgramOptionMap &add (const std::string &name, const std::string &desc,
Dest *ptr)
{
const std::string oname("--" + name);
ProgramOptionBase *optr = new ProgramOption<T>(oname, desc, ptr);
add_option(oname, optr);
return *this;
}
/// \brief Add an option with a default value
template <typename T, typename Dest, typename V>
ProgramOptionMap &add (const std::string &name, const std::string &desc,
Dest *ptr, const V &val)
{
const std::string oname("--" + name);
ProgramOptionBase *optr = new ProgramOption<T>(oname, desc, ptr, val);
add_option(oname, optr);
return *this;
}
ProgramOptionMap &remove (const std::string &name)
{
option_map_type::iterator iter = option_map_.find("--" + name);
if (iter != option_map_.end()) {
if (iter->second.first)
delete iter->second.first;
option_map_.erase(iter);
}
return *this;
}
/// \brief Process the options
///
/// \details
/// If the option "--help" is given at the commad line, then this function
/// does not process any other options. It merely process the options
/// --help by printing the help information.
///
/// \param argc The first argument of the `main` function
/// \param argv The second argument of the `main` function
///
/// \return `true` If the option `--help` has been specified on the command
/// line. Otherwise `false`.
bool process (int argc, const char **argv)
{
for (int ac = 1; ac != argc; ++ac) {
if (!std::strcmp(argv[ac], "--help")) {
for (option_map_type::iterator iter = option_map_.begin();
iter != option_map_.end(); ++iter) {
iter->second.first->print_help();
}
return true;
}
}
for (int ac = 1; ac < argc - 1; ++ac) {
if (process_option(argv[ac], argv[ac + 1]))
++ac;
}
return false;
}
/// \brief Process the options
bool process (int argc, char **argv)
{
const char **cargv = new const char *[argc];
for (int i = 0; i != argc; ++i)
cargv[i] = argv[i];
return process(argc, cargv);
}
/// \brief Count the number of occurence of an option on the command line
/// given its name
std::size_t count (const std::string &name) const
{
option_map_type::const_iterator iter = option_map_.find("--" + name);
if (iter != option_map_.end())
return iter->second.second;
else
return 0;
}
private :
option_map_type option_map_;
std::stringstream ss_;
void add_option (const std::string &oname, ProgramOptionBase *optr)
{
std::pair<option_map_type::iterator, bool> set =
option_map_.insert(std::make_pair(oname,
std::make_pair(optr, static_cast<std::size_t>(0))));
if (!set.second) {
if (set.first->second.first)
delete set.first->second.first;
set.first->second.first = optr;
}
}
bool process_option (const std::string &oname, const std::string &sval)
{
option_map_type::iterator iter = option_map_.find(oname);
if (iter == option_map_.end())
return false;
if (!iter->second.first->set(ss_, sval))
return false;
++iter->second.second;
return true;
}
}; // class ProgramOptionMap
} // namespace vsmc
#endif // VSMC_UTILITY_PROGRAM_OPTION_HPP
<|endoftext|> |
<commit_before>#ifndef WART_VARIANT_DETAIL_VARIANT_HPP
#define WART_VARIANT_DETAIL_VARIANT_HPP
#include "enable_if_elem.hpp"
#include "elem_index.hpp"
#include "../../all.hpp"
#include "../../enable_if_move_constructible.hpp"
#include "../../union.hpp"
#include <type_traits>
#include <utility>
namespace wart { namespace detail { namespace variant {
template <typename... T>
using union_t = wart::union_t<T...>;
template <typename... T>
class variant;
class uninitialized {};
template <typename F, typename... ArgTypes>
using common_result_of =
std::common_type<typename std::result_of<F(ArgTypes)>::type...>;
struct destroy {
template <typename T>
void operator()(T&& value) {
using type = typename std::remove_reference<T>::type;
std::forward<T>(value).~type();
}
};
struct copy_construct {
void* storage;
template <typename T>
void operator()(T const& value) {
new (storage) T(value);
}
};
template <typename... T>
struct copy_construct_index {
void* storage;
template <typename U>
int operator()(U const& value) {
new (storage) U(value);
return elem_index<U, T...>::value;
}
};
struct move_construct {
void* storage;
template <typename T>
typename enable_if_move_constructible<T>::type operator()(T&& value) {
new (storage) T(std::move(value));
}
};
template <typename... T>
struct move_construct_index {
void* storage;
template <typename U>
typename enable_if_move_constructible<U, int>::type operator()(U&& value) {
new (storage) U(std::move(value));
return elem_index<U, T...>::value;
}
};
template <typename... T>
struct copy_assign {
union_t<uninitialized, T...> union_;
template <typename U>
void operator()(U const& value) {
union_get<U>(union_) = value;
}
};
template <typename... T>
struct copy_assign_reindex {
variant<T...>& variant;
template <typename U>
void operator()(U const& value) {
if (variant.tag_ == elem_index<U, T...>::value) {
union_get<U>(variant.union_) = value;
} else {
variant.accept(destroy{});
new (&variant.union_) U(value);
variant.tag_ = elem_index<U, T...>::value;
}
}
};
template <typename... T>
struct move_assign {
union_t<uninitialized, T...> union_;
template <typename U>
typename enable_if_move_constructible<U>::type operator()(U&& value) {
union_get<U>(union_) = std::move(value);
}
};
template <typename... T>
struct move_assign_reindex {
variant<T...>& variant;
template <typename U>
typename enable_if_move_constructible<U>::type operator()(U&& value) {
if (variant.tag_ == elem_index<U, T...>::value) {
union_get<U>(variant.union_) = std::move(value);
} else {
variant.accept(destroy{});
new (&variant.union_) U(std::move(value));
variant.tag_ = elem_index<U, T...>::value;
}
}
};
struct trivially_destructible {};
template <typename Variant>
struct not_trivially_destructible {
~not_trivially_destructible() {
static_cast<Variant*>(this)->accept(destroy{});
}
};
template <typename... T>
class variant:
public
std::conditional<all<std::is_trivially_destructible<T>::value...>::value,
trivially_destructible,
not_trivially_destructible<variant<T...>>>::type {
int tag_;
union_t<uninitialized, T...> union_;
public:
template <typename F>
using result_of = common_result_of<F, T...>;
template <typename F>
using result_of_t = typename result_of<F>::type;
template <typename U>
constexpr
variant(U const& value,
typename enable_if_elem<U, T...>::type* = nullptr):
tag_{elem_index<U, T...>::value},
union_{value} {}
template <typename U>
constexpr
variant(U&& value,
typename enable_if_elem<U, T...>::type* = nullptr,
typename enable_if_move_constructible<U>::type* = nullptr):
tag_{elem_index<U, T...>::value},
union_{std::move(value)} {}
variant(variant const& rhs):
tag_{rhs.tag_} {
rhs.accept(copy_construct{&union_});
}
template <typename... U>
variant(variant<U...> const& rhs,
typename std::enable_if<all<elem<U, T...>::value...>::value
>::type* = nullptr):
tag_{rhs.accept(copy_construct_index<T...>{&union_})} {}
variant(variant&& rhs):
tag_{rhs.tag_} {
std::move(rhs).accept(move_construct{&union_});
}
template <typename... U>
variant(variant<U...>&& rhs,
typename std::enable_if<
all<elem<U, T...>::value...>::value
>::type* = nullptr):
tag_{std::move(rhs).accept(move_construct_index<T...>{&union_})} {}
variant& operator=(variant const& rhs) & {
static_assert(all<std::is_nothrow_copy_constructible<T>::value...>::value,
"all template arguments T must be nothrow copy constructible in class template variant");
if (this == &rhs) {
return *this;
}
if (tag_ == rhs.tag_) {
rhs.accept(copy_assign<T...>{union_});
} else {
accept(destroy{});
rhs.accept(copy_construct{&union_});
tag_ = rhs.tag_;
}
return *this;
}
template <typename... U>
variant& operator=(variant<U...> const& rhs) & {
static_assert(all<std::is_nothrow_copy_constructible<T>::value...>::value,
"all template arguments T must be nothrow copy constructible in class template variant");
rhs.accept(copy_assign_reindex<T...>{*this});
return *this;
}
variant& operator=(variant&& rhs) & {
static_assert(all<std::is_nothrow_move_constructible<T>::value...>::value,
"all template arguments T must be nothrow move constructible in class template variant");
if (this == &rhs) {
return *this;
}
if (tag_ == rhs.tag_) {
std::move(rhs).accept(move_assign<T...>{union_});
} else {
accept(destroy{});
std::move(rhs).accept(move_construct{&union_});
tag_ = rhs.tag_;
}
return *this;
}
template <typename... U>
variant& operator=(variant<U...>&& rhs) & {
static_assert(all<std::is_nothrow_copy_constructible<T>::value...>::value,
"all template arguments T must be nothrow copy constructible in class template variant");
std::move(rhs).accept(move_assign_reindex<T...>{*this});
return *this;
}
template <typename F>
result_of_t<F> accept(F&& f) const& {
using call = result_of_t<F&&> (*)(F&& f, union_t<uninitialized, T...> const&);
static call calls[] {
[](F&& f, union_t<uninitialized, T...> const& value) {
return std::forward<F>(f)(union_get<T>(value));
}...
};
return calls[tag_](std::forward<F>(f), union_);
}
template <typename F>
result_of_t<F> accept(F&& f) & {
using call = result_of_t<F&&> (*)(F&& f, union_t<uninitialized, T...>&);
static call calls[] {
[](F&& f, union_t<uninitialized, T...>& value) {
return std::forward<F>(f)(union_get<T>(value));
}...
};
return calls[tag_](std::forward<F>(f), union_);
}
template <typename F>
result_of_t<F> accept(F&& f) && {
using call = result_of_t<F> (*)(F&& f, union_t<uninitialized, T...>&&);
static call calls[] {
[](F&& f, union_t<uninitialized, T...>&& value) {
return std::forward<F>(f)(std::move(union_get<T>(value)));
}...
};
return calls[tag_](std::forward<F>(f), std::move(union_));
}
friend
struct copy_assign_reindex<T...>;
friend
struct move_assign_reindex<T...>;
};
}}}
#endif
<commit_msg>private inheritance<commit_after>#ifndef WART_VARIANT_DETAIL_VARIANT_HPP
#define WART_VARIANT_DETAIL_VARIANT_HPP
#include "enable_if_elem.hpp"
#include "elem_index.hpp"
#include "../../all.hpp"
#include "../../enable_if_move_constructible.hpp"
#include "../../union.hpp"
#include <type_traits>
#include <utility>
namespace wart { namespace detail { namespace variant {
template <typename... T>
using union_t = wart::union_t<T...>;
template <typename... T>
class variant;
class uninitialized {};
template <typename F, typename... ArgTypes>
using common_result_of =
std::common_type<typename std::result_of<F(ArgTypes)>::type...>;
struct destroy {
template <typename T>
void operator()(T&& value) {
using type = typename std::remove_reference<T>::type;
std::forward<T>(value).~type();
}
};
struct copy_construct {
void* storage;
template <typename T>
void operator()(T const& value) {
new (storage) T(value);
}
};
template <typename... T>
struct copy_construct_index {
void* storage;
template <typename U>
int operator()(U const& value) {
new (storage) U(value);
return elem_index<U, T...>::value;
}
};
struct move_construct {
void* storage;
template <typename T>
typename enable_if_move_constructible<T>::type operator()(T&& value) {
new (storage) T(std::move(value));
}
};
template <typename... T>
struct move_construct_index {
void* storage;
template <typename U>
typename enable_if_move_constructible<U, int>::type operator()(U&& value) {
new (storage) U(std::move(value));
return elem_index<U, T...>::value;
}
};
template <typename... T>
struct copy_assign {
union_t<uninitialized, T...> union_;
template <typename U>
void operator()(U const& value) {
union_get<U>(union_) = value;
}
};
template <typename... T>
struct copy_assign_reindex {
variant<T...>& variant;
template <typename U>
void operator()(U const& value) {
if (variant.tag_ == elem_index<U, T...>::value) {
union_get<U>(variant.union_) = value;
} else {
variant.accept(destroy{});
new (&variant.union_) U(value);
variant.tag_ = elem_index<U, T...>::value;
}
}
};
template <typename... T>
struct move_assign {
union_t<uninitialized, T...> union_;
template <typename U>
typename enable_if_move_constructible<U>::type operator()(U&& value) {
union_get<U>(union_) = std::move(value);
}
};
template <typename... T>
struct move_assign_reindex {
variant<T...>& variant;
template <typename U>
typename enable_if_move_constructible<U>::type operator()(U&& value) {
if (variant.tag_ == elem_index<U, T...>::value) {
union_get<U>(variant.union_) = std::move(value);
} else {
variant.accept(destroy{});
new (&variant.union_) U(std::move(value));
variant.tag_ = elem_index<U, T...>::value;
}
}
};
struct trivially_destructible {};
template <typename Variant>
struct not_trivially_destructible {
~not_trivially_destructible() {
static_cast<Variant*>(this)->accept(destroy{});
}
};
template <typename... T>
class variant:
std::conditional<all<std::is_trivially_destructible<T>::value...>::value,
trivially_destructible,
not_trivially_destructible<variant<T...>>>::type {
int tag_;
union_t<uninitialized, T...> union_;
public:
template <typename F>
using result_of = common_result_of<F, T...>;
template <typename F>
using result_of_t = typename result_of<F>::type;
template <typename U>
constexpr
variant(U const& value,
typename enable_if_elem<U, T...>::type* = nullptr):
tag_{elem_index<U, T...>::value},
union_{value} {}
template <typename U>
constexpr
variant(U&& value,
typename enable_if_elem<U, T...>::type* = nullptr,
typename enable_if_move_constructible<U>::type* = nullptr):
tag_{elem_index<U, T...>::value},
union_{std::move(value)} {}
variant(variant const& rhs):
tag_{rhs.tag_} {
rhs.accept(copy_construct{&union_});
}
template <typename... U>
variant(variant<U...> const& rhs,
typename std::enable_if<all<elem<U, T...>::value...>::value
>::type* = nullptr):
tag_{rhs.accept(copy_construct_index<T...>{&union_})} {}
variant(variant&& rhs):
tag_{rhs.tag_} {
std::move(rhs).accept(move_construct{&union_});
}
template <typename... U>
variant(variant<U...>&& rhs,
typename std::enable_if<
all<elem<U, T...>::value...>::value
>::type* = nullptr):
tag_{std::move(rhs).accept(move_construct_index<T...>{&union_})} {}
variant& operator=(variant const& rhs) & {
static_assert(all<std::is_nothrow_copy_constructible<T>::value...>::value,
"all template arguments T must be nothrow copy constructible in class template variant");
if (this == &rhs) {
return *this;
}
if (tag_ == rhs.tag_) {
rhs.accept(copy_assign<T...>{union_});
} else {
accept(destroy{});
rhs.accept(copy_construct{&union_});
tag_ = rhs.tag_;
}
return *this;
}
template <typename... U>
variant& operator=(variant<U...> const& rhs) & {
static_assert(all<std::is_nothrow_copy_constructible<T>::value...>::value,
"all template arguments T must be nothrow copy constructible in class template variant");
rhs.accept(copy_assign_reindex<T...>{*this});
return *this;
}
variant& operator=(variant&& rhs) & {
static_assert(all<std::is_nothrow_move_constructible<T>::value...>::value,
"all template arguments T must be nothrow move constructible in class template variant");
if (this == &rhs) {
return *this;
}
if (tag_ == rhs.tag_) {
std::move(rhs).accept(move_assign<T...>{union_});
} else {
accept(destroy{});
std::move(rhs).accept(move_construct{&union_});
tag_ = rhs.tag_;
}
return *this;
}
template <typename... U>
variant& operator=(variant<U...>&& rhs) & {
static_assert(all<std::is_nothrow_copy_constructible<T>::value...>::value,
"all template arguments T must be nothrow copy constructible in class template variant");
std::move(rhs).accept(move_assign_reindex<T...>{*this});
return *this;
}
template <typename F>
result_of_t<F> accept(F&& f) const& {
using call = result_of_t<F&&> (*)(F&& f, union_t<uninitialized, T...> const&);
static call calls[] {
[](F&& f, union_t<uninitialized, T...> const& value) {
return std::forward<F>(f)(union_get<T>(value));
}...
};
return calls[tag_](std::forward<F>(f), union_);
}
template <typename F>
result_of_t<F> accept(F&& f) & {
using call = result_of_t<F&&> (*)(F&& f, union_t<uninitialized, T...>&);
static call calls[] {
[](F&& f, union_t<uninitialized, T...>& value) {
return std::forward<F>(f)(union_get<T>(value));
}...
};
return calls[tag_](std::forward<F>(f), union_);
}
template <typename F>
result_of_t<F> accept(F&& f) && {
using call = result_of_t<F> (*)(F&& f, union_t<uninitialized, T...>&&);
static call calls[] {
[](F&& f, union_t<uninitialized, T...>&& value) {
return std::forward<F>(f)(std::move(union_get<T>(value)));
}...
};
return calls[tag_](std::forward<F>(f), std::move(union_));
}
friend
struct copy_assign_reindex<T...>;
friend
struct move_assign_reindex<T...>;
friend
struct not_trivially_destructible<variant<T...>>;
};
}}}
#endif
<|endoftext|> |
<commit_before>
//@HEADER
// ************************************************************************
//
// HPCCG: Simple Conjugate Gradient Benchmark Code
// Copyright (2006) Sandia Corporation
//
// Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
// license for use of this work by or on behalf of the U.S. Government.
//
// BSD 3-Clause License
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
//
// Questions? Contact Michael A. Heroux (maherou@sandia.gov)
//
// ************************************************************************
//@HEADER
/////////////////////////////////////////////////////////////////////////
// Routine to compute an approximate solution to Ax = b where:
// A - known matrix stored as an HPC_Sparse_Matrix struct
// b - known right hand side vector
// x - On entry is initial guess, on exit new approximate solution
// max_iter - Maximum number of iterations to perform, even if
// tolerance is not met.
// tolerance - Stop and assert convergence if norm of residual is <=
// to tolerance.
// niters - On output, the number of iterations actually performed.
/////////////////////////////////////////////////////////////////////////
#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
#include <cmath>
#include "mytimer.hpp"
#include "HPCCG.hpp"
#include <chrono>
#include <vector>
#include <algorithm>
#include "Halide.h"
#define TICK() t0 = mytimer() // Use TICK and TOCK to time a code section
#define TOCK(t) t += mytimer() - t0
double median(std::vector<std::chrono::duration<double, std::milli>> scores)
{
double median;
size_t size = scores.size();
std::sort(scores.begin(), scores.end());
if (size % 2 == 0)
median = (scores[size / 2 - 1].count() + scores[size / 2].count()) / 2;
else
median = scores[size / 2].count();
return median;
}
int HPCCG_tiramisu(HPC_Sparse_Matrix * A,
const double * const b, double * const x,
const int max_iter, const double tolerance, int &niters, double & normr,
double * times, Halide::Buffer<double> &r)
{
int nrow = A->local_nrow;
int ncol = A->local_ncol;
Halide::Buffer<double> p(ncol); // In parallel case, A is rectangular
Halide::Buffer<double> Ap(nrow);
Halide::Buffer<double> rtrans(1);
Halide::Buffer<double> alpha(1);
normr = 0.0;
rtrans(0) = 0.0;
alpha(0) = 0.0;
double oldrtrans = 0.0;
#ifdef USING_MPI
int rank; // Number of MPI processes, My process ID
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
#else
int rank = 0; // Serial case (not using MPI)
#endif
int print_freq = max_iter/10;
if (print_freq>50) print_freq=50;
if (print_freq<1) print_freq=1;
// p is of length ncols, copy x to p for sparse MV operation
waxpby(nrow, 1.0, x, 0.0, x, p.data());
#ifdef USING_MPI
exchange_externals(A,p.data());
#endif
HPC_sparsemv(A, p.data(), Ap.data());
waxpby(nrow, 1.0, b, -1.0, Ap.data(), r.data());
ddot(nrow, r.data(), r.data(), rtrans.data());
normr = sqrt(rtrans(0));
if (rank==0) cout << "Initial Residual = "<< normr << endl;
std::vector<std::chrono::duration<double,std::milli>> duration_vector_one_iter;
std::vector<std::chrono::duration<double,std::milli>> duration_vector_comm;
for(int k=1; k<=max_iter && normr > tolerance; k++ )
{
auto start_one_iter = std::chrono::high_resolution_clock::now();
if (k == 1)
waxpby(nrow, 1.0, r.data(), 0.0, r.data(), p.data());
else
{
oldrtrans = rtrans(0);
ddot (nrow, r.data(), r.data(), rtrans.data()); // r*r -> rtrans. (2*nrow ops)
double beta = rtrans(0)/oldrtrans;
waxpby (nrow, 1.0, r.data(), beta, p.data(), p.data()); // 2*nrow ops
}
normr = sqrt(rtrans(0));
if (rank==0 && (k%print_freq == 0 || k+1 == max_iter))
cout << "Iteration = "<< k << " Residual = "<< normr << endl;
#ifdef USING_MPI
auto start_comm = std::chrono::high_resolution_clock::now();
exchange_externals(A,p.data());
auto end_comm = std::chrono::high_resolution_clock::now();
#endif
HPC_sparsemv(A, p.data(), Ap.data()); // 2*nnz ops
alpha(0) = 0.0;
ddot(nrow, p.data(), Ap.data(), alpha.data()); // p*Ap -> alpha. (2*nrow ops)
alpha(0) = rtrans(0)/alpha(0);
waxpby(nrow, 1.0, x, alpha(0), p.data(), x);// 2*nrow ops
waxpby(nrow, 1.0, r.data(), -alpha(0), Ap.data(), r.data()); // 2*nrow ops
niters = k;
auto end_one_iter = std::chrono::high_resolution_clock::now();
std::chrono::duration<double,std::milli> duration_one_iter = end_one_iter - start_one_iter;
duration_vector_one_iter.push_back(duration_one_iter);
#ifdef USING_MPI
std::chrono::duration<double,std::milli> duration_one_comm = end_comm - start_comm;
duration_vector_one_iter.push_back(duration_one_iter);
#endif
}
// Store times
times[1] = median(duration_vector_one_iter); // Iteration total time
#ifdef USING_MPI
times[5] = median(duration_vector_comm); // exchange boundary time
#endif
return(0);
}
int HPCCG_ref(HPC_Sparse_Matrix * A,
const double * const b, double * const x,
const int max_iter, const double tolerance, int &niters, double & normr,
double * times, double *r)
{
int nrow = A->local_nrow;
int ncol = A->local_ncol;
double * p = new double [ncol]; // In parallel case, A is rectangular
double * Ap = new double [nrow];
normr = 0.0;
double rtrans = 0.0;
double oldrtrans = 0.0;
#ifdef USING_MPI
int rank; // Number of MPI processes, My process ID
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
#else
int rank = 0; // Serial case (not using MPI)
#endif
int print_freq = max_iter/10;
if (print_freq>50) print_freq=50;
if (print_freq<1) print_freq=1;
// p is of length ncols, copy x to p for sparse MV operation
waxpby(nrow, 1.0, x, 0.0, x, p);
#ifdef USING_MPI
exchange_externals(A,p);
#endif
HPC_sparsemv(A, p, Ap);
waxpby(nrow, 1.0, b, -1.0, Ap, r);
ddot(nrow, r, r, &rtrans);
normr = sqrt(rtrans);
if (rank==0) cout << "Initial Residual = "<< normr << endl;
std::vector<std::chrono::duration<double,std::milli>> duration_vector_one_iter;
std::vector<std::chrono::duration<double,std::milli>> duration_vector_comm;
for(int k=1; k<=max_iter && normr > tolerance; k++ )
{
auto start_one_iter = std::chrono::high_resolution_clock::now();
if (k == 1)
waxpby(nrow, 1.0, r, 0.0, r, p);
else
{
oldrtrans = rtrans;
ddot (nrow, r, r, &rtrans); // 2*nrow ops
double beta = rtrans/oldrtrans;
waxpby (nrow, 1.0, r, beta, p, p); // 2*nrow ops
}
normr = sqrt(rtrans);
if (rank==0 && (k%print_freq == 0 || k+1 == max_iter))
cout << "Iteration = "<< k << " Residual = "<< normr << endl;
#ifdef USING_MPI
auto start_comm = std::chrono::high_resolution_clock::now();
exchange_externals(A,p);
auto end_comm = std::chrono::high_resolution_clock::now();
#endif
HPC_sparsemv(A, p, Ap); // 2*nnz ops
double alpha = 0.0;
ddot(nrow, p, Ap, &alpha); // 2*nrow ops
alpha = rtrans/alpha;
waxpby(nrow, 1.0, x, alpha, p, x);// 2*nrow ops
waxpby(nrow, 1.0, r, -alpha, Ap, r); // 2*nrow ops
niters = k;
auto end_one_iter = std::chrono::high_resolution_clock::now();
std::chrono::duration<double,std::milli> duration_one_iter = end_one_iter - start_one_iter;
duration_vector_one_iter.push_back(duration_one_iter);
#ifdef USING_MPI
std::chrono::duration<double,std::milli> duration_one_comm = end_comm - start_comm;
duration_vector_one_iter.push_back(duration_one_iter);
#endif
}
// Store times
times[1] = median(duration_vector_one_iter); // Iteration total time
#ifdef USING_MPI
times[5] = median(duration_vector_comm); // exchange boundary time
#endif
delete [] p;
delete [] Ap;
return(0);
}
<commit_msg>Update HPCCG<commit_after>
//@HEADER
// ************************************************************************
//
// HPCCG: Simple Conjugate Gradient Benchmark Code
// Copyright (2006) Sandia Corporation
//
// Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
// license for use of this work by or on behalf of the U.S. Government.
//
// BSD 3-Clause License
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
//
// Questions? Contact Michael A. Heroux (maherou@sandia.gov)
//
// ************************************************************************
//@HEADER
/////////////////////////////////////////////////////////////////////////
// Routine to compute an approximate solution to Ax = b where:
// A - known matrix stored as an HPC_Sparse_Matrix struct
// b - known right hand side vector
// x - On entry is initial guess, on exit new approximate solution
// max_iter - Maximum number of iterations to perform, even if
// tolerance is not met.
// tolerance - Stop and assert convergence if norm of residual is <=
// to tolerance.
// niters - On output, the number of iterations actually performed.
/////////////////////////////////////////////////////////////////////////
#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
#include <cmath>
#include "mytimer.hpp"
#include "HPCCG.hpp"
#include <chrono>
#include <vector>
#include <algorithm>
#include "Halide.h"
#define TICK() t0 = mytimer() // Use TICK and TOCK to time a code section
#define TOCK(t) t += mytimer() - t0
double median(std::vector<std::chrono::duration<double, std::milli>> scores)
{
double median;
size_t size = scores.size();
std::sort(scores.begin(), scores.end());
if (size % 2 == 0)
median = (scores[size / 2 - 1].count() + scores[size / 2].count()) / 2;
else
median = scores[size / 2].count();
return median;
}
int HPCCG_tiramisu(HPC_Sparse_Matrix * A,
const double * const b, double * const x,
const int max_iter, const double tolerance, int &niters, double & normr,
double * times, Halide::Buffer<double> &r)
{
int nrow = A->local_nrow;
int ncol = A->local_ncol;
Halide::Buffer<double> p(ncol); // In parallel case, A is rectangular
Halide::Buffer<double> Ap(nrow);
Halide::Buffer<double> rtrans(1);
Halide::Buffer<double> alpha(1);
normr = 0.0;
rtrans(0) = 0.0;
alpha(0) = 0.0;
double oldrtrans = 0.0;
#ifdef USING_MPI
int rank; // Number of MPI processes, My process ID
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
#else
int rank = 0; // Serial case (not using MPI)
#endif
int print_freq = max_iter/10;
if (print_freq>50) print_freq=50;
if (print_freq<1) print_freq=1;
// p is of length ncols, copy x to p for sparse MV operation
waxpby(nrow, 1.0, x, 0.0, x, p.data());
#ifdef USING_MPI
exchange_externals(A,p.data());
#endif
HPC_sparsemv(A, p.data(), Ap.data());
waxpby(nrow, 1.0, b, -1.0, Ap.data(), r.data());
ddot(nrow, r.data(), r.data(), rtrans.data());
normr = sqrt(rtrans(0));
if (rank==0) cout << "Initial Residual = "<< normr << endl;
std::vector<std::chrono::duration<double,std::milli>> duration_vector_one_iter;
std::vector<std::chrono::duration<double,std::milli>> duration_vector_comm;
for(int k=1; k<=max_iter && normr > tolerance; k++ )
{
auto start_one_iter = std::chrono::high_resolution_clock::now();
alpha(0) = 0.0;
if (k == 1)
waxpby(nrow, 1.0, r.data(), 0.0, r.data(), p.data()); // r + 0*p -> p
else
{
oldrtrans = rtrans(0);
ddot (nrow, r.data(), r.data(), rtrans.data()); // r*r -> rtrans. (2*nrow ops)
double beta = rtrans(0)/oldrtrans;
waxpby (nrow, 1.0, r.data(), beta, p.data(), p.data()); // r + beta*p -> p. (2*nrow ops)
}
HPC_sparsemv(A, p.data(), Ap.data()); // A*p -> Ap. (2*nnz ops)
ddot(nrow, p.data(), Ap.data(), alpha.data()); // p*Ap -> alpha. (2*nrow ops)
alpha(0) = rtrans(0)/alpha(0);
waxpby(nrow, 1.0, x, alpha(0), p.data(), x);// x + alpha*p -> x. (2*nrow ops)
waxpby(nrow, 1.0, r.data(), -alpha(0), Ap.data(), r.data()); // 2*nrow ops
niters = k;
normr = sqrt(rtrans(0));
if (rank==0 && (k%print_freq == 0 || k+1 == max_iter))
cout << "Iteration = "<< k << " Residual = "<< normr << endl;
auto end_one_iter = std::chrono::high_resolution_clock::now();
std::chrono::duration<double,std::milli> duration_one_iter = end_one_iter - start_one_iter;
duration_vector_one_iter.push_back(duration_one_iter);
#ifdef USING_MPI
std::chrono::duration<double,std::milli> duration_one_comm = end_comm - start_comm;
duration_vector_one_iter.push_back(duration_one_iter);
#endif
}
// Store times
times[1] = median(duration_vector_one_iter); // Iteration total time
#ifdef USING_MPI
times[5] = median(duration_vector_comm); // exchange boundary time
#endif
return(0);
}
int HPCCG_ref(HPC_Sparse_Matrix * A,
const double * const b, double * const x,
const int max_iter, const double tolerance, int &niters, double & normr,
double * times, double *r)
{
int nrow = A->local_nrow;
int ncol = A->local_ncol;
double * p = new double [ncol]; // In parallel case, A is rectangular
double * Ap = new double [nrow];
normr = 0.0;
double rtrans = 0.0;
double oldrtrans = 0.0;
#ifdef USING_MPI
int rank; // Number of MPI processes, My process ID
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
#else
int rank = 0; // Serial case (not using MPI)
#endif
int print_freq = max_iter/10;
if (print_freq>50) print_freq=50;
if (print_freq<1) print_freq=1;
// p is of length ncols, copy x to p for sparse MV operation
waxpby(nrow, 1.0, x, 0.0, x, p);
#ifdef USING_MPI
exchange_externals(A,p);
#endif
HPC_sparsemv(A, p, Ap);
waxpby(nrow, 1.0, b, -1.0, Ap, r);
ddot(nrow, r, r, &rtrans);
normr = sqrt(rtrans);
if (rank==0) cout << "Initial Residual = "<< normr << endl;
std::vector<std::chrono::duration<double,std::milli>> duration_vector_one_iter;
std::vector<std::chrono::duration<double,std::milli>> duration_vector_comm;
for(int k=1; k<=max_iter && normr > tolerance; k++ )
{
auto start_one_iter = std::chrono::high_resolution_clock::now();
if (k == 1)
waxpby(nrow, 1.0, r, 0.0, r, p);
else
{
oldrtrans = rtrans;
ddot (nrow, r, r, &rtrans); // 2*nrow ops
double beta = rtrans/oldrtrans;
waxpby (nrow, 1.0, r, beta, p, p); // 2*nrow ops
}
normr = sqrt(rtrans);
if (rank==0 && (k%print_freq == 0 || k+1 == max_iter))
cout << "Iteration = "<< k << " Residual = "<< normr << endl;
#ifdef USING_MPI
auto start_comm = std::chrono::high_resolution_clock::now();
exchange_externals(A,p);
auto end_comm = std::chrono::high_resolution_clock::now();
#endif
HPC_sparsemv(A, p, Ap); // 2*nnz ops
double alpha = 0.0;
ddot(nrow, p, Ap, &alpha); // 2*nrow ops
alpha = rtrans/alpha;
waxpby(nrow, 1.0, x, alpha, p, x);// 2*nrow ops
waxpby(nrow, 1.0, r, -alpha, Ap, r); // 2*nrow ops
niters = k;
auto end_one_iter = std::chrono::high_resolution_clock::now();
std::chrono::duration<double,std::milli> duration_one_iter = end_one_iter - start_one_iter;
duration_vector_one_iter.push_back(duration_one_iter);
#ifdef USING_MPI
std::chrono::duration<double,std::milli> duration_one_comm = end_comm - start_comm;
duration_vector_one_iter.push_back(duration_one_iter);
#endif
}
// Store times
times[1] = median(duration_vector_one_iter); // Iteration total time
#ifdef USING_MPI
times[5] = median(duration_vector_comm); // exchange boundary time
#endif
delete [] p;
delete [] Ap;
return(0);
}
<|endoftext|> |
<commit_before>/*
* MRustC - Rust Compiler
* - By John Hodge (Mutabah/thePowersGang)
*
* trans/monomorphise.hpp
* - MIR monomorphisation
*/
#include "monomorphise.hpp"
#include <mir/mir.hpp>
namespace {
::MIR::LValue monomorph_LValue(const ::HIR::Crate& crate, const Trans_Params& params, const ::MIR::LValue& tpl)
{
TU_MATCHA( (tpl), (e),
(Variable, return e; ),
(Temporary, return e; ),
(Argument, return e; ),
(Return, return e; ),
(Static,
return params.monomorph(crate, e);
),
(Field,
return ::MIR::LValue::make_Field({
box$(monomorph_LValue(crate, params, *e.val)),
e.field_index
});
),
(Deref,
return ::MIR::LValue::make_Deref({
box$(monomorph_LValue(crate, params, *e.val))
});
),
(Index,
return ::MIR::LValue::make_Index({
box$(monomorph_LValue(crate, params, *e.val)),
box$(monomorph_LValue(crate, params, *e.idx))
});
),
(Downcast,
return ::MIR::LValue::make_Field({
box$(monomorph_LValue(crate, params, *e.val)),
e.variant_index
});
)
)
throw "";
}
::std::vector<::MIR::LValue> monomorph_LValue_list(const ::HIR::Crate& crate, const Trans_Params& params, const ::std::vector<::MIR::LValue>& tpl)
{
::std::vector<::MIR::LValue> rv;
rv.reserve( tpl.size() );
for(const auto& v : tpl)
rv.push_back( monomorph_LValue(crate, params, v) );
return rv;
}
}
::MIR::FunctionPointer Trans_Monomorphise(const ::HIR::Crate& crate, const Trans_Params& params, const ::MIR::FunctionPointer& tpl)
{
static Span sp;
TRACE_FUNCTION;
::MIR::Function output;
// 1. Monomorphise locals and temporaries
output.named_variables.reserve( tpl->named_variables.size() );
for(const auto& var : tpl->named_variables)
{
output.named_variables.push_back( params.monomorph(crate, var) );
}
output.temporaries.reserve( tpl->temporaries.size() );
for(const auto& ty : tpl->temporaries)
{
output.named_variables.push_back( params.monomorph(crate, ty) );
}
// 2. Monomorphise all paths
// 3. Convert virtual dispatch to vtable load
output.blocks.reserve( tpl->blocks.size() );
for(const auto& block : tpl->blocks)
{
::std::vector< ::MIR::Statement> statements;
statements.reserve( block.statements.size() );
for(const auto& stmt : block.statements)
{
assert( stmt.is_Drop() || stmt.is_Assign() );
if( stmt.is_Drop() )
{
const auto& e = stmt.as_Drop();
statements.push_back( ::MIR::Statement::make_Drop({
e.kind,
monomorph_LValue(crate, params, e.slot)
}) );
}
else
{
const auto& e = stmt.as_Assign();
::MIR::RValue rval;
TU_MATCHA( (e.src), (se),
(Use,
rval = ::MIR::RValue( monomorph_LValue(crate, params, se) );
),
(Constant,
TU_MATCHA( (se), (ce),
(Int,
rval = ::MIR::Constant::make_Int(ce);
),
(Uint,
rval = ::MIR::Constant::make_Uint(ce);
),
(Float,
rval = ::MIR::Constant::make_Float(ce);
),
(Bool,
rval = ::MIR::Constant::make_Bool(ce);
),
(Bytes,
rval = ::MIR::Constant(ce);
),
(StaticString,
rval = ::MIR::Constant(ce);
),
(Const,
rval = ::MIR::Constant::make_Const({
params.monomorph(crate, ce.p)
});
),
(ItemAddr,
auto p = params.monomorph(crate, ce);
// TODO: If this is a pointer to a function on a trait object, replace with the address loaded from the vtable.
// - Requires creating a new temporary for the vtable pointer.
rval = ::MIR::Constant( mv$(p) );
)
)
),
(SizedArray,
rval = ::MIR::RValue::make_SizedArray({
monomorph_LValue(crate, params, se.val),
se.count
});
),
(Borrow,
rval = ::MIR::RValue::make_Borrow({
se.region, se.type,
monomorph_LValue(crate, params, se.val)
});
),
(Cast,
rval = ::MIR::RValue::make_Cast({
monomorph_LValue(crate, params, se.val),
params.monomorph(crate, se.type)
});
),
(BinOp,
rval = ::MIR::RValue::make_BinOp({
monomorph_LValue(crate, params, se.val_l),
se.op,
monomorph_LValue(crate, params, se.val_r)
});
),
(UniOp,
rval = ::MIR::RValue::make_UniOp({
monomorph_LValue(crate, params, se.val),
se.op
});
),
(DstMeta,
auto lv = monomorph_LValue(crate, params, se.val);
// TODO: Get the type of this, and if it's an array - replace with the size
rval = ::MIR::RValue::make_DstMeta({ mv$(lv) });
),
(DstPtr,
rval = ::MIR::RValue::make_DstPtr({ monomorph_LValue(crate, params, se.val) });
),
(MakeDst,
rval = ::MIR::RValue::make_MakeDst({
monomorph_LValue(crate, params, se.ptr_val),
monomorph_LValue(crate, params, se.meta_val)
});
),
(Tuple,
rval = ::MIR::RValue::make_Tuple({
monomorph_LValue_list(crate, params, se.vals)
});
),
(Array,
rval = ::MIR::RValue::make_Array({
monomorph_LValue_list(crate, params, se.vals)
});
),
// Create a new instance of a union (and eventually enum)
(Variant,
rval = ::MIR::RValue::make_Variant({
params.monomorph(crate, se.path),
se.index,
monomorph_LValue(crate, params, se.val)
});
),
// Create a new instance of a struct (or enum)
(Struct,
rval = ::MIR::RValue::make_Struct({
params.monomorph(crate, se.path),
monomorph_LValue_list(crate, params, se.vals)
});
)
)
statements.push_back( ::MIR::Statement::make_Assign({
monomorph_LValue(crate, params, e.dst),
mv$(rval)
}) );
}
}
::MIR::Terminator terminator;
TU_MATCHA( (block.terminator), (e),
(Incomplete,
//BUG(sp, "Incomplete block");
terminator = e;
),
(Return,
terminator = e;
),
(Diverge,
terminator = e;
),
(Goto,
terminator = e;
),
(Panic,
terminator = e;
),
(If,
terminator = ::MIR::Terminator::make_If({
monomorph_LValue(crate, params, e.cond),
e.bb0, e.bb1
});
),
(Switch,
terminator = ::MIR::Terminator::make_Switch({
monomorph_LValue(crate, params, e.val),
e.targets
});
),
(Call,
terminator = ::MIR::Terminator::make_Call({
e.ret_block, e.panic_block,
monomorph_LValue(crate, params, e.ret_val),
monomorph_LValue(crate, params, e.fcn_val),
monomorph_LValue_list(crate, params, e.args)
});
)
)
output.blocks.push_back( ::MIR::BasicBlock { mv$(statements), mv$(terminator) } );
}
return ::MIR::FunctionPointer( box$(output).release() );
}
<commit_msg>Trans Monomorph - Note about vtable magic<commit_after>/*
* MRustC - Rust Compiler
* - By John Hodge (Mutabah/thePowersGang)
*
* trans/monomorphise.hpp
* - MIR monomorphisation
*/
#include "monomorphise.hpp"
#include <mir/mir.hpp>
#include <hir/hir.hpp>
namespace {
::MIR::LValue monomorph_LValue(const ::HIR::Crate& crate, const Trans_Params& params, const ::MIR::LValue& tpl)
{
TU_MATCHA( (tpl), (e),
(Variable, return e; ),
(Temporary, return e; ),
(Argument, return e; ),
(Return, return e; ),
(Static,
return params.monomorph(crate, e);
),
(Field,
return ::MIR::LValue::make_Field({
box$(monomorph_LValue(crate, params, *e.val)),
e.field_index
});
),
(Deref,
return ::MIR::LValue::make_Deref({
box$(monomorph_LValue(crate, params, *e.val))
});
),
(Index,
return ::MIR::LValue::make_Index({
box$(monomorph_LValue(crate, params, *e.val)),
box$(monomorph_LValue(crate, params, *e.idx))
});
),
(Downcast,
return ::MIR::LValue::make_Field({
box$(monomorph_LValue(crate, params, *e.val)),
e.variant_index
});
)
)
throw "";
}
::std::vector<::MIR::LValue> monomorph_LValue_list(const ::HIR::Crate& crate, const Trans_Params& params, const ::std::vector<::MIR::LValue>& tpl)
{
::std::vector<::MIR::LValue> rv;
rv.reserve( tpl.size() );
for(const auto& v : tpl)
rv.push_back( monomorph_LValue(crate, params, v) );
return rv;
}
}
::MIR::FunctionPointer Trans_Monomorphise(const ::HIR::Crate& crate, const Trans_Params& params, const ::MIR::FunctionPointer& tpl)
{
static Span sp;
TRACE_FUNCTION;
::MIR::Function output;
// 1. Monomorphise locals and temporaries
output.named_variables.reserve( tpl->named_variables.size() );
for(const auto& var : tpl->named_variables)
{
output.named_variables.push_back( params.monomorph(crate, var) );
}
output.temporaries.reserve( tpl->temporaries.size() );
for(const auto& ty : tpl->temporaries)
{
output.named_variables.push_back( params.monomorph(crate, ty) );
}
// 2. Monomorphise all paths
// 3. Convert virtual dispatch to vtable load
output.blocks.reserve( tpl->blocks.size() );
for(const auto& block : tpl->blocks)
{
::std::vector< ::MIR::Statement> statements;
statements.reserve( block.statements.size() );
for(const auto& stmt : block.statements)
{
assert( stmt.is_Drop() || stmt.is_Assign() );
if( stmt.is_Drop() )
{
const auto& e = stmt.as_Drop();
statements.push_back( ::MIR::Statement::make_Drop({
e.kind,
monomorph_LValue(crate, params, e.slot)
}) );
}
else
{
const auto& e = stmt.as_Assign();
::MIR::RValue rval;
TU_MATCHA( (e.src), (se),
(Use,
rval = ::MIR::RValue( monomorph_LValue(crate, params, se) );
),
(Constant,
TU_MATCHA( (se), (ce),
(Int,
rval = ::MIR::Constant::make_Int(ce);
),
(Uint,
rval = ::MIR::Constant::make_Uint(ce);
),
(Float,
rval = ::MIR::Constant::make_Float(ce);
),
(Bool,
rval = ::MIR::Constant::make_Bool(ce);
),
(Bytes,
rval = ::MIR::Constant(ce);
),
(StaticString,
rval = ::MIR::Constant(ce);
),
(Const,
rval = ::MIR::Constant::make_Const({
params.monomorph(crate, ce.p)
});
),
(ItemAddr,
auto p = params.monomorph(crate, ce);
// TODO: If this is a pointer to a function on a trait object, replace with the address loaded from the vtable.
// - Requires creating a new temporary for the vtable pointer.
// - Also requires knowing what the receiver is.
rval = ::MIR::Constant( mv$(p) );
)
)
),
(SizedArray,
rval = ::MIR::RValue::make_SizedArray({
monomorph_LValue(crate, params, se.val),
se.count
});
),
(Borrow,
rval = ::MIR::RValue::make_Borrow({
se.region, se.type,
monomorph_LValue(crate, params, se.val)
});
),
(Cast,
rval = ::MIR::RValue::make_Cast({
monomorph_LValue(crate, params, se.val),
params.monomorph(crate, se.type)
});
),
(BinOp,
rval = ::MIR::RValue::make_BinOp({
monomorph_LValue(crate, params, se.val_l),
se.op,
monomorph_LValue(crate, params, se.val_r)
});
),
(UniOp,
rval = ::MIR::RValue::make_UniOp({
monomorph_LValue(crate, params, se.val),
se.op
});
),
(DstMeta,
auto lv = monomorph_LValue(crate, params, se.val);
// TODO: Get the type of this, and if it's an array - replace with the size
rval = ::MIR::RValue::make_DstMeta({ mv$(lv) });
),
(DstPtr,
rval = ::MIR::RValue::make_DstPtr({ monomorph_LValue(crate, params, se.val) });
),
(MakeDst,
rval = ::MIR::RValue::make_MakeDst({
monomorph_LValue(crate, params, se.ptr_val),
monomorph_LValue(crate, params, se.meta_val)
});
),
(Tuple,
rval = ::MIR::RValue::make_Tuple({
monomorph_LValue_list(crate, params, se.vals)
});
),
(Array,
rval = ::MIR::RValue::make_Array({
monomorph_LValue_list(crate, params, se.vals)
});
),
// Create a new instance of a union (and eventually enum)
(Variant,
rval = ::MIR::RValue::make_Variant({
params.monomorph(crate, se.path),
se.index,
monomorph_LValue(crate, params, se.val)
});
),
// Create a new instance of a struct (or enum)
(Struct,
rval = ::MIR::RValue::make_Struct({
params.monomorph(crate, se.path),
monomorph_LValue_list(crate, params, se.vals)
});
)
)
statements.push_back( ::MIR::Statement::make_Assign({
monomorph_LValue(crate, params, e.dst),
mv$(rval)
}) );
}
}
::MIR::Terminator terminator;
TU_MATCHA( (block.terminator), (e),
(Incomplete,
//BUG(sp, "Incomplete block");
terminator = e;
),
(Return,
terminator = e;
),
(Diverge,
terminator = e;
),
(Goto,
terminator = e;
),
(Panic,
terminator = e;
),
(If,
terminator = ::MIR::Terminator::make_If({
monomorph_LValue(crate, params, e.cond),
e.bb0, e.bb1
});
),
(Switch,
terminator = ::MIR::Terminator::make_Switch({
monomorph_LValue(crate, params, e.val),
e.targets
});
),
(Call,
terminator = ::MIR::Terminator::make_Call({
e.ret_block, e.panic_block,
monomorph_LValue(crate, params, e.ret_val),
monomorph_LValue(crate, params, e.fcn_val),
monomorph_LValue_list(crate, params, e.args)
});
)
)
output.blocks.push_back( ::MIR::BasicBlock { mv$(statements), mv$(terminator) } );
}
return ::MIR::FunctionPointer( box$(output).release() );
}
<|endoftext|> |
<commit_before>#include "rosplan_interface_mapping/RPSimpleMapServer.h"
/* implementation of rosplan_interface_mapping::RPSimpleMapServer.h */
namespace KCL_rosplan {
/* constructor */
RPSimpleMapServer::RPSimpleMapServer(ros::NodeHandle &nh)
: message_store(nh) {
// config
std::string dataPath("common/");
nh.param("data_path", data_path, dataPath);
// knowledge interface
update_knowledge_client = nh.serviceClient<rosplan_knowledge_msgs::KnowledgeUpdateService>("/kcl_rosplan/update_knowledge_base");
// visualisation
waypoints_pub = nh.advertise<visualization_msgs::MarkerArray>("/kcl_rosplan/viz/waypoints", 10, true);
}
/*-----------*/
/* build PRM */
/*-----------*/
/**
* Generates waypoints and stores them in the knowledge base and scene database
*/
bool RPSimpleMapServer::generateRoadmap(rosplan_knowledge_msgs::CreatePRM::Request &req, rosplan_knowledge_msgs::CreatePRM::Response &res) {
ros::NodeHandle nh("~");
// clear previous roadmap from knowledge base
ROS_INFO("KCL: (RPSimpleMapServer) Cleaning old roadmap");
rosplan_knowledge_msgs::KnowledgeUpdateService updateSrv;
updateSrv.request.update_type = rosplan_knowledge_msgs::KnowledgeUpdateService::Request::REMOVE_KNOWLEDGE;
updateSrv.request.knowledge.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::INSTANCE;
updateSrv.request.knowledge.instance_type = "waypoint";
update_knowledge_client.call(updateSrv);
// clear previous roadmap from scene database
for (std::map<std::string,Waypoint*>::iterator wit=waypoints.begin(); wit!=waypoints.end(); ++wit) {
message_store.deleteID(db_name_map[wit->first]);
}
db_name_map.clear();
// clear from visualization
clearMarkerArrays(nh);
// generate waypoints
ROS_INFO("KCL: (RPSimpleMapServer) Generating roadmap");
for (std::map<std::string, Waypoint*>::const_iterator ci = waypoints.begin(); ci != waypoints.end(); ++ci)
delete (*ci).second;
waypoints.clear();
std::srand(std::time(0));
for(int i=0; i<req.nr_waypoints; i++) {
int x = (rand()%15);
int y = (rand()%15);
std::stringstream ss;
ss << "wp" << i;
Waypoint* wp = new Waypoint(ss.str(), x, y);
waypoints[wp->wpID] = wp;
}
// publish visualization
publishWaypointMarkerArray(nh);
// add roadmap to knowledge base and scene database
ROS_INFO("KCL: (RPSimpleMapServer) Adding knowledge");
for (std::map<std::string,Waypoint*>::iterator wit=waypoints.begin(); wit!=waypoints.end(); ++wit) {
// instance
rosplan_knowledge_msgs::KnowledgeUpdateService updateSrv;
updateSrv.request.update_type = rosplan_knowledge_msgs::KnowledgeUpdateService::Request::ADD_KNOWLEDGE;
updateSrv.request.knowledge.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::INSTANCE;
updateSrv.request.knowledge.instance_type = "waypoint";
updateSrv.request.knowledge.instance_name = wit->first;
update_knowledge_client.call(updateSrv);
res.waypoints.push_back(wit->first);
// predicates
for (std::vector<std::string>::iterator nit=wit->second->neighbours.begin(); nit!=wit->second->neighbours.end(); ++nit) {
rosplan_knowledge_msgs::KnowledgeUpdateService updatePredSrv;
updatePredSrv.request.update_type = rosplan_knowledge_msgs::KnowledgeUpdateService::Request::ADD_KNOWLEDGE;
updatePredSrv.request.knowledge.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_ATTRIBUTE;
updatePredSrv.request.knowledge.attribute_name = "connected";
diagnostic_msgs::KeyValue pairFrom;
pairFrom.key = "from";
pairFrom.value = wit->first;
updatePredSrv.request.knowledge.values.push_back(pairFrom);
diagnostic_msgs::KeyValue pairTo;
pairTo.key = "to";
pairTo.value = *nit;
updatePredSrv.request.knowledge.values.push_back(pairTo);
update_knowledge_client.call(updatePredSrv);
}
// functions
for (std::vector<std::string>::iterator nit=wit->second->neighbours.begin(); nit!=wit->second->neighbours.end(); ++nit) {
rosplan_knowledge_msgs::KnowledgeUpdateService updateFuncSrv;
updateFuncSrv.request.update_type = rosplan_knowledge_msgs::KnowledgeUpdateService::Request::ADD_KNOWLEDGE;
updateFuncSrv.request.knowledge.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_FUNCTION;
updateFuncSrv.request.knowledge.attribute_name = "distance";
diagnostic_msgs::KeyValue pairFrom;
pairFrom.key = "wp1";
pairFrom.value = wit->first;
updateFuncSrv.request.knowledge.values.push_back(pairFrom);
diagnostic_msgs::KeyValue pairTo;
pairTo.key = "wp2";
pairTo.value = *nit;
updateFuncSrv.request.knowledge.values.push_back(pairTo);
double dist = sqrt(
(wit->second->real_x - waypoints[*nit]->real_x)*(wit->second->real_x - waypoints[*nit]->real_x)
+ (wit->second->real_y - waypoints[*nit]->real_y)*(wit->second->real_y - waypoints[*nit]->real_y));
updateFuncSrv.request.knowledge.function_value = dist;
update_knowledge_client.call(updateFuncSrv);
}
//data
geometry_msgs::PoseStamped pose;
pose.header.frame_id = "world";
pose.pose.position.x = wit->second->real_x;
pose.pose.position.y = wit->second->real_y;
pose.pose.position.z = 0.0;
pose.pose.orientation.x = 0.0;;
pose.pose.orientation.y = 0.0;;
pose.pose.orientation.z = 1.0;
pose.pose.orientation.w = 1.0;
std::string id(message_store.insertNamed(wit->first, pose));
db_name_map[wit->first] = id;
}
// robot start position (TODO remove)
updateSrv.request.update_type = rosplan_knowledge_msgs::KnowledgeUpdateService::Request::ADD_KNOWLEDGE;
updateSrv.request.knowledge.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_ATTRIBUTE;
updateSrv.request.knowledge.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_ATTRIBUTE;
updateSrv.request.knowledge.attribute_name = "robot_at";
diagnostic_msgs::KeyValue pair1, pair2;
pair1.key = "v";
pair1.value = "kenny";
updateSrv.request.knowledge.values.push_back(pair1);
pair2.key = "wp";
pair2.value = "wp0";
updateSrv.request.knowledge.values.push_back(pair2);
update_knowledge_client.call(updateSrv);
ROS_INFO("KCL: (RPSimpleMapServer) Done");
return true;
}
/**
* parses a pose with yaw from strings: "[f, f, f]"
*/
void RPSimpleMapServer::parsePose(geometry_msgs::PoseStamped &pose, std::string line) {
int curr,next;
curr=line.find("[")+1;
next=line.find(",",curr);
pose.pose.position.x = (double)atof(line.substr(curr,next-curr).c_str());
curr=next+1; next=line.find(",",curr);
pose.pose.position.y = (double)atof(line.substr(curr,next-curr).c_str());
curr=next+1; next=line.find(",",curr);
pose.pose.orientation.x = 0.0;
pose.pose.orientation.y = 0.0;
pose.pose.orientation.w = (double)atof(line.substr(curr,next-curr).c_str());
pose.pose.orientation.z = sqrt(1 - pose.pose.orientation.w * pose.pose.orientation.w);
}
bool RPSimpleMapServer::setupRoadmap(std::string filename) {
ros::NodeHandle nh("~");
// clear previous roadmap from knowledge base
ROS_INFO("KCL: (RPSimpleMapServer) Loading roadmap from file");
// load configuration file
std::ifstream infile(filename.c_str());
std::string line;
int curr,next;
while(!infile.eof()) {
// read waypoint
std::getline(infile, line);
curr=line.find("[");
std::string name = line.substr(0,curr);
// instance
rosplan_knowledge_msgs::KnowledgeUpdateService updateSrv;
updateSrv.request.update_type = rosplan_knowledge_msgs::KnowledgeUpdateService::Request::ADD_KNOWLEDGE;
updateSrv.request.knowledge.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::INSTANCE;
updateSrv.request.knowledge.instance_type = "waypoint";
updateSrv.request.knowledge.instance_name = name;
update_knowledge_client.call(updateSrv);
// data
geometry_msgs::PoseStamped pose;
parsePose(pose, line);
std::string id(message_store.insertNamed(name, pose));
db_name_map[name] = id;
}
}
} // close namespace
/*-------------*/
/* Main method */
/*-------------*/
int main(int argc, char **argv) {
// setup ros
ros::init(argc, argv, "rosplan_simple_map_server");
ros::NodeHandle nh("~");
// params
std::string filename("waypoints.txt");
nh.param("waypoint_file", filename, filename);
// init
KCL_rosplan::RPSimpleMapServer sms(nh);
ros::ServiceServer createPRMService = nh.advertiseService("/kcl_rosplan/roadmap_server/create_prm", &KCL_rosplan::RPSimpleMapServer::generateRoadmap, &sms);
sms.setupRoadmap(filename);
ROS_INFO("KCL: (RPSimpleMapServer) Ready to receive.");
ros::spin();
return 0;
}
<commit_msg>Viz loaded waypoints<commit_after>#include "rosplan_interface_mapping/RPSimpleMapServer.h"
/* implementation of rosplan_interface_mapping::RPSimpleMapServer.h */
namespace KCL_rosplan {
/* constructor */
RPSimpleMapServer::RPSimpleMapServer(ros::NodeHandle &nh)
: message_store(nh) {
// config
std::string dataPath("common/");
nh.param("data_path", data_path, dataPath);
// knowledge interface
update_knowledge_client = nh.serviceClient<rosplan_knowledge_msgs::KnowledgeUpdateService>("/kcl_rosplan/update_knowledge_base");
// visualisation
waypoints_pub = nh.advertise<visualization_msgs::MarkerArray>("/kcl_rosplan/viz/waypoints", 10, true);
}
/*-----------*/
/* build PRM */
/*-----------*/
/**
* Generates waypoints and stores them in the knowledge base and scene database
*/
bool RPSimpleMapServer::generateRoadmap(rosplan_knowledge_msgs::CreatePRM::Request &req, rosplan_knowledge_msgs::CreatePRM::Response &res) {
ros::NodeHandle nh("~");
// clear previous roadmap from knowledge base
ROS_INFO("KCL: (RPSimpleMapServer) Cleaning old roadmap");
rosplan_knowledge_msgs::KnowledgeUpdateService updateSrv;
updateSrv.request.update_type = rosplan_knowledge_msgs::KnowledgeUpdateService::Request::REMOVE_KNOWLEDGE;
updateSrv.request.knowledge.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::INSTANCE;
updateSrv.request.knowledge.instance_type = "waypoint";
update_knowledge_client.call(updateSrv);
// clear previous roadmap from scene database
for (std::map<std::string,Waypoint*>::iterator wit=waypoints.begin(); wit!=waypoints.end(); ++wit) {
message_store.deleteID(db_name_map[wit->first]);
}
db_name_map.clear();
// clear from visualization
clearMarkerArrays(nh);
// generate waypoints
ROS_INFO("KCL: (RPSimpleMapServer) Generating roadmap");
for (std::map<std::string, Waypoint*>::const_iterator ci = waypoints.begin(); ci != waypoints.end(); ++ci)
delete (*ci).second;
waypoints.clear();
std::srand(std::time(0));
for(int i=0; i<req.nr_waypoints; i++) {
int x = (rand()%15);
int y = (rand()%15);
std::stringstream ss;
ss << "wp" << i;
Waypoint* wp = new Waypoint(ss.str(), x, y);
waypoints[wp->wpID] = wp;
}
// publish visualization
publishWaypointMarkerArray(nh);
// add roadmap to knowledge base and scene database
ROS_INFO("KCL: (RPSimpleMapServer) Adding knowledge");
for (std::map<std::string,Waypoint*>::iterator wit=waypoints.begin(); wit!=waypoints.end(); ++wit) {
// instance
rosplan_knowledge_msgs::KnowledgeUpdateService updateSrv;
updateSrv.request.update_type = rosplan_knowledge_msgs::KnowledgeUpdateService::Request::ADD_KNOWLEDGE;
updateSrv.request.knowledge.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::INSTANCE;
updateSrv.request.knowledge.instance_type = "waypoint";
updateSrv.request.knowledge.instance_name = wit->first;
update_knowledge_client.call(updateSrv);
res.waypoints.push_back(wit->first);
// predicates
for (std::vector<std::string>::iterator nit=wit->second->neighbours.begin(); nit!=wit->second->neighbours.end(); ++nit) {
rosplan_knowledge_msgs::KnowledgeUpdateService updatePredSrv;
updatePredSrv.request.update_type = rosplan_knowledge_msgs::KnowledgeUpdateService::Request::ADD_KNOWLEDGE;
updatePredSrv.request.knowledge.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_ATTRIBUTE;
updatePredSrv.request.knowledge.attribute_name = "connected";
diagnostic_msgs::KeyValue pairFrom;
pairFrom.key = "from";
pairFrom.value = wit->first;
updatePredSrv.request.knowledge.values.push_back(pairFrom);
diagnostic_msgs::KeyValue pairTo;
pairTo.key = "to";
pairTo.value = *nit;
updatePredSrv.request.knowledge.values.push_back(pairTo);
update_knowledge_client.call(updatePredSrv);
}
// functions
for (std::vector<std::string>::iterator nit=wit->second->neighbours.begin(); nit!=wit->second->neighbours.end(); ++nit) {
rosplan_knowledge_msgs::KnowledgeUpdateService updateFuncSrv;
updateFuncSrv.request.update_type = rosplan_knowledge_msgs::KnowledgeUpdateService::Request::ADD_KNOWLEDGE;
updateFuncSrv.request.knowledge.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_FUNCTION;
updateFuncSrv.request.knowledge.attribute_name = "distance";
diagnostic_msgs::KeyValue pairFrom;
pairFrom.key = "wp1";
pairFrom.value = wit->first;
updateFuncSrv.request.knowledge.values.push_back(pairFrom);
diagnostic_msgs::KeyValue pairTo;
pairTo.key = "wp2";
pairTo.value = *nit;
updateFuncSrv.request.knowledge.values.push_back(pairTo);
double dist = sqrt(
(wit->second->real_x - waypoints[*nit]->real_x)*(wit->second->real_x - waypoints[*nit]->real_x)
+ (wit->second->real_y - waypoints[*nit]->real_y)*(wit->second->real_y - waypoints[*nit]->real_y));
updateFuncSrv.request.knowledge.function_value = dist;
update_knowledge_client.call(updateFuncSrv);
}
//data
geometry_msgs::PoseStamped pose;
pose.header.frame_id = "world";
pose.pose.position.x = wit->second->real_x;
pose.pose.position.y = wit->second->real_y;
pose.pose.position.z = 0.0;
pose.pose.orientation.x = 0.0;;
pose.pose.orientation.y = 0.0;;
pose.pose.orientation.z = 1.0;
pose.pose.orientation.w = 1.0;
std::string id(message_store.insertNamed(wit->first, pose));
db_name_map[wit->first] = id;
}
// robot start position (TODO remove)
updateSrv.request.update_type = rosplan_knowledge_msgs::KnowledgeUpdateService::Request::ADD_KNOWLEDGE;
updateSrv.request.knowledge.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_ATTRIBUTE;
updateSrv.request.knowledge.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_ATTRIBUTE;
updateSrv.request.knowledge.attribute_name = "robot_at";
diagnostic_msgs::KeyValue pair1, pair2;
pair1.key = "v";
pair1.value = "kenny";
updateSrv.request.knowledge.values.push_back(pair1);
pair2.key = "wp";
pair2.value = "wp0";
updateSrv.request.knowledge.values.push_back(pair2);
update_knowledge_client.call(updateSrv);
ROS_INFO("KCL: (RPSimpleMapServer) Done");
return true;
}
/**
* parses a pose with yaw from strings: "[f, f, f]"
*/
void RPSimpleMapServer::parsePose(geometry_msgs::PoseStamped &pose, std::string line) {
int curr,next;
curr=line.find("[")+1;
next=line.find(",",curr);
pose.pose.position.x = (double)atof(line.substr(curr,next-curr).c_str());
curr=next+1; next=line.find(",",curr);
pose.pose.position.y = (double)atof(line.substr(curr,next-curr).c_str());
curr=next+1; next=line.find(",",curr);
pose.pose.orientation.x = 0.0;
pose.pose.orientation.y = 0.0;
pose.pose.orientation.w = (double)atof(line.substr(curr,next-curr).c_str());
pose.pose.orientation.z = sqrt(1 - pose.pose.orientation.w * pose.pose.orientation.w);
}
bool RPSimpleMapServer::setupRoadmap(std::string filename) {
ros::NodeHandle nh("~");
// clear previous roadmap from knowledge base
ROS_INFO("KCL: (RPSimpleMapServer) Loading roadmap from file");
// load configuration file
std::ifstream infile(filename.c_str());
std::string line;
int curr,next;
while(!infile.eof()) {
// read waypoint
std::getline(infile, line);
curr=line.find("[");
std::string name = line.substr(0,curr);
// instance
rosplan_knowledge_msgs::KnowledgeUpdateService updateSrv;
updateSrv.request.update_type = rosplan_knowledge_msgs::KnowledgeUpdateService::Request::ADD_KNOWLEDGE;
updateSrv.request.knowledge.knowledge_type = rosplan_knowledge_msgs::KnowledgeItem::INSTANCE;
updateSrv.request.knowledge.instance_type = "waypoint";
updateSrv.request.knowledge.instance_name = name;
update_knowledge_client.call(updateSrv);
// data
geometry_msgs::PoseStamped pose;
parsePose(pose, line);
std::string id(message_store.insertNamed(name, pose));
db_name_map[name] = id;
// save here for viz
Waypoint* wp = new Waypoint(name, pose.pose.position.x, pose.pose.position.y);
waypoints[wp->wpID] = wp;
}
// publish visualization
publishWaypointMarkerArray(nh);
}
} // close namespace
/*-------------*/
/* Main method */
/*-------------*/
int main(int argc, char **argv) {
// setup ros
ros::init(argc, argv, "rosplan_simple_map_server");
ros::NodeHandle nh("~");
// params
std::string filename("waypoints.txt");
nh.param("waypoint_file", filename, filename);
// init
KCL_rosplan::RPSimpleMapServer sms(nh);
ros::ServiceServer createPRMService = nh.advertiseService("/kcl_rosplan/roadmap_server/create_prm", &KCL_rosplan::RPSimpleMapServer::generateRoadmap, &sms);
sms.setupRoadmap(filename);
ROS_INFO("KCL: (RPSimpleMapServer) Ready to receive.");
ros::spin();
return 0;
}
<|endoftext|> |
<commit_before>
/*!
\file
\author Igor Mironchik (igor.mironchik at gmail dot com).
Copyright (c) 2013-2017 Igor Mironchik
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 ARGS__MULTI_ARG_HPP__INCLUDED
#define ARGS__MULTI_ARG_HPP__INCLUDED
// Args include.
#include "arg.hpp"
#include "context.hpp"
#include "exceptions.hpp"
#include "value_utils.hpp"
#include "utils.hpp"
#include "types.hpp"
// C++ include.
#include <utility>
namespace Args {
//
// MultiArg
//
/*!
MultiArg is a class that presents argument in the command
line taht can be presented more than once or can have more
than one value.
*/
class MultiArg
: public Arg
{
public:
//! Construct argument with flag and name.
template< typename T >
MultiArg(
//! Flag for this argument.
Char flag,
//! Name for this argument.
T && name,
//! Is this argument with value?
bool isWithValue = false,
//! Is this argument required?
bool isRequired = false );
//! Construct argument only with flag, without name.
explicit MultiArg(
//! Flag for this argument.
Char flag,
//! Is this argument with value?
bool isWithValue = false,
//! Is this argument required?
bool isRequired = false );
//! Construct argument only with name, without flag.
template< typename T >
explicit MultiArg(
//! Name for this argument.
T && name,
//! Is this argument with value?
bool isWithValue = false,
//! Is this argument required?
bool isRequired = false );
virtual ~MultiArg();
//! \return First value of this argument.
const String & value() const override;
//! Set value. \note Value will be pushed back to the list of values.
void setValue( const String & v ) override;
//! \return All values for this argument.
virtual const StringList & values() const;
/*!
\return Count of times that this argument was presented
in the command line if argument without value or count of values
if argument is with values.
*/
size_t count() const;
//! \return Default value.
const String & defaultValue() const override
{
if( !m_defaultValues.empty() )
return m_defaultValues.front();
else
return Arg::defaultValue();
}
//! Set default value. \note Value will be pushed back to the list
//! of default values.
void setDefaultValue( const String & v ) override
{
m_defaultValues.push_back( v );
}
//! \return Default values.
const StringList & defaultValues() const
{
return m_defaultValues;
}
//! Set default values.
void setDefaultValues( const StringList & v )
{
m_defaultValues = v;
}
protected:
/*!
Process argument's staff, for example take values from
context. This method invokes exactly at that moment when
parser has found this argument.
*/
void process(
//! Context of the command line.
Context & context ) override;
private:
DISABLE_COPY( MultiArg )
//! Dummy empty string.
static const String m_emptyString;
//! Values of this argument.
StringList m_values;
//! Counter.
size_t m_count;
//! Default values.
StringList m_defaultValues;
}; // class MultiArg
const String MultiArg::m_emptyString;
//
// MultiArg
//
template< typename T >
MultiArg::MultiArg( Char flag, T && name,
bool isWithValue, bool isRequired )
: Arg( flag, std::forward< T > ( name ), isWithValue, isRequired )
, m_count( 0 )
{
}
inline
MultiArg::MultiArg( Char flag,
bool isWithValue, bool isRequired )
: Arg( flag, isWithValue, isRequired )
, m_count( 0 )
{
}
template< typename T >
MultiArg::MultiArg( T && name,
bool isWithValue, bool isRequired )
: Arg( std::forward< T > ( name ), isWithValue, isRequired )
, m_count( 0 )
{
}
inline
MultiArg::~MultiArg()
{
}
inline const String &
MultiArg::value() const
{
if( !m_values.empty() )
return m_values.front();
else if( !m_defaultValues.empty() )
return m_defaultValues.front();
else
return m_emptyString;
}
inline void
MultiArg::setValue( const String & v )
{
m_values.push_back( v );
}
inline const StringList &
MultiArg::values() const
{
if( !m_values.empty() )
return m_values;
else
return m_defaultValues;
}
inline size_t
MultiArg::count() const
{
if( !isWithValue() )
return m_count;
else if( !m_values.empty() )
return m_values.size();
else
return m_defaultValues.size();
}
inline void
MultiArg::process( Context & context )
{
if( isWithValue() )
{
setDefined( eatValues( context, m_values,
String( SL( "Argument \"" ) ) +
name() + SL( "\" requires value that wasn't presented." ),
cmdLine() ) );
}
else
{
setDefined( true );
++m_count;
}
}
} /* namespace Args */
#endif // ARGS__MULTI_ARG_HPP__INCLUDED
<commit_msg>Minor fix.<commit_after>
/*!
\file
\author Igor Mironchik (igor.mironchik at gmail dot com).
Copyright (c) 2013-2017 Igor Mironchik
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 ARGS__MULTI_ARG_HPP__INCLUDED
#define ARGS__MULTI_ARG_HPP__INCLUDED
// Args include.
#include "arg.hpp"
#include "context.hpp"
#include "exceptions.hpp"
#include "value_utils.hpp"
#include "utils.hpp"
#include "types.hpp"
// C++ include.
#include <utility>
namespace Args {
//
// MultiArg
//
/*!
MultiArg is a class that presents argument in the command
line taht can be presented more than once or can have more
than one value.
*/
class MultiArg
: public Arg
{
public:
//! Construct argument with flag and name.
template< typename T >
MultiArg(
//! Flag for this argument.
Char flag,
//! Name for this argument.
T && name,
//! Is this argument with value?
bool isWithValue = false,
//! Is this argument required?
bool isRequired = false );
//! Construct argument only with flag, without name.
explicit MultiArg(
//! Flag for this argument.
Char flag,
//! Is this argument with value?
bool isWithValue = false,
//! Is this argument required?
bool isRequired = false );
//! Construct argument only with name, without flag.
template< typename T >
explicit MultiArg(
//! Name for this argument.
T && name,
//! Is this argument with value?
bool isWithValue = false,
//! Is this argument required?
bool isRequired = false );
virtual ~MultiArg();
//! \return First value of this argument.
const String & value() const override;
//! Set value. \note Value will be pushed back to the list of values.
void setValue( const String & v ) override;
//! \return All values for this argument.
virtual const StringList & values() const;
/*!
\return Count of times that this argument was presented
in the command line if argument without value or count of values
if argument is with values.
*/
size_t count() const;
//! \return Default value.
const String & defaultValue() const override
{
if( !m_defaultValues.empty() )
return m_defaultValues.front();
else
return m_emptyString;
}
//! Set default value. \note Value will be pushed back to the list
//! of default values.
void setDefaultValue( const String & v ) override
{
m_defaultValues.push_back( v );
}
//! \return Default values.
const StringList & defaultValues() const
{
return m_defaultValues;
}
//! Set default values.
void setDefaultValues( const StringList & v )
{
m_defaultValues = v;
}
protected:
/*!
Process argument's staff, for example take values from
context. This method invokes exactly at that moment when
parser has found this argument.
*/
void process(
//! Context of the command line.
Context & context ) override;
private:
DISABLE_COPY( MultiArg )
//! Dummy empty string.
static const String m_emptyString;
//! Values of this argument.
StringList m_values;
//! Counter.
size_t m_count;
//! Default values.
StringList m_defaultValues;
}; // class MultiArg
const String MultiArg::m_emptyString;
//
// MultiArg
//
template< typename T >
MultiArg::MultiArg( Char flag, T && name,
bool isWithValue, bool isRequired )
: Arg( flag, std::forward< T > ( name ), isWithValue, isRequired )
, m_count( 0 )
{
}
inline
MultiArg::MultiArg( Char flag,
bool isWithValue, bool isRequired )
: Arg( flag, isWithValue, isRequired )
, m_count( 0 )
{
}
template< typename T >
MultiArg::MultiArg( T && name,
bool isWithValue, bool isRequired )
: Arg( std::forward< T > ( name ), isWithValue, isRequired )
, m_count( 0 )
{
}
inline
MultiArg::~MultiArg()
{
}
inline const String &
MultiArg::value() const
{
if( !m_values.empty() )
return m_values.front();
else if( !m_defaultValues.empty() )
return m_defaultValues.front();
else
return m_emptyString;
}
inline void
MultiArg::setValue( const String & v )
{
m_values.push_back( v );
}
inline const StringList &
MultiArg::values() const
{
if( !m_values.empty() )
return m_values;
else
return m_defaultValues;
}
inline size_t
MultiArg::count() const
{
if( !isWithValue() )
return m_count;
else if( !m_values.empty() )
return m_values.size();
else
return m_defaultValues.size();
}
inline void
MultiArg::process( Context & context )
{
if( isWithValue() )
{
setDefined( eatValues( context, m_values,
String( SL( "Argument \"" ) ) +
name() + SL( "\" requires value that wasn't presented." ),
cmdLine() ) );
}
else
{
setDefined( true );
++m_count;
}
}
} /* namespace Args */
#endif // ARGS__MULTI_ARG_HPP__INCLUDED
<|endoftext|> |
<commit_before>//******************************************************************
//
// Copyright 2016 Samsung Electronics 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 "SceneCollectionResource.h"
#include <atomic>
#include "OCApi.h"
#include "RCSRequest.h"
#include "RCSSeparateResponse.h"
namespace OIC
{
namespace Service
{
namespace
{
std::atomic_int g_numOfSceneCollection(0);
}
SceneCollectionResource::SceneCollectionResource()
: m_uri(PREFIX_SCENE_COLLECTION_URI + "/" + std::to_string(g_numOfSceneCollection++)),
m_address(), m_sceneCollectionResourceObject(), m_requestHandler()
{
m_sceneCollectionResourceObject = createResourceObject();
}
SceneCollectionResource::Ptr SceneCollectionResource::create()
{
SceneCollectionResource::Ptr sceneCollectionResource(new SceneCollectionResource());
sceneCollectionResource->setDefaultAttributes();
sceneCollectionResource->initSetRequestHandler();
sceneCollectionResource->m_address = SceneUtils::getNetAddress();
return sceneCollectionResource;
}
SceneCollectionResource::Ptr SceneCollectionResource::create(
const RCSResourceAttributes & inputAttr)
{
auto sceneCollectionResource = SceneCollectionResource::create();
if (inputAttr.contains(SCENE_KEY_NAME))
{
sceneCollectionResource->setName(inputAttr.at(SCENE_KEY_NAME).get<std::string>());
}
if (inputAttr.contains(SCENE_KEY_SCENEVALUES))
{
auto sceneValues = inputAttr.at(SCENE_KEY_SCENEVALUES).
get<std::vector<std::string>>();
sceneCollectionResource->getRCSResourceObject()->setAttribute(
SCENE_KEY_SCENEVALUES, sceneValues);
}
if (inputAttr.contains(SCENE_KEY_LAST_SCENE))
{
auto sceneValues = inputAttr.at(SCENE_KEY_LAST_SCENE).get<std::string>();
sceneCollectionResource->getRCSResourceObject()->setAttribute(
SCENE_KEY_LAST_SCENE, sceneValues);
}
return sceneCollectionResource;
}
RCSResourceObject::Ptr SceneCollectionResource::createResourceObject()
{
return RCSResourceObject::Builder(
m_uri, SCENE_COLLECTION_RT, BASELINE_IF).
addInterface(OC::BATCH_INTERFACE).
addInterface(LINK_BATCH).
setDiscoverable(true).setObservable(false).build();
}
void SceneCollectionResource::setDefaultAttributes()
{
m_sceneCollectionResourceObject->setAttribute(SCENE_KEY_LAST_SCENE, std::string());
m_sceneCollectionResourceObject->setAttribute(SCENE_KEY_NAME, std::string());
m_sceneCollectionResourceObject->setAttribute(
SCENE_KEY_ID, SceneUtils::OICGenerateUUIDStr());
m_sceneCollectionResourceObject->setAttribute(SCENE_KEY_RTS, SCENE_MEMBER_RT);
m_sceneCollectionResourceObject->setAttribute(
SCENE_KEY_SCENEVALUES, std::vector<std::string>());
m_sceneCollectionResourceObject->setAttribute(SCENE_KEY_URI, m_uri);
}
void SceneCollectionResource::initSetRequestHandler()
{
m_requestHandler.m_owner
= std::weak_ptr<SceneCollectionResource>(shared_from_this());
m_sceneCollectionResourceObject->setSetRequestHandler(std::bind(
&SceneCollectionResource::SceneCollectionRequestHandler::onSetRequest,
m_requestHandler, std::placeholders::_1, std::placeholders::_2));
}
void SceneCollectionResource::addScene(const std::string & newScene)
{
addScene(std::string(newScene));
}
void SceneCollectionResource::addScene(std::string && newScene)
{
auto sceneValues = m_sceneCollectionResourceObject->getAttributeValue(
SCENE_KEY_SCENEVALUES).get< std::vector< std::string > >();
auto foundScene
= std::find(sceneValues.begin(), sceneValues.end(), newScene);
if (foundScene == sceneValues.end())
{
sceneValues.push_back(std::move(newScene));
m_sceneCollectionResourceObject->setAttribute(SCENE_KEY_SCENEVALUES, sceneValues);
}
else
{
throw RCSInvalidParameterException("Scene name is duplicate!");
}
}
void SceneCollectionResource::addSceneMember(
SceneMemberResource::Ptr newMember)
{
std::lock_guard<std::mutex> memberlock(m_sceneMemberLock);
auto foundmember = std::find_if(m_sceneMembers.begin(), m_sceneMembers.end(),
[& newMember](const SceneMemberResource::Ptr & ptr) -> bool
{
return ptr->getTargetUri() == newMember->getTargetUri();
});
if (foundmember != m_sceneMembers.end())
{
throw RCSBadRequestException("It is already registered member.");
}
m_sceneMembers.push_back(newMember);
m_sceneCollectionResourceObject->bindResource(newMember->getRCSResourceObject());
}
void SceneCollectionResource::execute(std::string && sceneName)
{
execute(std::move(sceneName), nullptr);
}
void SceneCollectionResource::execute(const std::string & sceneName)
{
execute(std::string(sceneName));
}
void SceneCollectionResource::execute(
const std::string & sceneName, SceneExecuteCallback executeCB)
{
execute(std::string(sceneName), std::move(executeCB));
}
void SceneCollectionResource::execute(
std::string && sceneName, SceneExecuteCallback executeCB)
{
auto sceneValues = m_sceneCollectionResourceObject->getAttributeValue(
SCENE_KEY_SCENEVALUES).get< std::vector< std::string > >();
auto foundSceneValue
= std::find(sceneValues.begin(), sceneValues.end(), sceneName);
if (foundSceneValue == sceneValues.end() && executeCB && !m_sceneMembers.size())
{
std::thread(std::move(executeCB), SCENE_CLIENT_BADREQUEST).detach();
return;
}
m_sceneCollectionResourceObject->setAttribute(
SCENE_KEY_LAST_SCENE, std::move(sceneName));
{
std::lock_guard<std::mutex> memberlock(m_sceneMemberLock);
auto executeHandler
= SceneExecuteResponseHandler::createExecuteHandler(
shared_from_this(), std::move(executeCB));
for (auto & it : m_sceneMembers)
{
it->execute(sceneName, std::bind(
&SceneExecuteResponseHandler::onResponse, executeHandler,
std::placeholders::_1, std::placeholders::_2));
}
}
}
std::string SceneCollectionResource::getId() const
{
return m_sceneCollectionResourceObject->getAttributeValue(
SCENE_KEY_ID).get<std::string>();
}
std::string SceneCollectionResource::getUri() const
{
return m_uri;
}
std::string SceneCollectionResource::getAddress() const
{
return m_address;
}
std::vector<std::string> SceneCollectionResource::getSceneValues() const
{
return m_sceneCollectionResourceObject->getAttributeValue(
SCENE_KEY_SCENEVALUES).get<std::vector<std::string>>();
}
std::vector<SceneMemberResource::Ptr> SceneCollectionResource::getSceneMembers() const
{
std::lock_guard<std::mutex> memberlock(m_sceneMemberLock);
return m_sceneMembers;
}
std::vector<SceneMemberResource::Ptr> SceneCollectionResource::findSceneMembers(
const std::string & sceneName) const
{
std::lock_guard<std::mutex> memberlock(m_sceneMemberLock);
std::vector<SceneMemberResource::Ptr> retMembers;
std::for_each(m_sceneMembers.begin(), m_sceneMembers.end(),
[& retMembers, & sceneName](SceneMemberResource::Ptr pMember)
{
if(pMember->hasSceneValue(sceneName))
{
retMembers.push_back(pMember);
}
});
return retMembers;
}
RCSResourceObject::Ptr SceneCollectionResource::getRCSResourceObject() const
{
return m_sceneCollectionResourceObject;
}
void SceneCollectionResource::setName(std::string && sceneCollectionName)
{
m_sceneCollectionResourceObject->setAttribute(
SCENE_KEY_NAME, std::move(sceneCollectionName));
}
void SceneCollectionResource::setName(const std::string & sceneCollectionName)
{
setName(std::string(sceneCollectionName));
}
std::string SceneCollectionResource::getName() const
{
return m_sceneCollectionResourceObject->getAttributeValue(
SCENE_KEY_NAME).get<std::string>();
}
RCSSetResponse SceneCollectionResource::SceneCollectionRequestHandler::
onSetRequest(const RCSRequest & request, RCSResourceAttributes & attributes)
{
if (request.getInterface() == LINK_BATCH)
{
return createSceneMemberRequest(request, attributes);
}
if (attributes.contains(SCENE_KEY_SCENEVALUES))
{
return addSceneRequest(request, attributes);
}
if (attributes.contains(SCENE_KEY_LAST_SCENE))
{
return executeSceneRequest(request, attributes);
}
if (attributes.contains(SCENE_KEY_NAME))
{
return setSceneCollectionName(request, attributes);
}
return RCSSetResponse::create(attributes, (int)SCENE_CLIENT_BADREQUEST).
setAcceptanceMethod(RCSSetResponse::AcceptanceMethod::IGNORE);
}
RCSSetResponse SceneCollectionResource::SceneCollectionRequestHandler::
addSceneRequest(const RCSRequest & /*request*/, RCSResourceAttributes & attributes)
{
SceneCollectionResource::Ptr ptr = m_owner.lock();
if (ptr == nullptr)
{
return RCSSetResponse::create(attributes, SCENE_CLIENT_BADREQUEST).
setAcceptanceMethod(RCSSetResponse::AcceptanceMethod::IGNORE);
}
auto values = attributes.at(SCENE_KEY_SCENEVALUES).get<std::vector<std::string>>();
auto sizeofValues = values.size();
unsigned int sameSize = 0;
std::for_each(values.begin(), values.end(),
[& ptr, & sameSize](const std::string & value)
{
try
{
ptr->addScene(value);
} catch (...)
{
sameSize++;
}
});
int eCode = SCENE_RESPONSE_SUCCESS;
if (sameSize == sizeofValues)
{
eCode = SCENE_CLIENT_BADREQUEST;
}
return RCSSetResponse::create(attributes, eCode).
setAcceptanceMethod(RCSSetResponse::AcceptanceMethod::IGNORE);
}
RCSSetResponse SceneCollectionResource::SceneCollectionRequestHandler::
executeSceneRequest(const RCSRequest & request, RCSResourceAttributes & attributes)
{
SceneCollectionResource::Ptr ptr = m_owner.lock();
if (ptr == nullptr)
{
return RCSSetResponse::create(attributes, SCENE_CLIENT_BADREQUEST).
setAcceptanceMethod(RCSSetResponse::AcceptanceMethod::IGNORE);
}
auto requestKey = attributes.at(SCENE_KEY_LAST_SCENE).get<std::string>();
RCSRequest req(request.getResourceObject().lock(), request.getOCRequest());
ptr->execute(std::string(requestKey),
[req](int /*eCode*/)
{
// TODO need to set error code.
// and need to set specific attr' but this attr not to be apply to RCSResourceObject.
RCSSeparateResponse(req).set();
});
return RCSSetResponse::separate();
}
RCSSetResponse SceneCollectionResource::SceneCollectionRequestHandler::
createSceneMemberRequest(const RCSRequest & /*request*/, RCSResourceAttributes & attributes)
{
int eCode = SCENE_CLIENT_BADREQUEST;
SceneCollectionResource::Ptr ptr = m_owner.lock();
if (!ptr)
{
return RCSSetResponse::create(attributes, eCode).
setAcceptanceMethod(RCSSetResponse::AcceptanceMethod::IGNORE);
}
RCSResourceAttributes responseAtt(attributes);
if (attributes.contains(SCENE_KEY_PAYLOAD_LINK))
{
auto linkAtt = attributes.at(SCENE_KEY_PAYLOAD_LINK).get<RCSResourceAttributes>();
if (linkAtt.contains(SCENE_KEY_HREF) &&
linkAtt.contains(SCENE_KEY_RT) && linkAtt.contains(SCENE_KEY_IF))
{
auto memberObj = SceneMemberResource::createSceneMemberResource(linkAtt);
try
{
ptr->addSceneMember(memberObj);
}
catch (...)
{
return RCSSetResponse::create(responseAtt, eCode).
setAcceptanceMethod(RCSSetResponse::AcceptanceMethod::IGNORE);
}
eCode = SCENE_RESPONSE_SUCCESS;
if (attributes.contains(SCENE_KEY_SCENEMAPPINGS))
{
addMemberInfoFromRemote(memberObj, attributes.at(
SCENE_KEY_SCENEMAPPINGS).get<std::vector<RCSResourceAttributes>>());
}
responseAtt[SCENE_KEY_ID] = RCSResourceAttributes::Value(memberObj->getId());
responseAtt[SCENE_KEY_CREATEDLINK]
= RCSResourceAttributes::Value(memberObj->getFullUri());
}
}
return RCSSetResponse::create(responseAtt, eCode).
setAcceptanceMethod(RCSSetResponse::AcceptanceMethod::IGNORE);
}
RCSSetResponse
SceneCollectionResource::SceneCollectionRequestHandler::setSceneCollectionName(
const RCSRequest & /*request*/, RCSResourceAttributes & attr)
{
int eCode = SCENE_CLIENT_BADREQUEST;
SceneCollectionResource::Ptr ptr = m_owner.lock();
if (ptr != nullptr)
{
eCode = SCENE_RESPONSE_SUCCESS;
ptr->setName(attr.at(SCENE_KEY_NAME).get<std::string>());
}
return RCSSetResponse::create(attr, eCode).
setAcceptanceMethod(RCSSetResponse::AcceptanceMethod::IGNORE);
}
void SceneCollectionResource::SceneCollectionRequestHandler::addMemberInfoFromRemote(
SceneMemberResource::Ptr memberObj, std::vector<RCSResourceAttributes> mInfo)
{
std::for_each(mInfo.begin(), mInfo.end(),
[& memberObj](const RCSResourceAttributes & att)
{
memberObj->addMappingInfo(SceneMemberResource::MappingInfo::create(att));
});
}
void SceneCollectionResource::SceneExecuteResponseHandler::
onResponse(const RCSResourceAttributes & /*attributes*/, int errorCode)
{
m_responseMembers++;
if (errorCode != SCENE_RESPONSE_SUCCESS && m_errorCode != errorCode)
{
m_errorCode = errorCode;
}
if (m_responseMembers == m_numOfMembers)
{
m_cb(m_errorCode);
}
}
SceneCollectionResource::SceneExecuteResponseHandler::Ptr
SceneCollectionResource::SceneExecuteResponseHandler::createExecuteHandler(
const SceneCollectionResource::Ptr ptr, SceneExecuteCallback executeCB)
{
auto executeHandler = std::make_shared<SceneExecuteResponseHandler>();
executeHandler->m_numOfMembers = ptr->m_sceneMembers.size();
executeHandler->m_responseMembers = 0;
executeHandler->m_cb =
[executeCB](int eCode)
{
std::thread(std::move(executeCB), eCode).detach();
};
executeHandler->m_owner
= std::weak_ptr<SceneCollectionResource>(ptr);
executeHandler->m_errorCode = SCENE_RESPONSE_SUCCESS;
return executeHandler;
}
}
}
<commit_msg>(IOT-1014) modified sceneCollectionResource<commit_after>//******************************************************************
//
// Copyright 2016 Samsung Electronics 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 "SceneCollectionResource.h"
#include <atomic>
#include "OCApi.h"
#include "RCSRequest.h"
#include "RCSSeparateResponse.h"
namespace OIC
{
namespace Service
{
namespace
{
std::atomic_int g_numOfSceneCollection(0);
}
SceneCollectionResource::SceneCollectionResource()
: m_uri(PREFIX_SCENE_COLLECTION_URI + "/" + std::to_string(g_numOfSceneCollection++)),
m_address(), m_sceneCollectionResourceObject(), m_requestHandler()
{
m_sceneCollectionResourceObject = createResourceObject();
}
SceneCollectionResource::Ptr SceneCollectionResource::create()
{
SceneCollectionResource::Ptr sceneCollectionResource(new SceneCollectionResource());
sceneCollectionResource->setDefaultAttributes();
sceneCollectionResource->initSetRequestHandler();
sceneCollectionResource->m_address = SceneUtils::getNetAddress();
return sceneCollectionResource;
}
SceneCollectionResource::Ptr SceneCollectionResource::create(
const RCSResourceAttributes & inputAttr)
{
auto sceneCollectionResource = SceneCollectionResource::create();
if (inputAttr.contains(SCENE_KEY_NAME))
{
sceneCollectionResource->setName(inputAttr.at(SCENE_KEY_NAME).get<std::string>());
}
if (inputAttr.contains(SCENE_KEY_SCENEVALUES))
{
auto sceneValues = inputAttr.at(SCENE_KEY_SCENEVALUES).
get<std::vector<std::string>>();
sceneCollectionResource->getRCSResourceObject()->setAttribute(
SCENE_KEY_SCENEVALUES, sceneValues);
}
if (inputAttr.contains(SCENE_KEY_LAST_SCENE))
{
auto sceneValues = inputAttr.at(SCENE_KEY_LAST_SCENE).get<std::string>();
sceneCollectionResource->getRCSResourceObject()->setAttribute(
SCENE_KEY_LAST_SCENE, sceneValues);
}
return sceneCollectionResource;
}
RCSResourceObject::Ptr SceneCollectionResource::createResourceObject()
{
return RCSResourceObject::Builder(
m_uri, SCENE_COLLECTION_RT, BASELINE_IF).
addInterface(OC::BATCH_INTERFACE).
addInterface(LINK_BATCH).
setDiscoverable(true).setObservable(false).build();
}
void SceneCollectionResource::setDefaultAttributes()
{
m_sceneCollectionResourceObject->setAttribute(SCENE_KEY_LAST_SCENE, std::string());
m_sceneCollectionResourceObject->setAttribute(SCENE_KEY_NAME, std::string());
m_sceneCollectionResourceObject->setAttribute(
SCENE_KEY_ID, SceneUtils::OICGenerateUUIDStr());
m_sceneCollectionResourceObject->setAttribute(SCENE_KEY_RTS, SCENE_MEMBER_RT);
m_sceneCollectionResourceObject->setAttribute(
SCENE_KEY_SCENEVALUES, std::vector<std::string>());
m_sceneCollectionResourceObject->setAttribute(SCENE_KEY_URI, m_uri);
}
void SceneCollectionResource::initSetRequestHandler()
{
m_requestHandler.m_owner
= std::weak_ptr<SceneCollectionResource>(shared_from_this());
m_sceneCollectionResourceObject->setSetRequestHandler(std::bind(
&SceneCollectionResource::SceneCollectionRequestHandler::onSetRequest,
m_requestHandler, std::placeholders::_1, std::placeholders::_2));
}
void SceneCollectionResource::addScene(const std::string & newScene)
{
addScene(std::string(newScene));
}
void SceneCollectionResource::addScene(std::string && newScene)
{
auto sceneValues = m_sceneCollectionResourceObject->getAttributeValue(
SCENE_KEY_SCENEVALUES).get< std::vector< std::string > >();
auto foundScene
= std::find(sceneValues.begin(), sceneValues.end(), newScene);
if (foundScene == sceneValues.end())
{
sceneValues.push_back(std::move(newScene));
m_sceneCollectionResourceObject->setAttribute(SCENE_KEY_SCENEVALUES, sceneValues);
}
else
{
throw RCSInvalidParameterException("Scene name is duplicate!");
}
}
void SceneCollectionResource::addSceneMember(
SceneMemberResource::Ptr newMember)
{
std::lock_guard<std::mutex> memberlock(m_sceneMemberLock);
auto foundmember = std::find_if(m_sceneMembers.begin(), m_sceneMembers.end(),
[& newMember](const SceneMemberResource::Ptr & ptr) -> bool
{
return ptr->getTargetUri() == newMember->getTargetUri();
});
if (foundmember != m_sceneMembers.end())
{
throw RCSBadRequestException("It is already registered member.");
}
m_sceneMembers.push_back(newMember);
m_sceneCollectionResourceObject->bindResource(newMember->getRCSResourceObject());
}
void SceneCollectionResource::execute(std::string && sceneName)
{
execute(std::move(sceneName), nullptr);
}
void SceneCollectionResource::execute(const std::string & sceneName)
{
execute(std::string(sceneName));
}
void SceneCollectionResource::execute(
const std::string & sceneName, SceneExecuteCallback executeCB)
{
execute(std::string(sceneName), std::move(executeCB));
}
void SceneCollectionResource::execute(
std::string && sceneName, SceneExecuteCallback executeCB)
{
auto sceneValues = m_sceneCollectionResourceObject->getAttributeValue(
SCENE_KEY_SCENEVALUES).get< std::vector< std::string > >();
auto foundSceneValue
= std::find(sceneValues.begin(), sceneValues.end(), sceneName);
if (foundSceneValue == sceneValues.end() && executeCB && !m_sceneMembers.size())
{
std::thread(std::move(executeCB), SCENE_CLIENT_BADREQUEST).detach();
return;
}
m_sceneCollectionResourceObject->setAttribute(
SCENE_KEY_LAST_SCENE, sceneName);
{
std::lock_guard<std::mutex> memberlock(m_sceneMemberLock);
auto executeHandler
= SceneExecuteResponseHandler::createExecuteHandler(
shared_from_this(), std::move(executeCB));
for (auto & it : m_sceneMembers)
{
it->execute(std::move(sceneName), std::bind(
&SceneExecuteResponseHandler::onResponse, executeHandler,
std::placeholders::_1, std::placeholders::_2));
}
}
}
std::string SceneCollectionResource::getId() const
{
return m_sceneCollectionResourceObject->getAttributeValue(
SCENE_KEY_ID).get<std::string>();
}
std::string SceneCollectionResource::getUri() const
{
return m_uri;
}
std::string SceneCollectionResource::getAddress() const
{
return m_address;
}
std::vector<std::string> SceneCollectionResource::getSceneValues() const
{
return m_sceneCollectionResourceObject->getAttributeValue(
SCENE_KEY_SCENEVALUES).get<std::vector<std::string>>();
}
std::vector<SceneMemberResource::Ptr> SceneCollectionResource::getSceneMembers() const
{
std::lock_guard<std::mutex> memberlock(m_sceneMemberLock);
return m_sceneMembers;
}
std::vector<SceneMemberResource::Ptr> SceneCollectionResource::findSceneMembers(
const std::string & sceneName) const
{
std::lock_guard<std::mutex> memberlock(m_sceneMemberLock);
std::vector<SceneMemberResource::Ptr> retMembers;
std::for_each(m_sceneMembers.begin(), m_sceneMembers.end(),
[& retMembers, & sceneName](SceneMemberResource::Ptr pMember)
{
if(pMember->hasSceneValue(sceneName))
{
retMembers.push_back(pMember);
}
});
return retMembers;
}
RCSResourceObject::Ptr SceneCollectionResource::getRCSResourceObject() const
{
return m_sceneCollectionResourceObject;
}
void SceneCollectionResource::setName(std::string && sceneCollectionName)
{
m_sceneCollectionResourceObject->setAttribute(
SCENE_KEY_NAME, std::move(sceneCollectionName));
}
void SceneCollectionResource::setName(const std::string & sceneCollectionName)
{
setName(std::string(sceneCollectionName));
}
std::string SceneCollectionResource::getName() const
{
return m_sceneCollectionResourceObject->getAttributeValue(
SCENE_KEY_NAME).get<std::string>();
}
RCSSetResponse SceneCollectionResource::SceneCollectionRequestHandler::
onSetRequest(const RCSRequest & request, RCSResourceAttributes & attributes)
{
if (request.getInterface() == LINK_BATCH)
{
return createSceneMemberRequest(request, attributes);
}
if (attributes.contains(SCENE_KEY_SCENEVALUES))
{
return addSceneRequest(request, attributes);
}
if (attributes.contains(SCENE_KEY_LAST_SCENE))
{
return executeSceneRequest(request, attributes);
}
if (attributes.contains(SCENE_KEY_NAME))
{
return setSceneCollectionName(request, attributes);
}
return RCSSetResponse::create(attributes, (int)SCENE_CLIENT_BADREQUEST).
setAcceptanceMethod(RCSSetResponse::AcceptanceMethod::IGNORE);
}
RCSSetResponse SceneCollectionResource::SceneCollectionRequestHandler::
addSceneRequest(const RCSRequest & /*request*/, RCSResourceAttributes & attributes)
{
SceneCollectionResource::Ptr ptr = m_owner.lock();
if (ptr == nullptr)
{
return RCSSetResponse::create(attributes, SCENE_CLIENT_BADREQUEST).
setAcceptanceMethod(RCSSetResponse::AcceptanceMethod::IGNORE);
}
auto values = attributes.at(SCENE_KEY_SCENEVALUES).get<std::vector<std::string>>();
auto sizeofValues = values.size();
unsigned int sameSize = 0;
std::for_each(values.begin(), values.end(),
[& ptr, & sameSize](const std::string & value)
{
try
{
ptr->addScene(value);
} catch (...)
{
sameSize++;
}
});
int eCode = SCENE_RESPONSE_SUCCESS;
if (sameSize == sizeofValues)
{
eCode = SCENE_CLIENT_BADREQUEST;
}
return RCSSetResponse::create(attributes, eCode).
setAcceptanceMethod(RCSSetResponse::AcceptanceMethod::IGNORE);
}
RCSSetResponse SceneCollectionResource::SceneCollectionRequestHandler::
executeSceneRequest(const RCSRequest & request, RCSResourceAttributes & attributes)
{
SceneCollectionResource::Ptr ptr = m_owner.lock();
if (ptr == nullptr)
{
return RCSSetResponse::create(attributes, SCENE_CLIENT_BADREQUEST).
setAcceptanceMethod(RCSSetResponse::AcceptanceMethod::IGNORE);
}
auto requestKey = attributes.at(SCENE_KEY_LAST_SCENE).get<std::string>();
RCSRequest req(request.getResourceObject().lock(), request.getOCRequest());
ptr->execute(std::string(requestKey),
[req](int /*eCode*/)
{
// TODO need to set error code.
// and need to set specific attr' but this attr not to be apply to RCSResourceObject.
RCSSeparateResponse(req).set();
});
return RCSSetResponse::separate();
}
RCSSetResponse SceneCollectionResource::SceneCollectionRequestHandler::
createSceneMemberRequest(const RCSRequest & /*request*/, RCSResourceAttributes & attributes)
{
int eCode = SCENE_CLIENT_BADREQUEST;
SceneCollectionResource::Ptr ptr = m_owner.lock();
if (!ptr)
{
return RCSSetResponse::create(attributes, eCode).
setAcceptanceMethod(RCSSetResponse::AcceptanceMethod::IGNORE);
}
RCSResourceAttributes responseAtt(attributes);
if (attributes.contains(SCENE_KEY_PAYLOAD_LINK))
{
auto linkAtt = attributes.at(SCENE_KEY_PAYLOAD_LINK).get<RCSResourceAttributes>();
if (linkAtt.contains(SCENE_KEY_HREF) &&
linkAtt.contains(SCENE_KEY_RT) && linkAtt.contains(SCENE_KEY_IF))
{
auto memberObj = SceneMemberResource::createSceneMemberResource(linkAtt);
try
{
ptr->addSceneMember(memberObj);
}
catch (...)
{
return RCSSetResponse::create(responseAtt, eCode).
setAcceptanceMethod(RCSSetResponse::AcceptanceMethod::IGNORE);
}
eCode = SCENE_RESPONSE_SUCCESS;
if (attributes.contains(SCENE_KEY_SCENEMAPPINGS))
{
addMemberInfoFromRemote(memberObj, attributes.at(
SCENE_KEY_SCENEMAPPINGS).get<std::vector<RCSResourceAttributes>>());
}
responseAtt[SCENE_KEY_ID] = RCSResourceAttributes::Value(memberObj->getId());
responseAtt[SCENE_KEY_CREATEDLINK]
= RCSResourceAttributes::Value(memberObj->getFullUri());
}
}
return RCSSetResponse::create(responseAtt, eCode).
setAcceptanceMethod(RCSSetResponse::AcceptanceMethod::IGNORE);
}
RCSSetResponse
SceneCollectionResource::SceneCollectionRequestHandler::setSceneCollectionName(
const RCSRequest & /*request*/, RCSResourceAttributes & attr)
{
int eCode = SCENE_CLIENT_BADREQUEST;
SceneCollectionResource::Ptr ptr = m_owner.lock();
if (ptr != nullptr)
{
eCode = SCENE_RESPONSE_SUCCESS;
ptr->setName(attr.at(SCENE_KEY_NAME).get<std::string>());
}
return RCSSetResponse::create(attr, eCode).
setAcceptanceMethod(RCSSetResponse::AcceptanceMethod::IGNORE);
}
void SceneCollectionResource::SceneCollectionRequestHandler::addMemberInfoFromRemote(
SceneMemberResource::Ptr memberObj, std::vector<RCSResourceAttributes> mInfo)
{
std::for_each(mInfo.begin(), mInfo.end(),
[& memberObj](const RCSResourceAttributes & att)
{
memberObj->addMappingInfo(SceneMemberResource::MappingInfo::create(att));
});
}
void SceneCollectionResource::SceneExecuteResponseHandler::
onResponse(const RCSResourceAttributes & /*attributes*/, int errorCode)
{
m_responseMembers++;
if (errorCode != SCENE_RESPONSE_SUCCESS && m_errorCode != errorCode)
{
m_errorCode = errorCode;
}
if (m_responseMembers == m_numOfMembers)
{
m_cb(m_errorCode);
}
}
SceneCollectionResource::SceneExecuteResponseHandler::Ptr
SceneCollectionResource::SceneExecuteResponseHandler::createExecuteHandler(
const SceneCollectionResource::Ptr ptr, SceneExecuteCallback executeCB)
{
auto executeHandler = std::make_shared<SceneExecuteResponseHandler>();
executeHandler->m_numOfMembers = ptr->m_sceneMembers.size();
executeHandler->m_responseMembers = 0;
executeHandler->m_cb =
[executeCB](int eCode)
{
std::thread(std::move(executeCB), eCode).detach();
};
executeHandler->m_owner
= std::weak_ptr<SceneCollectionResource>(ptr);
executeHandler->m_errorCode = SCENE_RESPONSE_SUCCESS;
return executeHandler;
}
}
}
<|endoftext|> |
<commit_before>/* TyTools - public domain
Niels Martignène <niels.martignene@gmail.com>
https://neodd.com/tytools
This software is in the public domain. Where that dedication is not
recognized, you are granted a perpetual, irrevocable license to copy,
distribute, and modify this file as you see fit.
See the LICENSE file for more details. */
#include <QBrush>
#include <QIcon>
#include "board.hpp"
#include "database.hpp"
#include "descriptor_notifier.hpp"
#include "monitor.hpp"
#include "../libhs/platform.h"
#include "../libty/task.h"
using namespace std;
Monitor::Monitor(QObject *parent)
: QAbstractListModel(parent)
{
int r = ty_pool_new(&pool_);
if (r < 0)
throw bad_alloc();
loadSettings();
}
Monitor::~Monitor()
{
stop();
ty_pool_free(pool_);
ty_monitor_free(monitor_);
}
void Monitor::loadSettings()
{
auto max_tasks = db_.get("maxTasks").toUInt();
if (!max_tasks) {
#ifdef _WIN32
if (hs_win32_version() >= HS_WIN32_VERSION_10) {
/* Windows 10 is much faster to load drivers and make the device available, we
can probably afford that. */
max_tasks = 2;
} else {
max_tasks = 1;
}
#else
max_tasks = 4;
#endif
}
ty_pool_set_max_threads(pool_, max_tasks);
default_serial_ = db_.get("serialByDefault", true).toBool();
serial_log_size_ = db_.get("serialLogSize", 20000000ull).toULongLong();
serial_log_dir_ = db_.get("serialLogDir", "").toString();
emit settingsChanged();
if (started_) {
stop();
start();
}
}
void Monitor::setMaxTasks(unsigned int max_tasks)
{
ty_pool_set_max_threads(pool_, max_tasks);
db_.put("maxTasks", max_tasks);
emit settingsChanged();
}
unsigned int Monitor::maxTasks() const
{
return ty_pool_get_max_threads(pool_);
}
void Monitor::setSerialByDefault(bool default_serial)
{
default_serial_ = default_serial;
for (auto &board: boards_) {
auto db = board->database();
if (!db.get("enableSerial").isValid()) {
board->setEnableSerial(default_serial);
db.remove("enableSerial");
}
}
db_.put("serialByDefault", default_serial);
emit settingsChanged();
}
void Monitor::setSerialLogSize(size_t default_size)
{
serial_log_size_ = default_size;
for (auto &board: boards_) {
auto db = board->database();
if (!db.get("serialLogSize").isValid()) {
board->setSerialLogSize(default_size);
board->updateSerialLogState(false);
db.remove("serialLogSize");
}
}
db_.put("serialLogSize", static_cast<qulonglong>(default_size));
emit settingsChanged();
}
void Monitor::setSerialLogDir(const QString &dir)
{
serial_log_dir_ = dir;
for (auto &board: boards_) {
board->serial_log_dir_ = dir;
board->updateSerialLogState(true);
emit board->settingsChanged();
}
db_.put("serialLogDir", dir);
emit settingsChanged();
}
bool Monitor::start()
{
if (started_)
return true;
int r;
if (!monitor_) {
ty_monitor *monitor;
r = ty_monitor_new(TY_MONITOR_PARALLEL_WAIT, &monitor);
if (r < 0)
return false;
unique_ptr<ty_monitor, decltype(&ty_monitor_free)> monitor_ptr(monitor, ty_monitor_free);
r = ty_monitor_register_callback(monitor, handleEvent, this);
if (r < 0)
return false;
ty_descriptor_set set = {};
ty_monitor_get_descriptors(monitor, &set, 1);
monitor_notifier_.setDescriptorSet(&set);
connect(&monitor_notifier_, &DescriptorNotifier::activated, this, &Monitor::refresh);
monitor_ = monitor_ptr.release();
}
serial_thread_.start();
r = ty_monitor_start(monitor_);
if (r < 0)
return false;
monitor_notifier_.setEnabled(true);
started_ = true;
return true;
}
void Monitor::stop()
{
if (!started_)
return;
serial_thread_.quit();
serial_thread_.wait();
if (!boards_.empty()) {
beginRemoveRows(QModelIndex(), 0, static_cast<int>(boards_.size()));
boards_.clear();
endRemoveRows();
}
monitor_notifier_.setEnabled(false);
ty_monitor_stop(monitor_);
started_ = false;
}
vector<shared_ptr<Board>> Monitor::boards()
{
return boards_;
}
shared_ptr<Board> Monitor::board(unsigned int i)
{
if (i >= boards_.size())
return nullptr;
return boards_[i];
}
unsigned int Monitor::boardCount() const
{
return static_cast<unsigned int>(boards_.size());
}
shared_ptr<Board> Monitor::boardFromModel(const QAbstractItemModel *model,
const QModelIndex &index)
{
auto board = model->data(index, Monitor::ROLE_BOARD).value<Board *>();
return board ? board->shared_from_this() : nullptr;
}
vector<shared_ptr<Board>> Monitor::find(function<bool(Board &board)> filter)
{
auto boards = boards_;
vector<shared_ptr<Board>> matches;
matches.reserve(boards_.size());
for (auto &board: boards_) {
if (filter(*board))
matches.push_back(board);
}
return matches;
}
int Monitor::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return static_cast<int>(boards_.size());
}
int Monitor::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return COLUMN_COUNT;
}
QVariant Monitor::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Vertical || role != Qt::DisplayRole)
return QVariant();
switch (section) {
case COLUMN_BOARD:
return tr("Board");
case COLUMN_STATUS:
return tr("Status");
case COLUMN_IDENTITY:
return tr("Identity");
case COLUMN_LOCATION:
return tr("Location");
case COLUMN_SERIAL_NUMBER:
return tr("Serial Number");
case COLUMN_DESCRIPTION:
return tr("Description");
}
return QVariant();
}
QVariant Monitor::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || index.row() >= static_cast<int>(boards_.size()))
return QVariant();
auto board = boards_[index.row()];
if (role == ROLE_BOARD)
return QVariant::fromValue(board.get());
if (index.column() == 0) {
switch (role) {
case Qt::ToolTipRole:
return tr("%1\n+ Location: %2\n+ Serial Number: %3\n+ Status: %4\n+ Capabilities: %5")
.arg(board->modelName())
.arg(board->location())
.arg(board->serialNumber())
.arg(board->statusText())
.arg(Board::makeCapabilityString(board->capabilities(), tr("(none)")));
case Qt::DecorationRole:
return board->statusIcon();
case Qt::EditRole:
return board->tag();
}
}
if (role == Qt::DisplayRole) {
switch (index.column()) {
case COLUMN_BOARD:
return board->tag();
case COLUMN_MODEL:
return board->modelName();
case COLUMN_STATUS:
return board->statusText();
case COLUMN_IDENTITY:
return board->id();
case COLUMN_LOCATION:
return board->location();
case COLUMN_SERIAL_NUMBER:
return board->serialNumber();
case COLUMN_DESCRIPTION:
return board->description();
}
}
return QVariant();
}
Qt::ItemFlags Monitor::flags(const QModelIndex &index) const
{
Q_UNUSED(index);
return Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled;
}
bool Monitor::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (role != Qt::EditRole || !index.isValid() || index.row() >= static_cast<int>(boards_.size()))
return false;
auto board = boards_[index.row()];
board->setTag(value.toString());
return true;
}
void Monitor::refresh(ty_descriptor desc)
{
Q_UNUSED(desc);
ty_monitor_refresh(monitor_);
}
int Monitor::handleEvent(ty_board *board, ty_monitor_event event, void *udata)
{
auto self = static_cast<Monitor *>(udata);
switch (event) {
case TY_MONITOR_EVENT_ADDED:
self->handleAddedEvent(board);
break;
case TY_MONITOR_EVENT_CHANGED:
case TY_MONITOR_EVENT_DISAPPEARED:
case TY_MONITOR_EVENT_DROPPED:
self->handleChangedEvent(board);
break;
}
return 0;
}
Monitor::iterator Monitor::findBoardIterator(ty_board *board)
{
return find_if(boards_.begin(), boards_.end(),
[=](std::shared_ptr<Board> &ptr) { return ptr->board() == board; });
}
void Monitor::handleAddedEvent(ty_board *board)
{
// Work around the private constructor for make_shared()
struct BoardSharedEnabler : public Board {
BoardSharedEnabler(ty_board *board)
: Board(board) {}
};
auto board_wrapper_ptr = make_shared<BoardSharedEnabler>(board);
auto board_wrapper = board_wrapper_ptr.get();
if (board_wrapper->hasCapability(TY_BOARD_CAPABILITY_UNIQUE))
configureBoardDatabase(*board_wrapper);
board_wrapper->serial_log_dir_ = serial_log_dir_;
board_wrapper->loadSettings(this);
board_wrapper->setThreadPool(pool_);
board_wrapper->serial_notifier_.moveToThread(&serial_thread_);
connect(board_wrapper, &Board::infoChanged, this, [=]() {
refreshBoardItem(findBoardIterator(board));
});
// Don't capture board_wrapper_ptr, this should be obvious but I made the mistake once
connect(board_wrapper, &Board::interfacesChanged, this, [=]() {
if (db_.isValid() && !board_wrapper->database().isValid() &&
board_wrapper->hasCapability(TY_BOARD_CAPABILITY_UNIQUE)) {
configureBoardDatabase(*board_wrapper);
board_wrapper->loadSettings(this);
}
refreshBoardItem(findBoardIterator(board));
});
connect(board_wrapper, &Board::statusChanged, this, [=]() {
refreshBoardItem(findBoardIterator(board));
});
connect(board_wrapper, &Board::progressChanged, this, [=]() {
refreshBoardItem(findBoardIterator(board));
});
connect(board_wrapper, &Board::dropped, this, [=]() {
removeBoardItem(findBoardIterator(board));
});
beginInsertRows(QModelIndex(), static_cast<int>(boards_.size()),
static_cast<int>(boards_.size()));
boards_.push_back(board_wrapper_ptr);
endInsertRows();
emit boardAdded(board_wrapper);
}
void Monitor::handleChangedEvent(ty_board *board)
{
auto it = findBoardIterator(board);
if (it == boards_.end())
return;
auto ptr = *it;
ptr->refreshBoard();
}
void Monitor::refreshBoardItem(iterator it)
{
auto index = createIndex(it - boards_.begin(), 0);
dataChanged(index, index);
}
void Monitor::removeBoardItem(iterator it)
{
beginRemoveRows(QModelIndex(), it - boards_.begin(), it - boards_.begin());
boards_.erase(it);
endRemoveRows();
}
void Monitor::configureBoardDatabase(Board &board)
{
board.setDatabase(db_.subDatabase(board.id()));
board.setCache(cache_.subDatabase(board.id()));
}
<commit_msg>Ignore Monitor setting changes when value is identical<commit_after>/* TyTools - public domain
Niels Martignène <niels.martignene@gmail.com>
https://neodd.com/tytools
This software is in the public domain. Where that dedication is not
recognized, you are granted a perpetual, irrevocable license to copy,
distribute, and modify this file as you see fit.
See the LICENSE file for more details. */
#include <QBrush>
#include <QIcon>
#include "board.hpp"
#include "database.hpp"
#include "descriptor_notifier.hpp"
#include "monitor.hpp"
#include "../libhs/platform.h"
#include "../libty/task.h"
using namespace std;
Monitor::Monitor(QObject *parent)
: QAbstractListModel(parent)
{
int r = ty_pool_new(&pool_);
if (r < 0)
throw bad_alloc();
loadSettings();
}
Monitor::~Monitor()
{
stop();
ty_pool_free(pool_);
ty_monitor_free(monitor_);
}
void Monitor::loadSettings()
{
auto max_tasks = db_.get("maxTasks").toUInt();
if (!max_tasks) {
#ifdef _WIN32
if (hs_win32_version() >= HS_WIN32_VERSION_10) {
/* Windows 10 is much faster to load drivers and make the device available, we
can probably afford that. */
max_tasks = 2;
} else {
max_tasks = 1;
}
#else
max_tasks = 4;
#endif
}
ty_pool_set_max_threads(pool_, max_tasks);
default_serial_ = db_.get("serialByDefault", true).toBool();
serial_log_size_ = db_.get("serialLogSize", 20000000ull).toULongLong();
serial_log_dir_ = db_.get("serialLogDir", "").toString();
emit settingsChanged();
if (started_) {
stop();
start();
}
}
void Monitor::setMaxTasks(unsigned int max_tasks)
{
ty_pool_set_max_threads(pool_, max_tasks);
db_.put("maxTasks", max_tasks);
emit settingsChanged();
}
unsigned int Monitor::maxTasks() const
{
return ty_pool_get_max_threads(pool_);
}
void Monitor::setSerialByDefault(bool default_serial)
{
if (default_serial == default_serial_)
return;
default_serial_ = default_serial;
for (auto &board: boards_) {
auto db = board->database();
if (!db.get("enableSerial").isValid()) {
board->setEnableSerial(default_serial);
db.remove("enableSerial");
}
}
db_.put("serialByDefault", default_serial);
emit settingsChanged();
}
void Monitor::setSerialLogSize(size_t default_size)
{
if (default_size == serial_log_size_)
return;
serial_log_size_ = default_size;
for (auto &board: boards_) {
auto db = board->database();
if (!db.get("serialLogSize").isValid()) {
board->setSerialLogSize(default_size);
board->updateSerialLogState(false);
db.remove("serialLogSize");
}
}
db_.put("serialLogSize", static_cast<qulonglong>(default_size));
emit settingsChanged();
}
void Monitor::setSerialLogDir(const QString &dir)
{
if (dir == serial_log_dir_)
return;
serial_log_dir_ = dir;
for (auto &board: boards_) {
board->serial_log_dir_ = dir;
board->updateSerialLogState(true);
emit board->settingsChanged();
}
db_.put("serialLogDir", dir);
emit settingsChanged();
}
bool Monitor::start()
{
if (started_)
return true;
int r;
if (!monitor_) {
ty_monitor *monitor;
r = ty_monitor_new(TY_MONITOR_PARALLEL_WAIT, &monitor);
if (r < 0)
return false;
unique_ptr<ty_monitor, decltype(&ty_monitor_free)> monitor_ptr(monitor, ty_monitor_free);
r = ty_monitor_register_callback(monitor, handleEvent, this);
if (r < 0)
return false;
ty_descriptor_set set = {};
ty_monitor_get_descriptors(monitor, &set, 1);
monitor_notifier_.setDescriptorSet(&set);
connect(&monitor_notifier_, &DescriptorNotifier::activated, this, &Monitor::refresh);
monitor_ = monitor_ptr.release();
}
serial_thread_.start();
r = ty_monitor_start(monitor_);
if (r < 0)
return false;
monitor_notifier_.setEnabled(true);
started_ = true;
return true;
}
void Monitor::stop()
{
if (!started_)
return;
serial_thread_.quit();
serial_thread_.wait();
if (!boards_.empty()) {
beginRemoveRows(QModelIndex(), 0, static_cast<int>(boards_.size()));
boards_.clear();
endRemoveRows();
}
monitor_notifier_.setEnabled(false);
ty_monitor_stop(monitor_);
started_ = false;
}
vector<shared_ptr<Board>> Monitor::boards()
{
return boards_;
}
shared_ptr<Board> Monitor::board(unsigned int i)
{
if (i >= boards_.size())
return nullptr;
return boards_[i];
}
unsigned int Monitor::boardCount() const
{
return static_cast<unsigned int>(boards_.size());
}
shared_ptr<Board> Monitor::boardFromModel(const QAbstractItemModel *model,
const QModelIndex &index)
{
auto board = model->data(index, Monitor::ROLE_BOARD).value<Board *>();
return board ? board->shared_from_this() : nullptr;
}
vector<shared_ptr<Board>> Monitor::find(function<bool(Board &board)> filter)
{
auto boards = boards_;
vector<shared_ptr<Board>> matches;
matches.reserve(boards_.size());
for (auto &board: boards_) {
if (filter(*board))
matches.push_back(board);
}
return matches;
}
int Monitor::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return static_cast<int>(boards_.size());
}
int Monitor::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return COLUMN_COUNT;
}
QVariant Monitor::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Vertical || role != Qt::DisplayRole)
return QVariant();
switch (section) {
case COLUMN_BOARD:
return tr("Board");
case COLUMN_STATUS:
return tr("Status");
case COLUMN_IDENTITY:
return tr("Identity");
case COLUMN_LOCATION:
return tr("Location");
case COLUMN_SERIAL_NUMBER:
return tr("Serial Number");
case COLUMN_DESCRIPTION:
return tr("Description");
}
return QVariant();
}
QVariant Monitor::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || index.row() >= static_cast<int>(boards_.size()))
return QVariant();
auto board = boards_[index.row()];
if (role == ROLE_BOARD)
return QVariant::fromValue(board.get());
if (index.column() == 0) {
switch (role) {
case Qt::ToolTipRole:
return tr("%1\n+ Location: %2\n+ Serial Number: %3\n+ Status: %4\n+ Capabilities: %5")
.arg(board->modelName())
.arg(board->location())
.arg(board->serialNumber())
.arg(board->statusText())
.arg(Board::makeCapabilityString(board->capabilities(), tr("(none)")));
case Qt::DecorationRole:
return board->statusIcon();
case Qt::EditRole:
return board->tag();
}
}
if (role == Qt::DisplayRole) {
switch (index.column()) {
case COLUMN_BOARD:
return board->tag();
case COLUMN_MODEL:
return board->modelName();
case COLUMN_STATUS:
return board->statusText();
case COLUMN_IDENTITY:
return board->id();
case COLUMN_LOCATION:
return board->location();
case COLUMN_SERIAL_NUMBER:
return board->serialNumber();
case COLUMN_DESCRIPTION:
return board->description();
}
}
return QVariant();
}
Qt::ItemFlags Monitor::flags(const QModelIndex &index) const
{
Q_UNUSED(index);
return Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled;
}
bool Monitor::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (role != Qt::EditRole || !index.isValid() || index.row() >= static_cast<int>(boards_.size()))
return false;
auto board = boards_[index.row()];
board->setTag(value.toString());
return true;
}
void Monitor::refresh(ty_descriptor desc)
{
Q_UNUSED(desc);
ty_monitor_refresh(monitor_);
}
int Monitor::handleEvent(ty_board *board, ty_monitor_event event, void *udata)
{
auto self = static_cast<Monitor *>(udata);
switch (event) {
case TY_MONITOR_EVENT_ADDED:
self->handleAddedEvent(board);
break;
case TY_MONITOR_EVENT_CHANGED:
case TY_MONITOR_EVENT_DISAPPEARED:
case TY_MONITOR_EVENT_DROPPED:
self->handleChangedEvent(board);
break;
}
return 0;
}
Monitor::iterator Monitor::findBoardIterator(ty_board *board)
{
return find_if(boards_.begin(), boards_.end(),
[=](std::shared_ptr<Board> &ptr) { return ptr->board() == board; });
}
void Monitor::handleAddedEvent(ty_board *board)
{
// Work around the private constructor for make_shared()
struct BoardSharedEnabler : public Board {
BoardSharedEnabler(ty_board *board)
: Board(board) {}
};
auto board_wrapper_ptr = make_shared<BoardSharedEnabler>(board);
auto board_wrapper = board_wrapper_ptr.get();
if (board_wrapper->hasCapability(TY_BOARD_CAPABILITY_UNIQUE))
configureBoardDatabase(*board_wrapper);
board_wrapper->serial_log_dir_ = serial_log_dir_;
board_wrapper->loadSettings(this);
board_wrapper->setThreadPool(pool_);
board_wrapper->serial_notifier_.moveToThread(&serial_thread_);
connect(board_wrapper, &Board::infoChanged, this, [=]() {
refreshBoardItem(findBoardIterator(board));
});
// Don't capture board_wrapper_ptr, this should be obvious but I made the mistake once
connect(board_wrapper, &Board::interfacesChanged, this, [=]() {
if (db_.isValid() && !board_wrapper->database().isValid() &&
board_wrapper->hasCapability(TY_BOARD_CAPABILITY_UNIQUE)) {
configureBoardDatabase(*board_wrapper);
board_wrapper->loadSettings(this);
}
refreshBoardItem(findBoardIterator(board));
});
connect(board_wrapper, &Board::statusChanged, this, [=]() {
refreshBoardItem(findBoardIterator(board));
});
connect(board_wrapper, &Board::progressChanged, this, [=]() {
refreshBoardItem(findBoardIterator(board));
});
connect(board_wrapper, &Board::dropped, this, [=]() {
removeBoardItem(findBoardIterator(board));
});
beginInsertRows(QModelIndex(), static_cast<int>(boards_.size()),
static_cast<int>(boards_.size()));
boards_.push_back(board_wrapper_ptr);
endInsertRows();
emit boardAdded(board_wrapper);
}
void Monitor::handleChangedEvent(ty_board *board)
{
auto it = findBoardIterator(board);
if (it == boards_.end())
return;
auto ptr = *it;
ptr->refreshBoard();
}
void Monitor::refreshBoardItem(iterator it)
{
auto index = createIndex(it - boards_.begin(), 0);
dataChanged(index, index);
}
void Monitor::removeBoardItem(iterator it)
{
beginRemoveRows(QModelIndex(), it - boards_.begin(), it - boards_.begin());
boards_.erase(it);
endRemoveRows();
}
void Monitor::configureBoardDatabase(Board &board)
{
board.setDatabase(db_.subDatabase(board.id()));
board.setCache(cache_.subDatabase(board.id()));
}
<|endoftext|> |
<commit_before>#include <QtGui>
#include <QDebug>
#include "i18n.h"
#include "account-mgr.h"
#include "utils/utils.h"
#include "seafile-applet.h"
#include "settings-mgr.h"
#include "api/requests.h"
#include "settings-dialog.h"
namespace {
bool isCheckLatestVersionEnabled() {
return QString(getBrand()) == "Seafile";
}
} // namespace
SettingsDialog::SettingsDialog(QWidget *parent) : QDialog(parent)
{
setupUi(this);
setWindowTitle(tr("Settings"));
setWindowIcon(QIcon(":/images/seafile.png"));
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
mTabWidget->setCurrentIndex(0);
// Since closeEvent() would not not called when accept() is called, we
// need to handle it here.
connect(this, SIGNAL(accepted()), this, SLOT(updateSettings()));
if (!isCheckLatestVersionEnabled()) {
mCheckLatestVersionBox->setVisible(false);
}
mLanguageComboBox->addItems(I18NHelper::getInstance()->getLanguages());
#ifdef Q_WS_MAC
layout()->setContentsMargins(8, 9, 9, 4);
layout()->setSpacing(5);
#endif
}
void SettingsDialog::updateSettings()
{
SettingsManager *mgr = seafApplet->settingsManager();
mgr->setNotify(mNotifyCheckBox->checkState() == Qt::Checked);
mgr->setAutoStart(mAutoStartCheckBox->checkState() == Qt::Checked);
mgr->setHideDockIcon(mHideDockIconCheckBox->checkState() == Qt::Checked);
mgr->setSyncExtraTempFile(mSyncExtraTempFileCheckBox->checkState() == Qt::Checked);
mgr->setMaxDownloadRatio(mDownloadSpinBox->value());
mgr->setMaxUploadRatio(mUploadSpinBox->value());
mgr->setHideMainWindowWhenStarted(mHideMainWinCheckBox->checkState() == Qt::Checked);
mgr->setAllowInvalidWorktree(mAllowInvalidWorktreeCheckBox->checkState() == Qt::Checked);
mgr->setHttpSyncEnabled(mEnableHttpSyncCheckBox->checkState() == Qt::Checked);
mgr->setHttpSyncCertVerifyDisabled(mDisableVerifyHttpSyncCert->checkState() == Qt::Checked);
mgr->setAllowRepoNotFoundOnServer(mAllowRepoNotFoundCheckBox->checkState() == Qt::Checked);
if (isCheckLatestVersionEnabled()) {
bool enabled = mCheckLatestVersionBox->checkState() == Qt::Checked;
mgr->setCheckLatestVersionEnabled(enabled);
}
if (mLanguageComboBox->currentIndex() != I18NHelper::getInstance()->preferredLanguage()) {
I18NHelper::getInstance()->setPreferredLanguage(mLanguageComboBox->currentIndex());
if (seafApplet->yesOrNoBox(tr("You have changed languange. Restart to apply it?"), this, true))
seafApplet->restartApp();
}
}
void SettingsDialog::closeEvent(QCloseEvent *event)
{
updateSettings();
event->ignore();
this->hide();
}
void SettingsDialog::showEvent(QShowEvent *event)
{
Qt::CheckState state;
int ratio;
SettingsManager *mgr = seafApplet->settingsManager();
mgr->loadSettings();
state = mgr->hideMainWindowWhenStarted() ? Qt::Checked : Qt::Unchecked;
mHideMainWinCheckBox->setCheckState(state);
state = mgr->allowInvalidWorktree() ? Qt::Checked : Qt::Unchecked;
mAllowInvalidWorktreeCheckBox->setCheckState(state);
state = mgr->syncExtraTempFile() ? Qt::Checked : Qt::Unchecked;
mSyncExtraTempFileCheckBox->setCheckState(state);
state = mgr->allowRepoNotFoundOnServer() ? Qt::Checked : Qt::Unchecked;
mAllowRepoNotFoundCheckBox->setCheckState(state);
state = mgr->httpSyncEnabled() ? Qt::Checked : Qt::Unchecked;
mEnableHttpSyncCheckBox->setCheckState(state);
state = mgr->httpSyncCertVerifyDisabled() ? Qt::Checked : Qt::Unchecked;
mDisableVerifyHttpSyncCert->setCheckState(state);
// currently supports windows only
state = mgr->autoStart() ? Qt::Checked : Qt::Unchecked;
mAutoStartCheckBox->setCheckState(state);
#if !defined(Q_WS_WIN) && !defined(Q_WS_MAC)
mAutoStartCheckBox->hide();
#endif
// currently supports mac only
state = mgr->hideDockIcon() ? Qt::Checked : Qt::Unchecked;
mHideDockIconCheckBox->setCheckState(state);
#if !defined(Q_WS_MAC)
mHideDockIconCheckBox->hide();
#endif
state = mgr->notify() ? Qt::Checked : Qt::Unchecked;
mNotifyCheckBox->setCheckState(state);
ratio = mgr->maxDownloadRatio();
mDownloadSpinBox->setValue(ratio);
ratio = mgr->maxUploadRatio();
mUploadSpinBox->setValue(ratio);
if (isCheckLatestVersionEnabled()) {
state = mgr->isCheckLatestVersionEnabled() ? Qt::Checked : Qt::Unchecked;
mCheckLatestVersionBox->setCheckState(state);
}
mLanguageComboBox->setCurrentIndex(I18NHelper::getInstance()->preferredLanguage());
QDialog::showEvent(event);
}
void SettingsDialog::autoStartChanged(int state)
{
qDebug("%s :%d", __func__, state);
bool autoStart = (mAutoStartCheckBox->checkState() == Qt::Checked);
seafApplet->settingsManager()->setAutoStart(autoStart);
}
void SettingsDialog::hideDockIconChanged(int state)
{
qDebug("%s :%d", __func__, state);
bool hideDockIcon = (mHideDockIconCheckBox->checkState() == Qt::Checked);
seafApplet->settingsManager()->setHideDockIcon(hideDockIcon);
}
void SettingsDialog::notifyChanged(int state)
{
qDebug("%s :%d", __func__, state);
bool notify = (mNotifyCheckBox->checkState() == Qt::Checked);
seafApplet->settingsManager()->setNotify(notify);
}
void SettingsDialog::downloadChanged(int value)
{
qDebug("%s :%d", __func__, value);
seafApplet->settingsManager()->setMaxDownloadRatio(mDownloadSpinBox->value());
}
void SettingsDialog::uploadChanged(int value)
{
qDebug("%s :%d", __func__, value);
seafApplet->settingsManager()->setMaxUploadRatio(mUploadSpinBox->value());
}
<commit_msg>fixed a bug of settings dialog<commit_after>#include <QtGui>
#include <QDebug>
#include "i18n.h"
#include "account-mgr.h"
#include "utils/utils.h"
#include "seafile-applet.h"
#include "settings-mgr.h"
#include "api/requests.h"
#include "settings-dialog.h"
namespace {
bool isCheckLatestVersionEnabled() {
return QString(getBrand()) == "Seafile";
}
} // namespace
SettingsDialog::SettingsDialog(QWidget *parent) : QDialog(parent)
{
setupUi(this);
setWindowTitle(tr("Settings"));
setWindowIcon(QIcon(":/images/seafile.png"));
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
mTabWidget->setCurrentIndex(0);
// Since closeEvent() would not not called when accept() is called, we
// need to handle it here.
connect(this, SIGNAL(accepted()), this, SLOT(updateSettings()));
if (!isCheckLatestVersionEnabled()) {
mCheckLatestVersionBox->setVisible(false);
}
mLanguageComboBox->addItems(I18NHelper::getInstance()->getLanguages());
#ifdef Q_WS_MAC
layout()->setContentsMargins(8, 9, 9, 4);
layout()->setSpacing(5);
#endif
}
void SettingsDialog::updateSettings()
{
SettingsManager *mgr = seafApplet->settingsManager();
mgr->setNotify(mNotifyCheckBox->checkState() == Qt::Checked);
mgr->setAutoStart(mAutoStartCheckBox->checkState() == Qt::Checked);
mgr->setHideDockIcon(mHideDockIconCheckBox->checkState() == Qt::Checked);
mgr->setSyncExtraTempFile(mSyncExtraTempFileCheckBox->checkState() == Qt::Checked);
mgr->setMaxDownloadRatio(mDownloadSpinBox->value());
mgr->setMaxUploadRatio(mUploadSpinBox->value());
mgr->setHideMainWindowWhenStarted(mHideMainWinCheckBox->checkState() == Qt::Checked);
mgr->setAllowInvalidWorktree(mAllowInvalidWorktreeCheckBox->checkState() == Qt::Checked);
mgr->setHttpSyncEnabled(mEnableHttpSyncCheckBox->checkState() == Qt::Checked);
mgr->setHttpSyncCertVerifyDisabled(mDisableVerifyHttpSyncCert->checkState() == Qt::Checked);
mgr->setAllowRepoNotFoundOnServer(mAllowRepoNotFoundCheckBox->checkState() == Qt::Checked);
if (isCheckLatestVersionEnabled()) {
bool enabled = mCheckLatestVersionBox->checkState() == Qt::Checked;
mgr->setCheckLatestVersionEnabled(enabled);
}
if (mLanguageComboBox->currentIndex() != I18NHelper::getInstance()->preferredLanguage()) {
I18NHelper::getInstance()->setPreferredLanguage(mLanguageComboBox->currentIndex());
if (seafApplet->yesOrNoBox(tr("You have changed languange. Restart to apply it?"), this, true))
seafApplet->restartApp();
}
}
void SettingsDialog::closeEvent(QCloseEvent *event)
{
event->ignore();
this->hide();
}
void SettingsDialog::showEvent(QShowEvent *event)
{
Qt::CheckState state;
int ratio;
SettingsManager *mgr = seafApplet->settingsManager();
mgr->loadSettings();
state = mgr->hideMainWindowWhenStarted() ? Qt::Checked : Qt::Unchecked;
mHideMainWinCheckBox->setCheckState(state);
state = mgr->allowInvalidWorktree() ? Qt::Checked : Qt::Unchecked;
mAllowInvalidWorktreeCheckBox->setCheckState(state);
state = mgr->syncExtraTempFile() ? Qt::Checked : Qt::Unchecked;
mSyncExtraTempFileCheckBox->setCheckState(state);
state = mgr->allowRepoNotFoundOnServer() ? Qt::Checked : Qt::Unchecked;
mAllowRepoNotFoundCheckBox->setCheckState(state);
state = mgr->httpSyncEnabled() ? Qt::Checked : Qt::Unchecked;
mEnableHttpSyncCheckBox->setCheckState(state);
state = mgr->httpSyncCertVerifyDisabled() ? Qt::Checked : Qt::Unchecked;
mDisableVerifyHttpSyncCert->setCheckState(state);
// currently supports windows only
state = mgr->autoStart() ? Qt::Checked : Qt::Unchecked;
mAutoStartCheckBox->setCheckState(state);
#if !defined(Q_WS_WIN) && !defined(Q_WS_MAC)
mAutoStartCheckBox->hide();
#endif
// currently supports mac only
state = mgr->hideDockIcon() ? Qt::Checked : Qt::Unchecked;
mHideDockIconCheckBox->setCheckState(state);
#if !defined(Q_WS_MAC)
mHideDockIconCheckBox->hide();
#endif
state = mgr->notify() ? Qt::Checked : Qt::Unchecked;
mNotifyCheckBox->setCheckState(state);
ratio = mgr->maxDownloadRatio();
mDownloadSpinBox->setValue(ratio);
ratio = mgr->maxUploadRatio();
mUploadSpinBox->setValue(ratio);
if (isCheckLatestVersionEnabled()) {
state = mgr->isCheckLatestVersionEnabled() ? Qt::Checked : Qt::Unchecked;
mCheckLatestVersionBox->setCheckState(state);
}
mLanguageComboBox->setCurrentIndex(I18NHelper::getInstance()->preferredLanguage());
QDialog::showEvent(event);
}
void SettingsDialog::autoStartChanged(int state)
{
qDebug("%s :%d", __func__, state);
bool autoStart = (mAutoStartCheckBox->checkState() == Qt::Checked);
seafApplet->settingsManager()->setAutoStart(autoStart);
}
void SettingsDialog::hideDockIconChanged(int state)
{
qDebug("%s :%d", __func__, state);
bool hideDockIcon = (mHideDockIconCheckBox->checkState() == Qt::Checked);
seafApplet->settingsManager()->setHideDockIcon(hideDockIcon);
}
void SettingsDialog::notifyChanged(int state)
{
qDebug("%s :%d", __func__, state);
bool notify = (mNotifyCheckBox->checkState() == Qt::Checked);
seafApplet->settingsManager()->setNotify(notify);
}
void SettingsDialog::downloadChanged(int value)
{
qDebug("%s :%d", __func__, value);
seafApplet->settingsManager()->setMaxDownloadRatio(mDownloadSpinBox->value());
}
void SettingsDialog::uploadChanged(int value)
{
qDebug("%s :%d", __func__, value);
seafApplet->settingsManager()->setMaxUploadRatio(mUploadSpinBox->value());
}
<|endoftext|> |
<commit_before>/*
* Copyright 2011-2020 Branimir Karadzic. All rights reserved.
* License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
*/
#include <bx/easing.h>
#include "common.h"
#include "bgfx_utils.h"
#include "imgui/imgui.h"
extern "C" void ProgressiveMesh(int vert_n, int vert_stride, const float *v, int tri_n, const int *tri, int *map, int *permutation);
static void * Alloc(size_t sz) {
return BX_ALLOC(entry::getAllocator(), sz);
}
static void Free(void *p) {
BX_FREE(entry::getAllocator(), p);
}
namespace
{
class ExampleBunnyLOD : public entry::AppI
{
public:
ExampleBunnyLOD(const char* _name, const char* _description, const char* _url)
: entry::AppI(_name, _description, _url)
{
}
void PermuteMesh(const bgfx::Memory *vb, const bgfx::Memory *ib, const bgfx::VertexLayout &layout) {
int i;
int stride = layout.getStride();
int offset = layout.getOffset(bgfx::Attrib::Position);
int vertices = vb->size / stride;
int triangles = ib->size / ( 3 * sizeof(uint32_t) );
int *permutation = (int*)Alloc(vertices * sizeof(int));
m_map = (int *)Alloc(vertices * sizeof(int));
// It will takes long time if there are too many vertices.
ProgressiveMesh(vertices, stride, (const float *)(vb->data + offset), triangles, (const int *)ib->data, m_map, permutation);
// rearrange the vertex Array
char * temp = (char *)Alloc(vertices * stride);
bx::memCopy(temp, vb->data, vb->size);
for (i = 0; i<vertices; i++) {
bx::memCopy(vb->data + permutation[i] * stride , temp + i * stride, stride);
}
Free(temp);
// update the changes in the entries in the triangle Array
for (i = 0; i<triangles * 3; i++) {
int *indices = (int *)(ib->data + i * sizeof(uint32_t));
*indices = permutation[*indices];
}
Free(permutation);
}
int findDuplicateVertices(const char *vb, int n, const bgfx::VertexLayout &layout, int *map) {
int i,j;
int stride = layout.getStride();
int poffset = layout.getOffset(bgfx::Attrib::Position);
for (i=0;i<n;i++) {
map[i] = i;
}
int merge = 0;
for (i=merge;i<n;i++) {
if (map[i] == i) {
float *p1 = (float *)(vb + i*stride + poffset);
map[i] = merge;
for (j=i+1;j<n;j++) {
if (map[j] == j) {
float *p2 = (float *)(vb + j*stride + poffset);
if (p1[0] == p2[0] && p1[1] == p2[1] && p1[2] == p2[2]) {
map[j] = merge;
}
}
}
++merge;
}
}
return merge;
}
const bgfx::Memory * mergeVertices(const char *vb, int stride, const int *map, int n, int merged) {
const bgfx::Memory * buffer = bgfx::alloc(stride * merged);
int i;
int target = 0;
for (i=0;i<n;i++) {
if (map[i] == target) {
bx::memCopy(buffer->data + target*stride, vb + i*stride, stride);
++target;
}
}
return buffer;
}
void loadMesh(Mesh *mesh) {
// merge sub mesh
int vertices = 0;
int indices = 0;
for (GroupArray::const_iterator it = mesh->m_groups.begin(), itEnd = mesh->m_groups.end(); it != itEnd; ++it) {
vertices += it->m_numVertices;
indices += it->m_numIndices;
}
const bgfx::Memory *ib = bgfx::alloc(indices * sizeof(uint32_t));
char * vb_data = (char *)Alloc(mesh->m_layout.getSize(vertices));
size_t voffset = 0;
size_t ioffset = 0;
int index = 0;
for (GroupArray::const_iterator it = mesh->m_groups.begin(), itEnd = mesh->m_groups.end(); it != itEnd; ++it) {
size_t vsize = mesh->m_layout.getSize(it->m_numVertices);
bx::memCopy(vb_data + voffset, it->m_vertices, vsize);
uint32_t *ibptr = (uint32_t *)(ib->data + ioffset);
for (uint32_t i = 0; i<it->m_numIndices; i++) {
ibptr[i] = it->m_indices[i] + index;
}
voffset+=vsize;
ioffset+=it->m_numIndices * sizeof(uint32_t);
index+=it->m_numVertices;
}
int * map = (int *)Alloc(vertices * sizeof(int));
int merged = findDuplicateVertices(vb_data, vertices, mesh->m_layout, map);
const bgfx::Memory *vb = mergeVertices(vb_data, mesh->m_layout.getStride(), map, vertices, merged);
Free(vb_data);
vertices = merged;
int i;
int *ib_data = (int *)ib->data;
for (i=0; i<indices; i++) {
ib_data[i] = map[ib_data[i]];
}
Free(map);
PermuteMesh(vb, ib, mesh->m_layout);
m_triangle = (int *)Alloc(ib->size);
bx::memCopy(m_triangle, ib->data, ib->size);
m_vb = bgfx::createVertexBuffer(vb, mesh->m_layout);
m_ib = bgfx::createDynamicIndexBuffer(ib, BGFX_BUFFER_INDEX32);
m_numVertices = vertices;
m_numTriangles = indices/3;
m_totalVertices = m_numVertices;
m_totalTriangles = m_numTriangles;
}
void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
{
Args args(_argc, _argv);
m_width = _width;
m_height = _height;
m_debug = BGFX_DEBUG_NONE;
m_reset = BGFX_RESET_VSYNC;
bgfx::Init init;
init.type = args.m_type;
init.vendorId = args.m_pciId;
init.resolution.width = m_width;
init.resolution.height = m_height;
init.resolution.reset = m_reset;
bgfx::init(init);
// Enable debug text.
bgfx::setDebug(m_debug);
// Set view 0 clear state.
bgfx::setViewClear(0
, BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
, 0x303030ff
, 1.0f
, 0
);
u_tint = bgfx::createUniform("u_tint", bgfx::UniformType::Vec4);
// Create program from shaders.
m_program = loadProgram("vs_picking_shaded", "fs_picking_shaded");
Mesh *mesh = meshLoad("meshes/bunny_patched.bin", true);
loadMesh(mesh);
meshUnload(mesh);
m_timeOffset = bx::getHPCounter();
m_LOD = 1.0f;
m_lastLOD = m_LOD;
imguiCreate();
}
int shutdown() override
{
imguiDestroy();
// Cleanup.
bgfx::destroy(m_program);
bgfx::destroy(m_vb);
bgfx::destroy(m_ib);
bgfx::destroy(u_tint);
Free(m_map);
Free(m_triangle);
// Shutdown bgfx.
bgfx::shutdown();
return 0;
}
void updateIndexBuffer() {
int verts = bx::easeInQuad(m_LOD) * m_totalVertices;
if (verts <= 0)
return;
int i,j;
int tris = 0;
const bgfx::Memory * ib = bgfx::alloc(m_totalTriangles * 3 * sizeof(uint32_t));
for (i = 0; i < (int)m_totalTriangles; i++) {
int v[3];
for (j=0;j<3;j++) {
int idx = m_triangle[i*3+j];
while (idx >= verts) {
idx = m_map[idx];
}
v[j] = idx;
}
if (v[0] != v[1] && v[0] != v[2] && v[1] != v[2]) {
bx::memCopy(ib->data + tris * 3 * sizeof(uint32_t), v, 3 * sizeof(int));
++tris;
}
}
m_numTriangles = tris;
m_numVertices = verts;
bgfx::update(m_ib, 0, ib);
}
void submitLOD(bgfx::ViewId viewid, const float *mtx) {
bgfx::setTransform(mtx);
bgfx::setState(0
| BGFX_STATE_WRITE_RGB
| BGFX_STATE_WRITE_A
| BGFX_STATE_WRITE_Z
| BGFX_STATE_DEPTH_TEST_LESS
| BGFX_STATE_CULL_CCW
| BGFX_STATE_MSAA
);
if (m_LOD != m_lastLOD) {
updateIndexBuffer();
m_lastLOD = m_LOD;
}
bgfx::setIndexBuffer(m_ib, 0, m_numTriangles*3);
bgfx::setVertexBuffer(0, m_vb, 0, m_numVertices);
bgfx::submit(viewid, m_program);
}
bool update() override
{
if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState) )
{
imguiBeginFrame(m_mouseState.m_mx
, m_mouseState.m_my
, (m_mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0)
| (m_mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0)
| (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
, m_mouseState.m_mz
, uint16_t(m_width)
, uint16_t(m_height)
);
showExampleDialog(this);
ImGui::SetNextWindowPos(
ImVec2(m_width - m_width / 5.0f - 10.0f, 10.0f)
, ImGuiCond_FirstUseEver
);
ImGui::SetNextWindowSize(
ImVec2(m_width / 5.0f, m_height / 2.0f)
, ImGuiCond_FirstUseEver
);
ImGui::Begin("Settings"
, NULL
, 0
);
ImGui::Text("Vertices: %d", m_numVertices);
ImGui::Text("Triangles: %d", m_numTriangles);
ImGui::SliderFloat("LOD Level", &m_LOD, 0.05f, 1.0f);
ImGui::End();
imguiEndFrame();
// Set view 0 default viewport.
bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) );
// This dummy draw call is here to make sure that view 0 is cleared
// if no other draw calls are submitted to view 0.
bgfx::touch(0);
float time = (float)( (bx::getHPCounter()-m_timeOffset)/double(bx::getHPFrequency() ) );
const float BasicColor[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
bgfx::setUniform(u_tint, BasicColor);
const bx::Vec3 at = { 0.0f, 1.0f, 0.0f };
const bx::Vec3 eye = { 0.0f, 1.0f, -2.5f };
// Set view and projection matrix for view 0.
{
float view[16];
bx::mtxLookAt(view, eye, at);
float proj[16];
bx::mtxProj(proj, 60.0f, float(m_width)/float(m_height), 0.1f, 100.0f, bgfx::getCaps()->homogeneousDepth);
bgfx::setViewTransform(0, view, proj);
// Set view 0 default viewport.
bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) );
}
float mtx[16];
bx::mtxRotateXY(mtx
, 0.0f
, time*0.37f
);
submitLOD(0, mtx);
// Advance to next frame. Rendering thread will be kicked to
// process submitted rendering primitives.
bgfx::frame();
return true;
}
return false;
}
entry::MouseState m_mouseState;
uint32_t m_width;
uint32_t m_height;
uint32_t m_debug;
uint32_t m_reset;
float m_lastLOD;
float m_LOD;
uint32_t m_numVertices;
uint32_t m_numTriangles;
uint32_t m_totalVertices;
uint32_t m_totalTriangles;
int *m_map;
int *m_triangle;
int64_t m_timeOffset;
bgfx::VertexBufferHandle m_vb;
bgfx::DynamicIndexBufferHandle m_ib;
bgfx::ProgramHandle m_program;
bgfx::UniformHandle u_tint;
};
} // namespace
ENTRY_IMPLEMENT_MAIN(
ExampleBunnyLOD
, "42-bunnylod"
, "Progressive Mesh LOD"
, "https://bkaradzic.github.io/bgfx/examples.html#bunnylod"
);
<commit_msg>Fixed warning.<commit_after>/*
* Copyright 2011-2020 Branimir Karadzic. All rights reserved.
* License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
*/
#include <bx/easing.h>
#include "common.h"
#include "bgfx_utils.h"
#include "imgui/imgui.h"
extern "C" void ProgressiveMesh(int vert_n, int vert_stride, const float *v, int tri_n, const int *tri, int *map, int *permutation);
static void * Alloc(size_t sz) {
return BX_ALLOC(entry::getAllocator(), sz);
}
static void Free(void *p) {
BX_FREE(entry::getAllocator(), p);
}
namespace
{
class ExampleBunnyLOD : public entry::AppI
{
public:
ExampleBunnyLOD(const char* _name, const char* _description, const char* _url)
: entry::AppI(_name, _description, _url)
{
}
void PermuteMesh(const bgfx::Memory *vb, const bgfx::Memory *ib, const bgfx::VertexLayout &layout) {
int i;
int stride = layout.getStride();
int offset = layout.getOffset(bgfx::Attrib::Position);
int vertices = vb->size / stride;
int triangles = ib->size / ( 3 * sizeof(uint32_t) );
int *permutation = (int*)Alloc(vertices * sizeof(int));
m_map = (int *)Alloc(vertices * sizeof(int));
// It will takes long time if there are too many vertices.
ProgressiveMesh(vertices, stride, (const float *)(vb->data + offset), triangles, (const int *)ib->data, m_map, permutation);
// rearrange the vertex Array
char * temp = (char *)Alloc(vertices * stride);
bx::memCopy(temp, vb->data, vb->size);
for (i = 0; i<vertices; i++) {
bx::memCopy(vb->data + permutation[i] * stride , temp + i * stride, stride);
}
Free(temp);
// update the changes in the entries in the triangle Array
for (i = 0; i<triangles * 3; i++) {
int *indices = (int *)(ib->data + i * sizeof(uint32_t));
*indices = permutation[*indices];
}
Free(permutation);
}
int findDuplicateVertices(const char *vb, int n, const bgfx::VertexLayout &layout, int *map) {
int i,j;
int stride = layout.getStride();
int poffset = layout.getOffset(bgfx::Attrib::Position);
for (i=0;i<n;i++) {
map[i] = i;
}
int merge = 0;
for (i=merge;i<n;i++) {
if (map[i] == i) {
float *p1 = (float *)(vb + i*stride + poffset);
map[i] = merge;
for (j=i+1;j<n;j++) {
if (map[j] == j) {
float *p2 = (float *)(vb + j*stride + poffset);
if (p1[0] == p2[0] && p1[1] == p2[1] && p1[2] == p2[2]) {
map[j] = merge;
}
}
}
++merge;
}
}
return merge;
}
const bgfx::Memory * mergeVertices(const char *vb, int stride, const int *map, int n, int merged) {
const bgfx::Memory * buffer = bgfx::alloc(stride * merged);
int i;
int target = 0;
for (i=0;i<n;i++) {
if (map[i] == target) {
bx::memCopy(buffer->data + target*stride, vb + i*stride, stride);
++target;
}
}
return buffer;
}
void loadMesh(Mesh *mesh) {
// merge sub mesh
int vertices = 0;
int indices = 0;
for (GroupArray::const_iterator it = mesh->m_groups.begin(), itEnd = mesh->m_groups.end(); it != itEnd; ++it) {
vertices += it->m_numVertices;
indices += it->m_numIndices;
}
const bgfx::Memory *ib = bgfx::alloc(indices * sizeof(uint32_t));
char * vb_data = (char *)Alloc(mesh->m_layout.getSize(vertices));
size_t voffset = 0;
size_t ioffset = 0;
int index = 0;
for (GroupArray::const_iterator it = mesh->m_groups.begin(), itEnd = mesh->m_groups.end(); it != itEnd; ++it) {
size_t vsize = mesh->m_layout.getSize(it->m_numVertices);
bx::memCopy(vb_data + voffset, it->m_vertices, vsize);
uint32_t *ibptr = (uint32_t *)(ib->data + ioffset);
for (uint32_t i = 0; i<it->m_numIndices; i++) {
ibptr[i] = it->m_indices[i] + index;
}
voffset+=vsize;
ioffset+=it->m_numIndices * sizeof(uint32_t);
index+=it->m_numVertices;
}
int * map = (int *)Alloc(vertices * sizeof(int));
int merged = findDuplicateVertices(vb_data, vertices, mesh->m_layout, map);
const bgfx::Memory *vb = mergeVertices(vb_data, mesh->m_layout.getStride(), map, vertices, merged);
Free(vb_data);
vertices = merged;
int i;
int *ib_data = (int *)ib->data;
for (i=0; i<indices; i++) {
ib_data[i] = map[ib_data[i]];
}
Free(map);
PermuteMesh(vb, ib, mesh->m_layout);
m_triangle = (int *)Alloc(ib->size);
bx::memCopy(m_triangle, ib->data, ib->size);
m_vb = bgfx::createVertexBuffer(vb, mesh->m_layout);
m_ib = bgfx::createDynamicIndexBuffer(ib, BGFX_BUFFER_INDEX32);
m_numVertices = vertices;
m_numTriangles = indices/3;
m_totalVertices = m_numVertices;
m_totalTriangles = m_numTriangles;
}
void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
{
Args args(_argc, _argv);
m_width = _width;
m_height = _height;
m_debug = BGFX_DEBUG_NONE;
m_reset = BGFX_RESET_VSYNC;
bgfx::Init init;
init.type = args.m_type;
init.vendorId = args.m_pciId;
init.resolution.width = m_width;
init.resolution.height = m_height;
init.resolution.reset = m_reset;
bgfx::init(init);
// Enable debug text.
bgfx::setDebug(m_debug);
// Set view 0 clear state.
bgfx::setViewClear(0
, BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
, 0x303030ff
, 1.0f
, 0
);
u_tint = bgfx::createUniform("u_tint", bgfx::UniformType::Vec4);
// Create program from shaders.
m_program = loadProgram("vs_picking_shaded", "fs_picking_shaded");
Mesh *mesh = meshLoad("meshes/bunny_patched.bin", true);
loadMesh(mesh);
meshUnload(mesh);
m_timeOffset = bx::getHPCounter();
m_LOD = 1.0f;
m_lastLOD = m_LOD;
imguiCreate();
}
int shutdown() override
{
imguiDestroy();
// Cleanup.
bgfx::destroy(m_program);
bgfx::destroy(m_vb);
bgfx::destroy(m_ib);
bgfx::destroy(u_tint);
Free(m_map);
Free(m_triangle);
// Shutdown bgfx.
bgfx::shutdown();
return 0;
}
void updateIndexBuffer() {
int verts = int(bx::easeInQuad(m_LOD) * m_totalVertices);
if (verts <= 0)
return;
int i,j;
int tris = 0;
const bgfx::Memory * ib = bgfx::alloc(m_totalTriangles * 3 * sizeof(uint32_t));
for (i = 0; i < (int)m_totalTriangles; i++) {
int v[3];
for (j=0;j<3;j++) {
int idx = m_triangle[i*3+j];
while (idx >= verts) {
idx = m_map[idx];
}
v[j] = idx;
}
if (v[0] != v[1] && v[0] != v[2] && v[1] != v[2]) {
bx::memCopy(ib->data + tris * 3 * sizeof(uint32_t), v, 3 * sizeof(int));
++tris;
}
}
m_numTriangles = tris;
m_numVertices = verts;
bgfx::update(m_ib, 0, ib);
}
void submitLOD(bgfx::ViewId viewid, const float *mtx) {
bgfx::setTransform(mtx);
bgfx::setState(0
| BGFX_STATE_WRITE_RGB
| BGFX_STATE_WRITE_A
| BGFX_STATE_WRITE_Z
| BGFX_STATE_DEPTH_TEST_LESS
| BGFX_STATE_CULL_CCW
| BGFX_STATE_MSAA
);
if (m_LOD != m_lastLOD) {
updateIndexBuffer();
m_lastLOD = m_LOD;
}
bgfx::setIndexBuffer(m_ib, 0, m_numTriangles*3);
bgfx::setVertexBuffer(0, m_vb, 0, m_numVertices);
bgfx::submit(viewid, m_program);
}
bool update() override
{
if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState) )
{
imguiBeginFrame(m_mouseState.m_mx
, m_mouseState.m_my
, (m_mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0)
| (m_mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0)
| (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
, m_mouseState.m_mz
, uint16_t(m_width)
, uint16_t(m_height)
);
showExampleDialog(this);
ImGui::SetNextWindowPos(
ImVec2(m_width - m_width / 5.0f - 10.0f, 10.0f)
, ImGuiCond_FirstUseEver
);
ImGui::SetNextWindowSize(
ImVec2(m_width / 5.0f, m_height / 2.0f)
, ImGuiCond_FirstUseEver
);
ImGui::Begin("Settings"
, NULL
, 0
);
ImGui::Text("Vertices: %d", m_numVertices);
ImGui::Text("Triangles: %d", m_numTriangles);
ImGui::SliderFloat("LOD Level", &m_LOD, 0.05f, 1.0f);
ImGui::End();
imguiEndFrame();
// Set view 0 default viewport.
bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) );
// This dummy draw call is here to make sure that view 0 is cleared
// if no other draw calls are submitted to view 0.
bgfx::touch(0);
float time = (float)( (bx::getHPCounter()-m_timeOffset)/double(bx::getHPFrequency() ) );
const float BasicColor[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
bgfx::setUniform(u_tint, BasicColor);
const bx::Vec3 at = { 0.0f, 1.0f, 0.0f };
const bx::Vec3 eye = { 0.0f, 1.0f, -2.5f };
// Set view and projection matrix for view 0.
{
float view[16];
bx::mtxLookAt(view, eye, at);
float proj[16];
bx::mtxProj(proj, 60.0f, float(m_width)/float(m_height), 0.1f, 100.0f, bgfx::getCaps()->homogeneousDepth);
bgfx::setViewTransform(0, view, proj);
// Set view 0 default viewport.
bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) );
}
float mtx[16];
bx::mtxRotateXY(mtx
, 0.0f
, time*0.37f
);
submitLOD(0, mtx);
// Advance to next frame. Rendering thread will be kicked to
// process submitted rendering primitives.
bgfx::frame();
return true;
}
return false;
}
entry::MouseState m_mouseState;
uint32_t m_width;
uint32_t m_height;
uint32_t m_debug;
uint32_t m_reset;
float m_lastLOD;
float m_LOD;
uint32_t m_numVertices;
uint32_t m_numTriangles;
uint32_t m_totalVertices;
uint32_t m_totalTriangles;
int *m_map;
int *m_triangle;
int64_t m_timeOffset;
bgfx::VertexBufferHandle m_vb;
bgfx::DynamicIndexBufferHandle m_ib;
bgfx::ProgramHandle m_program;
bgfx::UniformHandle u_tint;
};
} // namespace
ENTRY_IMPLEMENT_MAIN(
ExampleBunnyLOD
, "42-bunnylod"
, "Progressive Mesh LOD"
, "https://bkaradzic.github.io/bgfx/examples.html#bunnylod"
);
<|endoftext|> |
<commit_before>#include "NuulsUploader.hpp"
#include "common/Env.hpp"
#include "common/NetworkRequest.hpp"
#include "providers/twitch/TwitchMessageBuilder.hpp"
#include <QHttpMultiPart>
#define UPLOAD_DELAY 2000
// Delay between uploads in milliseconds
namespace {
QString getImageFileFormat(const QString &path)
{
static QStringList listOfImageFormats = {".png", ".jpg", ".jpeg"};
for (const QString &format : listOfImageFormats)
{
if (path.endsWith(format, Qt::CaseInsensitive))
{
return format.mid(1);
}
}
return QString();
}
boost::optional<QByteArray> convertToPng(QImage image)
{
QByteArray imageData;
QBuffer buf(&imageData);
buf.open(QIODevice::WriteOnly);
bool success = image.save(&buf, "png");
if (success)
{
return boost::optional<QByteArray>(imageData);
}
else
{
return boost::optional<QByteArray>(boost::none);
}
}
} // namespace
namespace chatterino {
// These variables are only used from the main thread.
bool isUploading = false;
std::queue<RawImageData> uploadQueue;
void uploadImageToNuuls(RawImageData imageData, ChannelPtr channel,
ResizingTextEdit &textEdit)
{
const static char *boundary = "thisistheboudaryasd";
const static QString contentType =
QString("multipart/form-data; boundary=%1").arg(boundary);
static QUrl url(Env::get().imageUploaderUrl);
QHttpMultiPart *payload = new QHttpMultiPart(QHttpMultiPart::FormDataType);
QHttpPart part = QHttpPart();
part.setBody(imageData.data);
part.setHeader(QNetworkRequest::ContentTypeHeader,
QString("image/%1").arg(imageData.format));
part.setHeader(QNetworkRequest::ContentLengthHeader,
QVariant(imageData.data.length()));
part.setHeader(
QNetworkRequest::ContentDispositionHeader,
QString("form-data; name=\"attachment\"; filename=\"control_v.%1\"")
.arg(imageData.format));
payload->setBoundary(boundary);
payload->append(part);
NetworkRequest(url, NetworkRequestType::Post)
.header("Content-Type", contentType)
.multiPart(payload)
.onSuccess([&textEdit, channel](NetworkResult result) -> Outcome {
textEdit.insertPlainText(result.getData() + QString(" "));
isUploading = false;
if (uploadQueue.empty())
{
channel->addMessage(makeSystemMessage(
QString("Your image has been uploaded.")));
}
else
{
channel->addMessage(makeSystemMessage(
QString("Your image has been uploaded. %1 left. Please "
"wait until all of them are uploaded. About %2 "
"seconds left.")
.arg(uploadQueue.size(),
uploadQueue.size() * (UPLOAD_DELAY / 1000 + 1))));
// 2 seconds for the timer that's there not to spam the remote server
// and 1 second of actual uploading.
QTimer::singleShot(UPLOAD_DELAY, [channel, &textEdit]() {
uploadImageToNuuls(uploadQueue.front(), channel, textEdit);
uploadQueue.pop();
});
}
return Success;
})
.onError([channel](NetworkResult result) -> bool {
channel->addMessage(makeSystemMessage(
QString("An error happened while uploading your image: %1")
.arg(result.status())));
isUploading = false;
return true;
})
.execute();
}
void upload(const QMimeData *source, ChannelPtr channel,
ResizingTextEdit &outputTextEdit)
{
// There's no need to thread proof this function. It is called only from the main thread.
if (isUploading)
{
channel->addMessage(makeSystemMessage(
QString("Please wait until the upload finishes.")));
return;
}
isUploading = true;
channel->addMessage(makeSystemMessage(QString("Started upload...")));
if (source->hasFormat("image/png"))
{
uploadImageToNuuls({source->data("image/png"), "png"}, channel,
outputTextEdit);
}
else if (source->hasFormat("image/jpeg"))
{
uploadImageToNuuls({source->data("image/jpeg"), "jpeg"}, channel,
outputTextEdit);
}
else if (source->hasFormat("image/gif"))
{
uploadImageToNuuls({source->data("image/gif"), "gif"}, channel,
outputTextEdit);
}
else if (source->hasUrls())
{
// This path gets chosen when files are copied from a file manager, like explorer.exe, caja.
// Each entry in source->urls() is a QUrl pointing to a file that was copied.
for (const QUrl &path : source->urls())
{
QString localPath = path.toLocalFile();
if (!getImageFileFormat(localPath).isEmpty())
{
channel->addMessage(makeSystemMessage(
QString("Uploading image: %1").arg(localPath)));
QImage img = QImage(localPath);
if (img.isNull())
{
channel->addMessage(
makeSystemMessage(QString("Couldn't load image :(")));
isUploading = false;
return;
}
boost::optional<QByteArray> imageData = convertToPng(img);
if (imageData)
{
RawImageData data = {imageData.get(), "png"};
uploadQueue.push(data);
}
else
{
channel->addMessage(makeSystemMessage(
QString("Cannot upload file: %1, Couldn't convert "
"image to png.")
.arg(localPath)));
}
}
else if (localPath.endsWith(".gif"))
{
channel->addMessage(makeSystemMessage(
QString("Uploading GIF: %1").arg(localPath)));
QFile file(localPath);
bool isOkay = file.open(QIODevice::ReadOnly);
if (!isOkay)
{
channel->addMessage(
makeSystemMessage(QString("Failed to open file. :(")));
isUploading = false;
return;
}
RawImageData data = {file.readAll(), "gif"};
uploadQueue.push(data);
file.close();
// file.readAll() => might be a bit big but it /should/ work
}
else
{
channel->addMessage(makeSystemMessage(
QString("Cannot upload file: %1, not an image")
.arg(localPath)));
isUploading = false;
}
}
if (!uploadQueue.empty())
{
uploadImageToNuuls(uploadQueue.front(), channel, outputTextEdit);
uploadQueue.pop();
}
}
else
{ // not PNG, try loading it into QImage and save it to a PNG.
QImage image = qvariant_cast<QImage>(source->imageData());
boost::optional<QByteArray> imageData = convertToPng(image);
if (imageData)
{
uploadImageToNuuls({imageData.get(), "png"}, channel,
outputTextEdit);
}
else
{
channel->addMessage(makeSystemMessage(
QString("Cannot upload file, failed to convert to png.")));
isUploading = false;
}
}
}
} // namespace chatterino
<commit_msg>Fix wrong QSrting::arg() being called by using two calls.<commit_after>#include "NuulsUploader.hpp"
#include "common/Env.hpp"
#include "common/NetworkRequest.hpp"
#include "providers/twitch/TwitchMessageBuilder.hpp"
#include <QHttpMultiPart>
#define UPLOAD_DELAY 2000
// Delay between uploads in milliseconds
namespace {
QString getImageFileFormat(const QString &path)
{
static QStringList listOfImageFormats = {".png", ".jpg", ".jpeg"};
for (const QString &format : listOfImageFormats)
{
if (path.endsWith(format, Qt::CaseInsensitive))
{
return format.mid(1);
}
}
return QString();
}
boost::optional<QByteArray> convertToPng(QImage image)
{
QByteArray imageData;
QBuffer buf(&imageData);
buf.open(QIODevice::WriteOnly);
bool success = image.save(&buf, "png");
if (success)
{
return boost::optional<QByteArray>(imageData);
}
else
{
return boost::optional<QByteArray>(boost::none);
}
}
} // namespace
namespace chatterino {
// These variables are only used from the main thread.
bool isUploading = false;
std::queue<RawImageData> uploadQueue;
void uploadImageToNuuls(RawImageData imageData, ChannelPtr channel,
ResizingTextEdit &textEdit)
{
const static char *boundary = "thisistheboudaryasd";
const static QString contentType =
QString("multipart/form-data; boundary=%1").arg(boundary);
static QUrl url(Env::get().imageUploaderUrl);
QHttpMultiPart *payload = new QHttpMultiPart(QHttpMultiPart::FormDataType);
QHttpPart part = QHttpPart();
part.setBody(imageData.data);
part.setHeader(QNetworkRequest::ContentTypeHeader,
QString("image/%1").arg(imageData.format));
part.setHeader(QNetworkRequest::ContentLengthHeader,
QVariant(imageData.data.length()));
part.setHeader(
QNetworkRequest::ContentDispositionHeader,
QString("form-data; name=\"attachment\"; filename=\"control_v.%1\"")
.arg(imageData.format));
payload->setBoundary(boundary);
payload->append(part);
NetworkRequest(url, NetworkRequestType::Post)
.header("Content-Type", contentType)
.multiPart(payload)
.onSuccess([&textEdit, channel](NetworkResult result) -> Outcome {
textEdit.insertPlainText(result.getData() + QString(" "));
isUploading = false;
if (uploadQueue.empty())
{
channel->addMessage(makeSystemMessage(
QString("Your image has been uploaded.")));
}
else
{
channel->addMessage(makeSystemMessage(
QString("Your image has been uploaded. %1 left. Please "
"wait until all of them are uploaded. About %2 "
"seconds left.")
.arg(uploadQueue.size())
.arg(uploadQueue.size() * (UPLOAD_DELAY / 1000 + 1))));
// 2 seconds for the timer that's there not to spam the remote server
// and 1 second of actual uploading.
QTimer::singleShot(UPLOAD_DELAY, [channel, &textEdit]() {
uploadImageToNuuls(uploadQueue.front(), channel, textEdit);
uploadQueue.pop();
});
}
return Success;
})
.onError([channel](NetworkResult result) -> bool {
channel->addMessage(makeSystemMessage(
QString("An error happened while uploading your image: %1")
.arg(result.status())));
isUploading = false;
return true;
})
.execute();
}
void upload(const QMimeData *source, ChannelPtr channel,
ResizingTextEdit &outputTextEdit)
{
// There's no need to thread proof this function. It is called only from the main thread.
if (isUploading)
{
channel->addMessage(makeSystemMessage(
QString("Please wait until the upload finishes.")));
return;
}
isUploading = true;
channel->addMessage(makeSystemMessage(QString("Started upload...")));
if (source->hasFormat("image/png"))
{
uploadImageToNuuls({source->data("image/png"), "png"}, channel,
outputTextEdit);
}
else if (source->hasFormat("image/jpeg"))
{
uploadImageToNuuls({source->data("image/jpeg"), "jpeg"}, channel,
outputTextEdit);
}
else if (source->hasFormat("image/gif"))
{
uploadImageToNuuls({source->data("image/gif"), "gif"}, channel,
outputTextEdit);
}
else if (source->hasUrls())
{
// This path gets chosen when files are copied from a file manager, like explorer.exe, caja.
// Each entry in source->urls() is a QUrl pointing to a file that was copied.
for (const QUrl &path : source->urls())
{
QString localPath = path.toLocalFile();
if (!getImageFileFormat(localPath).isEmpty())
{
channel->addMessage(makeSystemMessage(
QString("Uploading image: %1").arg(localPath)));
QImage img = QImage(localPath);
if (img.isNull())
{
channel->addMessage(
makeSystemMessage(QString("Couldn't load image :(")));
isUploading = false;
return;
}
boost::optional<QByteArray> imageData = convertToPng(img);
if (imageData)
{
RawImageData data = {imageData.get(), "png"};
uploadQueue.push(data);
}
else
{
channel->addMessage(makeSystemMessage(
QString("Cannot upload file: %1, Couldn't convert "
"image to png.")
.arg(localPath)));
}
}
else if (localPath.endsWith(".gif"))
{
channel->addMessage(makeSystemMessage(
QString("Uploading GIF: %1").arg(localPath)));
QFile file(localPath);
bool isOkay = file.open(QIODevice::ReadOnly);
if (!isOkay)
{
channel->addMessage(
makeSystemMessage(QString("Failed to open file. :(")));
isUploading = false;
return;
}
RawImageData data = {file.readAll(), "gif"};
uploadQueue.push(data);
file.close();
// file.readAll() => might be a bit big but it /should/ work
}
else
{
channel->addMessage(makeSystemMessage(
QString("Cannot upload file: %1, not an image")
.arg(localPath)));
isUploading = false;
}
}
if (!uploadQueue.empty())
{
uploadImageToNuuls(uploadQueue.front(), channel, outputTextEdit);
uploadQueue.pop();
}
}
else
{ // not PNG, try loading it into QImage and save it to a PNG.
QImage image = qvariant_cast<QImage>(source->imageData());
boost::optional<QByteArray> imageData = convertToPng(image);
if (imageData)
{
uploadImageToNuuls({imageData.get(), "png"}, channel,
outputTextEdit);
}
else
{
channel->addMessage(makeSystemMessage(
QString("Cannot upload file, failed to convert to png.")));
isUploading = false;
}
}
}
} // namespace chatterino
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/profiling/memory/bookkeeping.h"
#include "test/gtest_and_gmock.h"
namespace perfetto {
namespace profiling {
namespace {
using ::testing::AnyOf;
using ::testing::Eq;
std::vector<FrameData> stack() {
std::vector<FrameData> res;
unwindstack::FrameData data{};
data.function_name = "fun1";
data.map_name = "map1";
res.emplace_back(std::move(data), "dummy_buildid");
data = {};
data.function_name = "fun2";
data.map_name = "map2";
res.emplace_back(std::move(data), "dummy_buildid");
return res;
}
std::vector<FrameData> stack2() {
std::vector<FrameData> res;
unwindstack::FrameData data{};
data.function_name = "fun1";
data.map_name = "map1";
res.emplace_back(std::move(data), "dummy_buildid");
data = {};
data.function_name = "fun3";
data.map_name = "map3";
res.emplace_back(std::move(data), "dummy_buildid");
return res;
}
TEST(BookkeepingTest, Basic) {
uint64_t sequence_number = 1;
GlobalCallstackTrie c;
HeapTracker hd(&c, false);
hd.RecordMalloc(stack(), 1, 5, 5, sequence_number, 100 * sequence_number);
sequence_number++;
hd.RecordMalloc(stack2(), 2, 2, 2, sequence_number, 100 * sequence_number);
sequence_number++;
ASSERT_EQ(hd.GetSizeForTesting(stack()), 5u);
ASSERT_EQ(hd.GetSizeForTesting(stack2()), 2u);
ASSERT_EQ(hd.GetTimestampForTesting(), 100 * (sequence_number - 1));
hd.RecordFree(2, sequence_number, 100 * sequence_number);
sequence_number++;
ASSERT_EQ(hd.GetSizeForTesting(stack()), 5u);
ASSERT_EQ(hd.GetSizeForTesting(stack2()), 0u);
ASSERT_EQ(hd.GetTimestampForTesting(), 100 * (sequence_number - 1));
hd.RecordFree(1, sequence_number, 100 * sequence_number);
sequence_number++;
ASSERT_EQ(hd.GetSizeForTesting(stack()), 0u);
ASSERT_EQ(hd.GetSizeForTesting(stack2()), 0u);
ASSERT_EQ(hd.GetTimestampForTesting(), 100 * (sequence_number - 1));
}
TEST(BookkeepingTest, Max) {
uint64_t sequence_number = 1;
GlobalCallstackTrie c;
HeapTracker hd(&c, true);
hd.RecordMalloc(stack(), 1, 5, 5, sequence_number, 100 * sequence_number);
sequence_number++;
hd.RecordMalloc(stack2(), 2, 2, 2, sequence_number, 100 * sequence_number);
sequence_number++;
hd.RecordFree(2, sequence_number, 100 * sequence_number);
sequence_number++;
hd.RecordFree(1, sequence_number, 100 * sequence_number);
sequence_number++;
ASSERT_EQ(hd.max_timestamp(), 200u);
ASSERT_EQ(hd.GetMaxForTesting(stack()), 5u);
ASSERT_EQ(hd.GetMaxForTesting(stack2()), 2u);
}
TEST(BookkeepingTest, TwoHeapTrackers) {
uint64_t sequence_number = 1;
GlobalCallstackTrie c;
HeapTracker hd(&c, false);
{
HeapTracker hd2(&c, false);
hd.RecordMalloc(stack(), 1, 5, 5, sequence_number, 100 * sequence_number);
hd2.RecordMalloc(stack(), 2, 2, 2, sequence_number, 100 * sequence_number);
sequence_number++;
ASSERT_EQ(hd2.GetSizeForTesting(stack()), 2u);
ASSERT_EQ(hd.GetSizeForTesting(stack()), 5u);
ASSERT_EQ(hd.GetTimestampForTesting(), 100 * (sequence_number - 1));
}
ASSERT_EQ(hd.GetSizeForTesting(stack()), 5u);
}
TEST(BookkeepingTest, ReplaceAlloc) {
uint64_t sequence_number = 1;
GlobalCallstackTrie c;
HeapTracker hd(&c, false);
hd.RecordMalloc(stack(), 1, 5, 5, sequence_number, 100 * sequence_number);
sequence_number++;
hd.RecordMalloc(stack2(), 1, 2, 2, sequence_number, 100 * sequence_number);
sequence_number++;
EXPECT_EQ(hd.GetSizeForTesting(stack()), 0u);
EXPECT_EQ(hd.GetSizeForTesting(stack2()), 2u);
ASSERT_EQ(hd.GetTimestampForTesting(), 100 * (sequence_number - 1));
}
TEST(BookkeepingTest, OutOfOrder) {
GlobalCallstackTrie c;
HeapTracker hd(&c, false);
hd.RecordMalloc(stack(), 1, 5, 5, 2, 2);
hd.RecordMalloc(stack2(), 1, 2, 2, 1, 1);
EXPECT_EQ(hd.GetSizeForTesting(stack()), 5u);
EXPECT_EQ(hd.GetSizeForTesting(stack2()), 0u);
}
TEST(BookkeepingTest, ManyAllocations) {
GlobalCallstackTrie c;
HeapTracker hd(&c, false);
std::vector<std::pair<uint64_t, uint64_t>> batch_frees;
for (uint64_t sequence_number = 1; sequence_number < 1000;) {
if (batch_frees.size() > 10) {
for (const auto& p : batch_frees)
hd.RecordFree(p.first, p.second, 100 * p.second);
batch_frees.clear();
}
uint64_t addr = sequence_number;
hd.RecordMalloc(stack(), addr, 5, 5, sequence_number, sequence_number);
sequence_number++;
batch_frees.emplace_back(addr, sequence_number++);
ASSERT_THAT(hd.GetSizeForTesting(stack()), AnyOf(Eq(0u), Eq(5u)));
}
}
TEST(BookkeepingTest, ArbitraryOrder) {
std::vector<FrameData> s = stack();
std::vector<FrameData> s2 = stack2();
enum OperationType { kAlloc, kFree, kDump };
struct Operation {
uint64_t sequence_number;
OperationType type;
uint64_t address;
uint64_t bytes; // 0 for free
const std::vector<FrameData>* stack; // nullptr for free
// For std::next_permutation.
bool operator<(const Operation& other) const {
return sequence_number < other.sequence_number;
}
} operations[] = {
{1, kAlloc, 1, 5, &s}, //
{2, kAlloc, 1, 10, &s2}, //
{3, kFree, 1, 0, nullptr}, //
{4, kFree, 2, 0, nullptr}, //
{5, kFree, 3, 0, nullptr}, //
{6, kAlloc, 3, 2, &s}, //
{7, kAlloc, 4, 3, &s2}, //
{0, kDump, 0, 0, nullptr}, //
};
uint64_t s_size = 2;
uint64_t s2_size = 3;
do {
GlobalCallstackTrie c;
HeapTracker hd(&c, false);
for (auto it = std::begin(operations); it != std::end(operations); ++it) {
const Operation& operation = *it;
if (operation.type == OperationType::kFree) {
hd.RecordFree(operation.address, operation.sequence_number,
100 * operation.sequence_number);
} else if (operation.type == OperationType::kAlloc) {
hd.RecordMalloc(*operation.stack, operation.address, operation.bytes,
operation.bytes, operation.sequence_number,
100 * operation.sequence_number);
} else {
hd.GetCallstackAllocations(
[](const HeapTracker::CallstackAllocations&) {});
}
}
ASSERT_EQ(hd.GetSizeForTesting(s), s_size);
ASSERT_EQ(hd.GetSizeForTesting(s2), s2_size);
} while (std::next_permutation(std::begin(operations), std::end(operations)));
}
} // namespace
} // namespace profiling
} // namespace perfetto
<commit_msg>Add bookkeeping test for empty callstack. am: debe648a37<commit_after>/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/profiling/memory/bookkeeping.h"
#include "test/gtest_and_gmock.h"
namespace perfetto {
namespace profiling {
namespace {
using ::testing::AnyOf;
using ::testing::Eq;
std::vector<FrameData> stack() {
std::vector<FrameData> res;
unwindstack::FrameData data{};
data.function_name = "fun1";
data.map_name = "map1";
res.emplace_back(std::move(data), "dummy_buildid");
data = {};
data.function_name = "fun2";
data.map_name = "map2";
res.emplace_back(std::move(data), "dummy_buildid");
return res;
}
std::vector<FrameData> stack2() {
std::vector<FrameData> res;
unwindstack::FrameData data{};
data.function_name = "fun1";
data.map_name = "map1";
res.emplace_back(std::move(data), "dummy_buildid");
data = {};
data.function_name = "fun3";
data.map_name = "map3";
res.emplace_back(std::move(data), "dummy_buildid");
return res;
}
TEST(BookkeepingTest, EmptyStack) {
uint64_t sequence_number = 1;
GlobalCallstackTrie c;
HeapTracker hd(&c, false);
hd.RecordMalloc({}, 0x1, 5, 5, sequence_number, 100 * sequence_number);
sequence_number++;
hd.RecordFree(0x1, sequence_number, 100 * sequence_number);
hd.GetCallstackAllocations([](const HeapTracker::CallstackAllocations&) {});
}
TEST(BookkeepingTest, Basic) {
uint64_t sequence_number = 1;
GlobalCallstackTrie c;
HeapTracker hd(&c, false);
hd.RecordMalloc(stack(), 0x1, 5, 5, sequence_number, 100 * sequence_number);
sequence_number++;
hd.RecordMalloc(stack2(), 0x2, 2, 2, sequence_number, 100 * sequence_number);
sequence_number++;
ASSERT_EQ(hd.GetSizeForTesting(stack()), 5u);
ASSERT_EQ(hd.GetSizeForTesting(stack2()), 2u);
ASSERT_EQ(hd.GetTimestampForTesting(), 100 * (sequence_number - 1));
hd.RecordFree(0x2, sequence_number, 100 * sequence_number);
sequence_number++;
ASSERT_EQ(hd.GetSizeForTesting(stack()), 5u);
ASSERT_EQ(hd.GetSizeForTesting(stack2()), 0u);
ASSERT_EQ(hd.GetTimestampForTesting(), 100 * (sequence_number - 1));
hd.RecordFree(0x1, sequence_number, 100 * sequence_number);
sequence_number++;
ASSERT_EQ(hd.GetSizeForTesting(stack()), 0u);
ASSERT_EQ(hd.GetSizeForTesting(stack2()), 0u);
ASSERT_EQ(hd.GetTimestampForTesting(), 100 * (sequence_number - 1));
}
TEST(BookkeepingTest, Max) {
uint64_t sequence_number = 1;
GlobalCallstackTrie c;
HeapTracker hd(&c, true);
hd.RecordMalloc(stack(), 0x1, 5, 5, sequence_number, 100 * sequence_number);
sequence_number++;
hd.RecordMalloc(stack2(), 0x2, 2, 2, sequence_number, 100 * sequence_number);
sequence_number++;
hd.RecordFree(0x2, sequence_number, 100 * sequence_number);
sequence_number++;
hd.RecordFree(0x1, sequence_number, 100 * sequence_number);
sequence_number++;
ASSERT_EQ(hd.max_timestamp(), 200u);
ASSERT_EQ(hd.GetMaxForTesting(stack()), 5u);
ASSERT_EQ(hd.GetMaxForTesting(stack2()), 2u);
}
TEST(BookkeepingTest, TwoHeapTrackers) {
uint64_t sequence_number = 1;
GlobalCallstackTrie c;
HeapTracker hd(&c, false);
{
HeapTracker hd2(&c, false);
hd.RecordMalloc(stack(), 0x1, 5, 5, sequence_number, 100 * sequence_number);
hd2.RecordMalloc(stack(), 0x2, 2, 2, sequence_number,
100 * sequence_number);
sequence_number++;
ASSERT_EQ(hd2.GetSizeForTesting(stack()), 2u);
ASSERT_EQ(hd.GetSizeForTesting(stack()), 5u);
ASSERT_EQ(hd.GetTimestampForTesting(), 100 * (sequence_number - 1));
}
ASSERT_EQ(hd.GetSizeForTesting(stack()), 5u);
}
TEST(BookkeepingTest, ReplaceAlloc) {
uint64_t sequence_number = 1;
GlobalCallstackTrie c;
HeapTracker hd(&c, false);
hd.RecordMalloc(stack(), 0x1, 5, 5, sequence_number, 100 * sequence_number);
sequence_number++;
hd.RecordMalloc(stack2(), 0x1, 2, 2, sequence_number, 100 * sequence_number);
sequence_number++;
EXPECT_EQ(hd.GetSizeForTesting(stack()), 0u);
EXPECT_EQ(hd.GetSizeForTesting(stack2()), 2u);
ASSERT_EQ(hd.GetTimestampForTesting(), 100 * (sequence_number - 1));
}
TEST(BookkeepingTest, OutOfOrder) {
GlobalCallstackTrie c;
HeapTracker hd(&c, false);
hd.RecordMalloc(stack(), 0x1, 5, 5, 2, 2);
hd.RecordMalloc(stack2(), 0x1, 2, 2, 1, 1);
EXPECT_EQ(hd.GetSizeForTesting(stack()), 5u);
EXPECT_EQ(hd.GetSizeForTesting(stack2()), 0u);
}
TEST(BookkeepingTest, ManyAllocations) {
GlobalCallstackTrie c;
HeapTracker hd(&c, false);
std::vector<std::pair<uint64_t, uint64_t>> batch_frees;
for (uint64_t sequence_number = 1; sequence_number < 1000;) {
if (batch_frees.size() > 10) {
for (const auto& p : batch_frees)
hd.RecordFree(p.first, p.second, 100 * p.second);
batch_frees.clear();
}
uint64_t addr = sequence_number;
hd.RecordMalloc(stack(), addr, 5, 5, sequence_number, sequence_number);
sequence_number++;
batch_frees.emplace_back(addr, sequence_number++);
ASSERT_THAT(hd.GetSizeForTesting(stack()), AnyOf(Eq(0u), Eq(5u)));
}
}
TEST(BookkeepingTest, ArbitraryOrder) {
std::vector<FrameData> s = stack();
std::vector<FrameData> s2 = stack2();
enum OperationType { kAlloc, kFree, kDump };
struct Operation {
uint64_t sequence_number;
OperationType type;
uint64_t address;
uint64_t bytes; // 0 for free
const std::vector<FrameData>* stack; // nullptr for free
// For std::next_permutation.
bool operator<(const Operation& other) const {
return sequence_number < other.sequence_number;
}
} operations[] = {
{1, kAlloc, 0x1, 5, &s}, //
{2, kAlloc, 0x1, 10, &s2}, //
{3, kFree, 0x01, 0, nullptr}, //
{4, kFree, 0x02, 0, nullptr}, //
{5, kFree, 0x03, 0, nullptr}, //
{6, kAlloc, 0x3, 2, &s}, //
{7, kAlloc, 0x4, 3, &s2}, //
{0, kDump, 0x00, 0, nullptr}, //
};
uint64_t s_size = 2;
uint64_t s2_size = 3;
do {
GlobalCallstackTrie c;
HeapTracker hd(&c, false);
for (auto it = std::begin(operations); it != std::end(operations); ++it) {
const Operation& operation = *it;
if (operation.type == OperationType::kFree) {
hd.RecordFree(operation.address, operation.sequence_number,
100 * operation.sequence_number);
} else if (operation.type == OperationType::kAlloc) {
hd.RecordMalloc(*operation.stack, operation.address, operation.bytes,
operation.bytes, operation.sequence_number,
100 * operation.sequence_number);
} else {
hd.GetCallstackAllocations(
[](const HeapTracker::CallstackAllocations&) {});
}
}
ASSERT_EQ(hd.GetSizeForTesting(s), s_size);
ASSERT_EQ(hd.GetSizeForTesting(s2), s2_size);
} while (std::next_permutation(std::begin(operations), std::end(operations)));
}
} // namespace
} // namespace profiling
} // namespace perfetto
<|endoftext|> |
<commit_before>/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <string.h>
#include <node.h>
#include <nan.h>
#include "grpc/grpc.h"
#include "grpc/byte_buffer_reader.h"
#include "grpc/support/slice.h"
#include "byte_buffer.h"
namespace grpc {
namespace node {
using v8::Context;
using v8::Function;
using v8::Handle;
using v8::Object;
using v8::Number;
using v8::Value;
grpc_byte_buffer *BufferToByteBuffer(Handle<Value> buffer) {
NanScope();
int length = ::node::Buffer::Length(buffer);
char *data = ::node::Buffer::Data(buffer);
gpr_slice slice = gpr_slice_malloc(length);
memcpy(GPR_SLICE_START_PTR(slice), data, length);
grpc_byte_buffer *byte_buffer(grpc_raw_byte_buffer_create(&slice, 1));
gpr_slice_unref(slice);
return byte_buffer;
}
Handle<Value> ByteBufferToBuffer(grpc_byte_buffer *buffer) {
NanEscapableScope();
if (buffer == NULL) {
return NanEscapeScope(NanNull());
}
size_t length = grpc_byte_buffer_length(buffer);
char *result = reinterpret_cast<char *>(calloc(length, sizeof(char)));
size_t offset = 0;
grpc_byte_buffer_reader reader;
grpc_byte_buffer_reader_init(&reader, buffer);
gpr_slice next;
while (grpc_byte_buffer_reader_next(&reader, &next) != 0) {
memcpy(result + offset, GPR_SLICE_START_PTR(next), GPR_SLICE_LENGTH(next));
offset += GPR_SLICE_LENGTH(next);
}
return NanEscapeScope(MakeFastBuffer(NanNewBufferHandle(result, length)));
}
Handle<Value> MakeFastBuffer(Handle<Value> slowBuffer) {
NanEscapableScope();
Handle<Object> globalObj = NanGetCurrentContext()->Global();
Handle<Function> bufferConstructor = Handle<Function>::Cast(
globalObj->Get(NanNew("Buffer")));
Handle<Value> consArgs[3] = {
slowBuffer,
NanNew<Number>(::node::Buffer::Length(slowBuffer)),
NanNew<Number>(0)
};
Handle<Object> fastBuffer = bufferConstructor->NewInstance(3, consArgs);
return NanEscapeScope(fastBuffer);
}
} // namespace node
} // namespace grpc
<commit_msg>Fixed memory leak in Buffer construction<commit_after>/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <string.h>
#include <node.h>
#include <nan.h>
#include "grpc/grpc.h"
#include "grpc/byte_buffer_reader.h"
#include "grpc/support/slice.h"
#include "byte_buffer.h"
namespace grpc {
namespace node {
using v8::Context;
using v8::Function;
using v8::Handle;
using v8::Object;
using v8::Number;
using v8::Value;
grpc_byte_buffer *BufferToByteBuffer(Handle<Value> buffer) {
NanScope();
int length = ::node::Buffer::Length(buffer);
char *data = ::node::Buffer::Data(buffer);
gpr_slice slice = gpr_slice_malloc(length);
memcpy(GPR_SLICE_START_PTR(slice), data, length);
grpc_byte_buffer *byte_buffer(grpc_raw_byte_buffer_create(&slice, 1));
gpr_slice_unref(slice);
return byte_buffer;
}
Handle<Value> ByteBufferToBuffer(grpc_byte_buffer *buffer) {
NanEscapableScope();
if (buffer == NULL) {
return NanEscapeScope(NanNull());
}
size_t length = grpc_byte_buffer_length(buffer);
char *result = reinterpret_cast<char *>(calloc(length, sizeof(char)));
size_t offset = 0;
grpc_byte_buffer_reader reader;
grpc_byte_buffer_reader_init(&reader, buffer);
gpr_slice next;
while (grpc_byte_buffer_reader_next(&reader, &next) != 0) {
memcpy(result + offset, GPR_SLICE_START_PTR(next), GPR_SLICE_LENGTH(next));
offset += GPR_SLICE_LENGTH(next);
}
return NanEscapeScope(MakeFastBuffer(NanBufferUse(result, length)));
}
Handle<Value> MakeFastBuffer(Handle<Value> slowBuffer) {
NanEscapableScope();
Handle<Object> globalObj = NanGetCurrentContext()->Global();
Handle<Function> bufferConstructor = Handle<Function>::Cast(
globalObj->Get(NanNew("Buffer")));
Handle<Value> consArgs[3] = {
slowBuffer,
NanNew<Number>(::node::Buffer::Length(slowBuffer)),
NanNew<Number>(0)
};
Handle<Object> fastBuffer = bufferConstructor->NewInstance(3, consArgs);
return NanEscapeScope(fastBuffer);
}
} // namespace node
} // namespace grpc
<|endoftext|> |
<commit_before>/*
* examples/blassolve.C
*
* Copyright (C) J-G Dumas
* ========LICENCE========
* This file is part of the library LinBox.
*
* LinBox 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
* ========LICENCE========
*/
#include <iostream>
#include "linbox/matrix/dense-matrix.h"
#include "linbox/solutions/solve.h"
#include "linbox/util/matrix-stream.h"
#include "linbox/solutions/methods.h"
using namespace LinBox;
typedef Givaro::ZRing<Givaro::Integer> Ints;
typedef DenseVector<Ints> ZVector;
int main (int argc, char **argv) {
// Usage
if (argc < 2 || argc > 4) {
std::cerr << "Usage: solve <matrix-file-in-supported-format> [<dense-vector-file>]" << std::endl;
return 0;
}
// File
std::ifstream input (argv[1]);
if (!input) { std::cerr << "Error opening matrix file " << argv[1] << std::endl; return -1; }
std::ifstream invect;
bool createB = false;
if (argc == 2) {
createB = true;
}
if (argc == 3) {
invect.open (argv[2], std::ifstream::in);
if (!invect) {
createB = true;
} else {
createB = false;
}
}
// Read Integral matrix from File
Ints ZZ;
MatrixStream< Ints > ms( ZZ, input );
DenseMatrix<Ints> A (ms);
Ints::Element d;
std::cout << "A is " << A.rowdim() << " by " << A.coldim() << std::endl;
{
// Print Matrix
// Matrix Market
// std::cout << "A is " << A << std::endl;
// Maple
A.write(std::cout << "Pretty A is ", Tag::FileFormat::Maple) << std::endl;
}
// Vectors
ZVector X(ZZ, A.coldim()),B(ZZ, A.rowdim());
if (createB) {
std::cerr << "Creating a random {-1,1} vector " << std::endl;
srand48( BaseTimer::seed() );
for(ZVector::iterator it=B.begin();
it != B.end(); ++it)
if (drand48() <0.5)
*it = -1;
else
*it = 1;
} else {
for(ZVector::iterator it=B.begin();
it != B.end(); ++it)
invect >> *it;
}
{
// Print RHS
std::cout << "B is [";
for(auto it:B) ZZ.write(std::cout, it) << " ";
std::cout << "]" << std::endl;
}
std::cout << "B is " << B.size() << "x1" << std::endl;
Timer chrono;
// BlasElimination
Method::BlasElimination M;
//M.singular(Specifier::NONSINGULAR);
chrono.start();
solve (X, d, A, B, M);
chrono.stop();
std::cout << "CPU time (seconds): " << chrono.usertime() << std::endl;
{
// Solution size
std::cout<<"Reduced solution: \n";
size_t maxbits=0;
for (size_t i=0;i<A.coldim();++i){
maxbits=(maxbits > X[i].bitsize() ? maxbits: X[i].bitsize());
}
std::cout<<" numerators of size "<<maxbits<<" bits" << std::endl
<<" denominators hold over "<<d.bitsize()<<" bits\n";
}
{
// Check Solution
VectorDomain<Ints> VD(ZZ);
MatrixDomain<Ints> MD(ZZ);
ZVector LHS(ZZ, A.rowdim()), RHS(ZZ, B);
// check that Ax = d.b
MD.vectorMul(LHS, A, X);
VD.mulin(RHS, d);
if (VD.areEqual(LHS, RHS))
std::cout << "Ax=b : Yes" << std::endl;
else
std::cout << "Ax=b : No" << std::endl;
}
{
// Print Solution
std::cout << "(BlasElimination) Solution is [";
for(auto it:X) ZZ.write(std::cout, it) << " ";
std::cout << "] / ";
ZZ.write(std::cout, d)<< std::endl;
}
return 0;
}
// Local Variables:
// mode: C++
// tab-width: 4
// indent-tabs-mode: nil
// c-basic-offset: 4
// End:
// vim:sts=4:sw=4:ts=4:et:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
<commit_msg>test for zero denominator<commit_after>/*
* examples/blassolve.C
*
* Copyright (C) J-G Dumas
* ========LICENCE========
* This file is part of the library LinBox.
*
* LinBox 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
* ========LICENCE========
*/
#include <iostream>
#include "linbox/matrix/dense-matrix.h"
#include "linbox/solutions/solve.h"
#include "linbox/util/matrix-stream.h"
#include "linbox/solutions/methods.h"
using namespace LinBox;
typedef Givaro::ZRing<Givaro::Integer> Ints;
typedef DenseVector<Ints> ZVector;
int main (int argc, char **argv) {
// Usage
if (argc < 2 || argc > 4) {
std::cerr << "Usage: solve <matrix-file-in-supported-format> [<dense-vector-file>]" << std::endl;
return 0;
}
// File
std::ifstream input (argv[1]);
if (!input) { std::cerr << "Error opening matrix file " << argv[1] << std::endl; return -1; }
std::ifstream invect;
bool createB = false;
if (argc == 2) {
createB = true;
}
if (argc == 3) {
invect.open (argv[2], std::ifstream::in);
if (!invect) {
createB = true;
} else {
createB = false;
}
}
// Read Integral matrix from File
Ints ZZ;
MatrixStream< Ints > ms( ZZ, input );
DenseMatrix<Ints> A (ms);
Ints::Element d;
std::cout << "A is " << A.rowdim() << " by " << A.coldim() << std::endl;
{
// Print Matrix
// Matrix Market
// std::cout << "A is " << A << std::endl;
// Maple
A.write(std::cout << "Pretty A is ", Tag::FileFormat::Maple) << std::endl;
}
// Vectors
ZVector X(ZZ, A.coldim()),B(ZZ, A.rowdim());
if (createB) {
std::cerr << "Creating a random {-1,1} vector " << std::endl;
srand48( BaseTimer::seed() );
for(ZVector::iterator it=B.begin();
it != B.end(); ++it)
if (drand48() <0.5)
*it = -1;
else
*it = 1;
} else {
for(ZVector::iterator it=B.begin();
it != B.end(); ++it)
invect >> *it;
}
{
// Print RHS
std::cout << "B is [";
for(auto it:B) ZZ.write(std::cout, it) << " ";
std::cout << "]" << std::endl;
}
std::cout << "B is " << B.size() << "x1" << std::endl;
Timer chrono;
// BlasElimination
Method::BlasElimination M;
//M.singular(Specifier::NONSINGULAR);
chrono.start();
solve (X, d, A, B, M);
chrono.stop();
std::cout << "CPU time (seconds): " << chrono.usertime() << std::endl;
{
// Solution size
std::cout<<"Reduced solution: \n";
size_t maxbits=0;
for (size_t i=0;i<A.coldim();++i){
maxbits=(maxbits > X[i].bitsize() ? maxbits: X[i].bitsize());
}
std::cout<<" numerators of size "<<maxbits<<" bits" << std::endl
<<" denominators hold over "<<d.bitsize()<<" bits\n";
}
{
// Check Solution
if (ZZ.isZero(d))
std::cout << "**** ERROR ****\n**** Zero denominator" << std::endl;
else {
VectorDomain<Ints> VD(ZZ);
MatrixDomain<Ints> MD(ZZ);
ZVector LHS(ZZ, A.rowdim()), RHS(ZZ, B);
// check that Ax = d.b
MD.vectorMul(LHS, A, X);
VD.mulin(RHS, d);
if (VD.areEqual(LHS, RHS))
std::cout << "Ax=b : Yes" << std::endl;
else
std::cout << "Ax=b : No" << std::endl;
}
}
{
// Print Solution
std::cout << "(BlasElimination) Solution is [";
for(auto it:X) ZZ.write(std::cout, it) << " ";
std::cout << "] / ";
ZZ.write(std::cout, d)<< std::endl;
}
return 0;
}
// Local Variables:
// mode: C++
// tab-width: 4
// indent-tabs-mode: nil
// c-basic-offset: 4
// End:
// vim:sts=4:sw=4:ts=4:et:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifndef WIN32
#include <grp.h>
#endif
#include <signal.h>
#if !defined(__FreeBSD__) && !defined(WIN32)
#include <uuid/uuid.h>
#endif
#ifdef WIN32
#include <WinSock2.h>
#endif
#include <ctime>
#include <sstream>
#include <boost/algorithm/string/trim.hpp>
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <osquery/core.h>
#include <osquery/database.h>
#include <osquery/filesystem.h>
#include <osquery/logger.h>
#include <osquery/sql.h>
#include <osquery/system.h>
#include "osquery/core/process.h"
#include "osquery/core/utils.h"
namespace fs = boost::filesystem;
namespace osquery {
/// The path to the pidfile for osqueryd
CLI_FLAG(string,
pidfile,
OSQUERY_DB_HOME "/osqueryd.pidfile",
"Path to the daemon pidfile mutex");
/// Should the daemon force unload previously-running osqueryd daemons.
CLI_FLAG(bool,
force,
false,
"Force osqueryd to kill previously-running daemons");
FLAG(string,
host_identifier,
"hostname",
"Field used to identify the host running osquery (hostname, uuid)");
FLAG(bool, utc, true, "Convert all UNIX times to UTC");
#ifdef WIN32
struct tm* gmtime_r(time_t* t, struct tm* result) {
_gmtime64_s(result, t);
return result;
}
struct tm* localtime_r(time_t* t, struct tm* result) {
_localtime64_s(result, t);
return result;
}
#endif
std::string getHostname() {
#ifdef WIN32
long size = 256;
#else
static long max_hostname = sysconf(_SC_HOST_NAME_MAX);
long size = (max_hostname > 255) ? max_hostname + 1 : 256;
#endif
char* hostname = (char*)malloc(size);
std::string hostname_string;
if (hostname != nullptr) {
memset((void*)hostname, 0, size);
gethostname(hostname, size - 1);
hostname_string = std::string(hostname);
free(hostname);
}
boost::algorithm::trim(hostname_string);
return hostname_string;
}
std::string generateNewUUID() {
boost::uuids::uuid uuid = boost::uuids::random_generator()();
return boost::uuids::to_string(uuid);
}
std::string generateHostUUID() {
#ifdef __APPLE__
// Use the hardware UUID available on OSX to identify this machine
uuid_t id;
// wait at most 5 seconds for gethostuuid to return
const timespec wait = {5, 0};
int result = gethostuuid(id, &wait);
if (result == 0) {
char out[128] = {0};
uuid_unparse(id, out);
std::string uuid_string = std::string(out);
boost::algorithm::trim(uuid_string);
return uuid_string;
} else {
// Unable to get the hardware UUID, just return a new UUID
return generateNewUUID();
}
#else
return generateNewUUID();
#endif
}
Status getHostUUID(std::string& ident) {
// Lookup the host identifier (UUID) previously generated and stored.
auto status = getDatabaseValue(kPersistentSettings, "hostIdentifier", ident);
if (ident.size() == 0) {
// There was no UUID stored in the database, generate one and store it.
ident = osquery::generateHostUUID();
VLOG(1) << "Using UUID " << ident << " as host identifier";
return setDatabaseValue(kPersistentSettings, "hostIdentifier", ident);
}
return status;
}
std::string getHostIdentifier() {
if (FLAGS_host_identifier != "uuid") {
// use the hostname as the default machine identifier
return osquery::getHostname();
}
// Generate a identifier/UUID for this application launch, and persist.
static std::string ident;
if (ident.size() == 0) {
getHostUUID(ident);
}
return ident;
}
std::string getAsciiTime() {
auto result = std::time(nullptr);
struct tm now;
gmtime_r(&result, &now);
auto time_str = platformAsctime(&now);
boost::algorithm::trim(time_str);
return time_str + " UTC";
}
size_t getUnixTime() {
return std::time(nullptr);
}
Status checkStalePid(const std::string& content) {
int pid;
try {
pid = boost::lexical_cast<int>(content);
} catch (const boost::bad_lexical_cast& /* e */) {
if (FLAGS_force) {
return Status(0, "Force loading and not parsing pidfile");
} else {
return Status(1, "Could not parse pidfile");
}
}
PlatformProcess target(pid);
int status = 0;
// The pid is running, check if it is an osqueryd process by name.
std::stringstream query_text;
query_text << "SELECT name FROM processes WHERE pid = " << pid
<< " AND name LIKE 'osqueryd%';";
auto q = SQL(query_text.str());
if (!q.ok()) {
return Status(1, "Error querying processes: " + q.getMessageString());
}
if (q.rows().size() > 0) {
// If the process really is osqueryd, return an "error" status.
if (FLAGS_force) {
// The caller may choose to abort the existing daemon with --force.
// Do not use SIGQUIT as it will cause a crash on OS X.
status = target.kill() ? 0 : -1;
sleepFor(1000);
return Status(status, "Tried to force remove the existing osqueryd");
}
return Status(1, "osqueryd (" + content + ") is already running");
} else {
VLOG(1) << "Found stale process for osqueryd (" << content
<< ") removing pidfile";
}
return Status(0, "OK");
}
Status createPidFile() {
// check if pidfile exists
auto pidfile_path = fs::path(FLAGS_pidfile).make_preferred();
if (pathExists(pidfile_path).ok()) {
// if it exists, check if that pid is running.
std::string content;
auto read_status = readFile(pidfile_path, content, true);
if (!read_status.ok()) {
return Status(1, "Could not read pidfile: " + read_status.toString());
}
auto stale_status = checkStalePid(content);
if (!stale_status.ok()) {
return stale_status;
}
}
// Now the pidfile is either the wrong pid or the pid is not running.
try {
boost::filesystem::remove(pidfile_path);
} catch (const boost::filesystem::filesystem_error& /* e */) {
// Unable to remove old pidfile.
LOG(WARNING) << "Unable to remove the osqueryd pidfile";
}
// If no pidfile exists or the existing pid was stale, write, log, and run.
auto pid = boost::lexical_cast<std::string>(
PlatformProcess::getCurrentProcess()->pid());
VLOG(1) << "Writing osqueryd pid (" << pid << ") to "
<< pidfile_path.string();
auto status = writeTextFile(pidfile_path, pid, 0644);
return status;
}
#ifndef WIN32
#if defined(__linux__)
#include <sys/fsuid.h>
static inline int _fs_set_group(gid_t gid) {
return setfsgid(gid) * 0;
}
static inline int _fs_set_user(uid_t uid) {
return setfsuid(uid) * 0;
}
#else
static inline int _fs_set_group(gid_t gid) {
return setegid(gid);
}
static inline int _fs_set_user(uid_t uid) {
return seteuid(uid);
}
#endif
bool DropPrivileges::dropToParent(const fs::path& path) {
uid_t to_user{0};
gid_t to_group{0};
// Open the parent path of the requested file to operate on.
int pfd = open(path.parent_path().string().c_str(), O_RDONLY | O_NONBLOCK);
if (pfd >= 0) {
struct stat file;
if (geteuid() == 0 && fstat(pfd, &file) >= 0 &&
(file.st_uid != 0 || file.st_gid != 0)) {
// A drop is required if this process is executed as a superuser and
// the folder can be altered by non-super users.
to_user = file.st_uid;
to_group = file.st_gid;
}
close(pfd);
}
if (to_user == 0 && to_group == 0) {
// No drop required.
return true;
} else if (dropped() && to_user == to_user_ && to_group == to_group_) {
// They are already dropped to the correct user/group.
return true;
} else if (!dropped()) {
// Privileges should be dropped.
if (_fs_set_group(to_group) != 0) {
return false;
} else if (_fs_set_user(to_user) != 0) {
// Privileges are not dropped and could not be set for the user.
// Restore the group and fail.
(void)_fs_set_group(getgid());
return false;
}
// Privileges are now dropped to the requested user/group.
to_user_ = to_user;
to_group_ = to_group;
dropped_ = true;
fs_drop_ = true;
return true;
}
// Privileges are dropped but not to the requested user/group.
// Proceed with extreme caution.
return false;
}
bool DropPrivileges::dropTo(uid_t uid, gid_t gid) {
if (dropped() && uid == to_user_ && gid == to_group_) {
// Privileges are already dropped to the requested user and group.
return true;
} else if (dropped()) {
return false;
}
/// Drop process groups.
if (original_groups_ != nullptr) {
restoreGroups();
}
group_size_ = getgroups(0, nullptr);
original_groups_ = (gid_t*)malloc(group_size_ * sizeof(gid_t));
group_size_ = getgroups(group_size_, original_groups_);
setgroups(1, &gid);
if (setegid(gid) != 0) {
return false;
} else if (seteuid(uid) != 0) {
(void)setegid(getgid());
return false;
}
// Privileges are now dropped to the requested user/group.
to_user_ = uid;
to_group_ = gid;
dropped_ = true;
return true;
}
void DropPrivileges::restoreGroups() {
setgroups(group_size_, original_groups_);
group_size_ = 0;
free(original_groups_);
original_groups_ = nullptr;
}
DropPrivileges::~DropPrivileges() {
if (dropped_) {
// 1. On Linux/BSD we do not need to differentiate between FS/E since FS
// is set implicitly by seteuid.
// 2. We are elevating privileges, there is no security vulnerability if
// either privilege change fails.
if (fs_drop_) {
(void)_fs_set_user(getuid());
(void)_fs_set_group(getgid());
} else {
(void)seteuid(getuid());
(void)setegid(getgid());
}
dropped_ = false;
}
if (original_groups_ != nullptr) {
restoreGroups();
}
}
#endif
}
<commit_msg>Attempt to query platform UUID on Linux (#2522)<commit_after>/*
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifndef WIN32
#include <grp.h>
#endif
#include <signal.h>
#if !defined(__FreeBSD__) && !defined(WIN32)
#include <uuid/uuid.h>
#endif
#ifdef WIN32
#include <WinSock2.h>
#endif
#include <ctime>
#include <sstream>
#include <boost/algorithm/string/trim.hpp>
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <osquery/core.h>
#include <osquery/database.h>
#include <osquery/filesystem.h>
#include <osquery/logger.h>
#include <osquery/sql.h>
#include <osquery/system.h>
#include "osquery/core/process.h"
#include "osquery/core/utils.h"
namespace fs = boost::filesystem;
namespace osquery {
/// The path to the pidfile for osqueryd
CLI_FLAG(string,
pidfile,
OSQUERY_DB_HOME "/osqueryd.pidfile",
"Path to the daemon pidfile mutex");
/// Should the daemon force unload previously-running osqueryd daemons.
CLI_FLAG(bool,
force,
false,
"Force osqueryd to kill previously-running daemons");
FLAG(string,
host_identifier,
"hostname",
"Field used to identify the host running osquery (hostname, uuid)");
FLAG(bool, utc, true, "Convert all UNIX times to UTC");
#ifdef WIN32
struct tm* gmtime_r(time_t* t, struct tm* result) {
_gmtime64_s(result, t);
return result;
}
struct tm* localtime_r(time_t* t, struct tm* result) {
_localtime64_s(result, t);
return result;
}
#endif
std::string getHostname() {
#ifdef WIN32
long size = 256;
#else
static long max_hostname = sysconf(_SC_HOST_NAME_MAX);
long size = (max_hostname > 255) ? max_hostname + 1 : 256;
#endif
char* hostname = (char*)malloc(size);
std::string hostname_string;
if (hostname != nullptr) {
memset((void*)hostname, 0, size);
gethostname(hostname, size - 1);
hostname_string = std::string(hostname);
free(hostname);
}
boost::algorithm::trim(hostname_string);
return hostname_string;
}
std::string generateNewUUID() {
LOG(INFO) << "Cannot retrieve platform UUID: generating an ephemeral UUID";
boost::uuids::uuid uuid = boost::uuids::random_generator()();
return boost::uuids::to_string(uuid);
}
std::string generateHostUUID() {
#ifdef __APPLE__
// Use the hardware UUID available on OSX to identify this machine
uuid_t id;
// wait at most 5 seconds for gethostuuid to return
const timespec wait = {5, 0};
int result = gethostuuid(id, &wait);
if (result == 0) {
char out[128] = {0};
uuid_unparse(id, out);
std::string uuid_string = std::string(out);
boost::algorithm::trim(uuid_string);
return uuid_string;
} else {
// Unable to get the hardware UUID, just return a new UUID
return generateNewUUID();
}
#else
std::string uuid;
if (readFile("/sys/class/dmi/id/product_uuid", uuid)) {
boost::algorithm::trim(uuid);
return uuid;
}
return generateNewUUID();
#endif
}
Status getHostUUID(std::string& ident) {
// Lookup the host identifier (UUID) previously generated and stored.
auto status = getDatabaseValue(kPersistentSettings, "hostIdentifier", ident);
if (ident.size() == 0) {
// There was no UUID stored in the database, generate one and store it.
ident = osquery::generateHostUUID();
VLOG(1) << "Using UUID " << ident << " as host identifier";
return setDatabaseValue(kPersistentSettings, "hostIdentifier", ident);
}
return status;
}
std::string getHostIdentifier() {
if (FLAGS_host_identifier != "uuid") {
// use the hostname as the default machine identifier
return osquery::getHostname();
}
// Generate a identifier/UUID for this application launch, and persist.
static std::string ident;
if (ident.size() == 0) {
getHostUUID(ident);
}
return ident;
}
std::string getAsciiTime() {
auto result = std::time(nullptr);
struct tm now;
gmtime_r(&result, &now);
auto time_str = platformAsctime(&now);
boost::algorithm::trim(time_str);
return time_str + " UTC";
}
size_t getUnixTime() {
return std::time(nullptr);
}
Status checkStalePid(const std::string& content) {
int pid;
try {
pid = boost::lexical_cast<int>(content);
} catch (const boost::bad_lexical_cast& /* e */) {
if (FLAGS_force) {
return Status(0, "Force loading and not parsing pidfile");
} else {
return Status(1, "Could not parse pidfile");
}
}
PlatformProcess target(pid);
int status = 0;
// The pid is running, check if it is an osqueryd process by name.
std::stringstream query_text;
query_text << "SELECT name FROM processes WHERE pid = " << pid
<< " AND name LIKE 'osqueryd%';";
auto q = SQL(query_text.str());
if (!q.ok()) {
return Status(1, "Error querying processes: " + q.getMessageString());
}
if (q.rows().size() > 0) {
// If the process really is osqueryd, return an "error" status.
if (FLAGS_force) {
// The caller may choose to abort the existing daemon with --force.
// Do not use SIGQUIT as it will cause a crash on OS X.
status = target.kill() ? 0 : -1;
sleepFor(1000);
return Status(status, "Tried to force remove the existing osqueryd");
}
return Status(1, "osqueryd (" + content + ") is already running");
} else {
VLOG(1) << "Found stale process for osqueryd (" << content
<< ") removing pidfile";
}
return Status(0, "OK");
}
Status createPidFile() {
// check if pidfile exists
auto pidfile_path = fs::path(FLAGS_pidfile).make_preferred();
if (pathExists(pidfile_path).ok()) {
// if it exists, check if that pid is running.
std::string content;
auto read_status = readFile(pidfile_path, content, true);
if (!read_status.ok()) {
return Status(1, "Could not read pidfile: " + read_status.toString());
}
auto stale_status = checkStalePid(content);
if (!stale_status.ok()) {
return stale_status;
}
}
// Now the pidfile is either the wrong pid or the pid is not running.
try {
boost::filesystem::remove(pidfile_path);
} catch (const boost::filesystem::filesystem_error& /* e */) {
// Unable to remove old pidfile.
LOG(WARNING) << "Unable to remove the osqueryd pidfile";
}
// If no pidfile exists or the existing pid was stale, write, log, and run.
auto pid = boost::lexical_cast<std::string>(
PlatformProcess::getCurrentProcess()->pid());
VLOG(1) << "Writing osqueryd pid (" << pid << ") to "
<< pidfile_path.string();
auto status = writeTextFile(pidfile_path, pid, 0644);
return status;
}
#ifndef WIN32
#if defined(__linux__)
#include <sys/fsuid.h>
static inline int _fs_set_group(gid_t gid) {
return setfsgid(gid) * 0;
}
static inline int _fs_set_user(uid_t uid) {
return setfsuid(uid) * 0;
}
#else
static inline int _fs_set_group(gid_t gid) {
return setegid(gid);
}
static inline int _fs_set_user(uid_t uid) {
return seteuid(uid);
}
#endif
bool DropPrivileges::dropToParent(const fs::path& path) {
uid_t to_user{0};
gid_t to_group{0};
// Open the parent path of the requested file to operate on.
int pfd = open(path.parent_path().string().c_str(), O_RDONLY | O_NONBLOCK);
if (pfd >= 0) {
struct stat file;
if (geteuid() == 0 && fstat(pfd, &file) >= 0 &&
(file.st_uid != 0 || file.st_gid != 0)) {
// A drop is required if this process is executed as a superuser and
// the folder can be altered by non-super users.
to_user = file.st_uid;
to_group = file.st_gid;
}
close(pfd);
}
if (to_user == 0 && to_group == 0) {
// No drop required.
return true;
} else if (dropped() && to_user == to_user_ && to_group == to_group_) {
// They are already dropped to the correct user/group.
return true;
} else if (!dropped()) {
// Privileges should be dropped.
if (_fs_set_group(to_group) != 0) {
return false;
} else if (_fs_set_user(to_user) != 0) {
// Privileges are not dropped and could not be set for the user.
// Restore the group and fail.
(void)_fs_set_group(getgid());
return false;
}
// Privileges are now dropped to the requested user/group.
to_user_ = to_user;
to_group_ = to_group;
dropped_ = true;
fs_drop_ = true;
return true;
}
// Privileges are dropped but not to the requested user/group.
// Proceed with extreme caution.
return false;
}
bool DropPrivileges::dropTo(uid_t uid, gid_t gid) {
if (dropped() && uid == to_user_ && gid == to_group_) {
// Privileges are already dropped to the requested user and group.
return true;
} else if (dropped()) {
return false;
}
/// Drop process groups.
if (original_groups_ != nullptr) {
restoreGroups();
}
group_size_ = getgroups(0, nullptr);
original_groups_ = (gid_t*)malloc(group_size_ * sizeof(gid_t));
group_size_ = getgroups(group_size_, original_groups_);
setgroups(1, &gid);
if (setegid(gid) != 0) {
return false;
} else if (seteuid(uid) != 0) {
(void)setegid(getgid());
return false;
}
// Privileges are now dropped to the requested user/group.
to_user_ = uid;
to_group_ = gid;
dropped_ = true;
return true;
}
void DropPrivileges::restoreGroups() {
setgroups(group_size_, original_groups_);
group_size_ = 0;
free(original_groups_);
original_groups_ = nullptr;
}
DropPrivileges::~DropPrivileges() {
if (dropped_) {
// 1. On Linux/BSD we do not need to differentiate between FS/E since FS
// is set implicitly by seteuid.
// 2. We are elevating privileges, there is no security vulnerability if
// either privilege change fails.
if (fs_drop_) {
(void)_fs_set_user(getuid());
(void)_fs_set_group(getgid());
} else {
(void)seteuid(getuid());
(void)setegid(getgid());
}
dropped_ = false;
}
if (original_groups_ != nullptr) {
restoreGroups();
}
}
#endif
}
<|endoftext|> |
<commit_before>
// Library includes
#include <string>
#include <ostream>
#include <iostream>
#include <memory>
#include "grl/KukaFRI.hpp"
#include "grl/KukaFriClientData.hpp"
#include <boost/log/trivial.hpp>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <boost/asio.hpp>
#include <vector>
#include <iostream>
//
//template<typename T,typename V>
//inline T& printseq(T& out, V& v){
// out << "[";
// size_t last = v.size() - 1;
// for(size_t i = 0; i < v.size(); ++i) {
// out << v[i];
// if (i != last)
// out << ", ";
// }
// out << "]";
// return out;
//}
//
//template<typename T,size_t N>
//inline boost::log::formatting_ostream& operator<< (boost::log::formatting_ostream& out, const boost::container::static_vector<T,N>& v) {
// return printseq(out,v);
//}
//
//
//template<typename T,size_t N>
//ostream& operator<< (ostream& out, const boost::container::static_vector<T,N>& v) {
// return printseq(out,v);
//}
//
//
//template<typename T>
//inline boost::log::formatting_ostream& operator<<(boost::log::formatting_ostream& out, std::vector<T>& v)
//{
// return printseq(out, v);
//}
//template<typename T>
//inline std::ostream& operator<<(std::ostream& out, std::vector<T>& v)
//{
// return printseq(out,v);
//}
using boost::asio::ip::udp;
enum { max_length = 1024 };
int main(int argc, char* argv[])
{
try
{
std::string localhost("192.170.10.100");
std::string localport("30200");
std::string remotehost("192.170.10.2");
std::string remoteport("30200");
std::cout << "argc: " << argc << "\n";
/// @todo add default localhost/localport
if (argc !=5 && argc !=1)
{
std::cerr << "Usage: " << argv[0] << " <localip> <localport> <remoteip> <remoteport>\n";
return 1;
}
if(argc ==5){
localhost = std::string(argv[1]);
localport = std::string(argv[2]);
remotehost = std::string(argv[3]);
remoteport = std::string(argv[4]);
}
std::cout << "using: " << argv[0] << " " << localhost << " " << localport << " " << remotehost << " " << remoteport << "\n";
boost::asio::io_service io_service;
boost::asio::ip::udp::socket s(io_service, boost::asio::ip::udp::endpoint(boost::asio::ip::address::from_string(localhost), boost::lexical_cast<short>(localport)));
boost::asio::ip::udp::resolver resolver(io_service);
boost::asio::ip::udp::endpoint endpoint = *resolver.resolve({boost::asio::ip::udp::v4(), remotehost, remoteport});
s.connect(endpoint);
KUKA::FRI::ClientData friData(7);
/// @todo maybe there is a more convienient way to set this that is easier for users? perhaps initializeClientDataForiiwa()?
friData.expectedMonitorMsgID = KUKA::LBRState::LBRMONITORMESSAGEID;
std::chrono::time_point<std::chrono::high_resolution_clock> startTime;
double delta = -0.001;
BOOST_LOG_TRIVIAL(warning) << "WARNING: YOU COULD DAMAGE OR DESTROY YOUR KUKA ROBOT "
<< "if joint angle delta variable is too large with respect to "
<< "the time it takes to go around the loop and change it. "
<< "Current delta (radians/update): " << delta << "\n";
std::vector<double> ipoJointPos;
std::vector<double> offsetFromipoJointPos(7,0); // length 7, value 0
std::vector<double> jointStateToCommand(7,0);
for (std::size_t i = 0;;++i) {
/// use the interpolated joint position from the previous update as the base
/// @todo why is this?
grl::robot::arm::copy(friData.monitoringMsg,std::back_inserter(ipoJointPos),grl::revolute_joint_angle_interpolated_open_chain_state_tag());
/// perform the update step, receiving and sending data to/from the arm
boost::system::error_code send_ec, recv_ec;
std::size_t send_bytes_transferred, recv_bytes_transferred;
grl::robot::arm::update_state(s,friData,send_ec,send_bytes_transferred, recv_ec, recv_bytes_transferred);
// if data didn't arrive correctly, skip and try again
if(send_ec || recv_ec) continue;
/// consider moving joint angles based on time
int joint_to_move = 6;
if(i == 0 || ipoJointPos.empty()){
}
if
(
grl::robot::arm::get(friData.monitoringMsg,KUKA::FRI::ESessionState()) == KUKA::FRI::COMMANDING_ACTIVE
)
{
offsetFromipoJointPos[joint_to_move]+=delta;
// swap directions when a half circle was completed
if (
(offsetFromipoJointPos[joint_to_move] > 0.2 && delta > 0) ||
(offsetFromipoJointPos[joint_to_move] < -0.2 && delta < 0)
)
{
delta *=-1;
}
}
KUKA::FRI::ESessionState sessionState = grl::robot::arm::get(friData.monitoringMsg,KUKA::FRI::ESessionState());
// copy current joint position to commanded position
if (sessionState == KUKA::FRI::COMMANDING_WAIT || sessionState == KUKA::FRI::COMMANDING_ACTIVE)
{
boost::transform ( ipoJointPos, offsetFromipoJointPos, jointStateToCommand.begin(), std::plus<double>());
grl::robot::arm::set(friData.commandMsg, jointStateToCommand, grl::revolute_joint_angle_open_chain_command_tag());
}
// vector addition between ipoJointPosition and ipoJointPositionOffsets, copying the result into jointStateToCommand
/// @todo should we take the current joint state into consideration?
//BOOST_LOG_TRIVIAL(trace) << "position: " << state.position << " us: " << std::chrono::duration_cast<std::chrono::microseconds>(state.timestamp - startTime).count() << " connectionQuality: " << state.connectionQuality << " operationMode: " << state.operationMode << " sessionState: " << state.sessionState << " driveState: " << state.driveState << " ipoJointPosition: " << state.ipoJointPosition << " ipoJointPositionOffsets: " << state.ipoJointPositionOffsets << "\n";
}
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
<commit_msg>fixed incorrect copy of ipo joint position<commit_after>
// Library includes
#include <string>
#include <ostream>
#include <iostream>
#include <memory>
#include "grl/KukaFRI.hpp"
#include "grl/KukaFriClientData.hpp"
#include <boost/log/trivial.hpp>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <boost/asio.hpp>
#include <vector>
#include <iostream>
//
//template<typename T,typename V>
//inline T& printseq(T& out, V& v){
// out << "[";
// size_t last = v.size() - 1;
// for(size_t i = 0; i < v.size(); ++i) {
// out << v[i];
// if (i != last)
// out << ", ";
// }
// out << "]";
// return out;
//}
//
//template<typename T,size_t N>
//inline boost::log::formatting_ostream& operator<< (boost::log::formatting_ostream& out, const boost::container::static_vector<T,N>& v) {
// return printseq(out,v);
//}
//
//
//template<typename T,size_t N>
//ostream& operator<< (ostream& out, const boost::container::static_vector<T,N>& v) {
// return printseq(out,v);
//}
//
//
//template<typename T>
//inline boost::log::formatting_ostream& operator<<(boost::log::formatting_ostream& out, std::vector<T>& v)
//{
// return printseq(out, v);
//}
//template<typename T>
//inline std::ostream& operator<<(std::ostream& out, std::vector<T>& v)
//{
// return printseq(out,v);
//}
using boost::asio::ip::udp;
enum { max_length = 1024 };
int main(int argc, char* argv[])
{
try
{
std::string localhost("192.170.10.100");
std::string localport("30200");
std::string remotehost("192.170.10.2");
std::string remoteport("30200");
std::cout << "argc: " << argc << "\n";
/// @todo add default localhost/localport
if (argc !=5 && argc !=1)
{
std::cerr << "Usage: " << argv[0] << " <localip> <localport> <remoteip> <remoteport>\n";
return 1;
}
if(argc ==5){
localhost = std::string(argv[1]);
localport = std::string(argv[2]);
remotehost = std::string(argv[3]);
remoteport = std::string(argv[4]);
}
std::cout << "using: " << argv[0] << " " << localhost << " " << localport << " " << remotehost << " " << remoteport << "\n";
boost::asio::io_service io_service;
boost::asio::ip::udp::socket s(io_service, boost::asio::ip::udp::endpoint(boost::asio::ip::address::from_string(localhost), boost::lexical_cast<short>(localport)));
boost::asio::ip::udp::resolver resolver(io_service);
boost::asio::ip::udp::endpoint endpoint = *resolver.resolve({boost::asio::ip::udp::v4(), remotehost, remoteport});
s.connect(endpoint);
KUKA::FRI::ClientData friData(7);
/// @todo maybe there is a more convienient way to set this that is easier for users? perhaps initializeClientDataForiiwa()?
friData.expectedMonitorMsgID = KUKA::LBRState::LBRMONITORMESSAGEID;
std::chrono::time_point<std::chrono::high_resolution_clock> startTime;
double delta = -0.001;
BOOST_LOG_TRIVIAL(warning) << "WARNING: YOU COULD DAMAGE OR DESTROY YOUR KUKA ROBOT "
<< "if joint angle delta variable is too large with respect to "
<< "the time it takes to go around the loop and change it. "
<< "Current delta (radians/update): " << delta << "\n";
std::vector<double> ipoJointPos(7,0);
std::vector<double> offsetFromipoJointPos(7,0); // length 7, value 0
std::vector<double> jointStateToCommand(7,0);
for (std::size_t i = 0;;++i) {
/// use the interpolated joint position from the previous update as the base
/// @todo why is this?
grl::robot::arm::copy(friData.monitoringMsg,ipoJointPos.begin(),grl::revolute_joint_angle_interpolated_open_chain_state_tag());
/// perform the update step, receiving and sending data to/from the arm
boost::system::error_code send_ec, recv_ec;
std::size_t send_bytes_transferred, recv_bytes_transferred;
grl::robot::arm::update_state(s,friData,send_ec,send_bytes_transferred, recv_ec, recv_bytes_transferred);
// if data didn't arrive correctly, skip and try again
if(send_ec || recv_ec) continue;
/// consider moving joint angles based on time
int joint_to_move = 6;
if
(
grl::robot::arm::get(friData.monitoringMsg,KUKA::FRI::ESessionState()) == KUKA::FRI::COMMANDING_ACTIVE
)
{
offsetFromipoJointPos[joint_to_move]+=delta;
// swap directions when a half circle was completed
if (
(offsetFromipoJointPos[joint_to_move] > 0.2 && delta > 0) ||
(offsetFromipoJointPos[joint_to_move] < -0.2 && delta < 0)
)
{
delta *=-1;
}
}
KUKA::FRI::ESessionState sessionState = grl::robot::arm::get(friData.monitoringMsg,KUKA::FRI::ESessionState());
// copy current joint position to commanded position
if (sessionState == KUKA::FRI::COMMANDING_WAIT || sessionState == KUKA::FRI::COMMANDING_ACTIVE)
{
boost::transform ( ipoJointPos, offsetFromipoJointPos, jointStateToCommand.begin(), std::plus<double>());
grl::robot::arm::set(friData.commandMsg, jointStateToCommand, grl::revolute_joint_angle_open_chain_command_tag());
}
// vector addition between ipoJointPosition and ipoJointPositionOffsets, copying the result into jointStateToCommand
/// @todo should we take the current joint state into consideration?
//BOOST_LOG_TRIVIAL(trace) << "position: " << state.position << " us: " << std::chrono::duration_cast<std::chrono::microseconds>(state.timestamp - startTime).count() << " connectionQuality: " << state.connectionQuality << " operationMode: " << state.operationMode << " sessionState: " << state.sessionState << " driveState: " << state.driveState << " ipoJointPosition: " << state.ipoJointPosition << " ipoJointPositionOffsets: " << state.ipoJointPositionOffsets << "\n";
}
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
<|endoftext|> |
<commit_before>#include "ofxGuiGroupExtended.h"
#include "ofGraphics.h"
using namespace std;
ofxGuiGroupExtended::ofxGuiGroupExtended(){
_bVertical = true;
_bUseHeader = true;
}
ofxGuiGroupExtended::ofxGuiGroupExtended(const ofParameterGroup & parameters, string filename, float x, float y)
:ofxGuiGroup(parameters, filename, x, y){
_bVertical = true;
_bUseHeader = true;
}
ofxGuiGroupExtended * ofxGuiGroupExtended::setup(string collectionName, string filename, float x, float y){
ofxGuiGroup::setup(collectionName,filename,x,y);
return this;
}
ofxGuiGroupExtended * ofxGuiGroupExtended::setup(const ofParameterGroup & _parameters, string _filename, float x, float y){
ofxGuiGroup::setup(_parameters,filename,x,y);
return this;
}
void ofxGuiGroupExtended::add(ofxBaseGui * element){
collection.push_back( element );
if(_bVertical || collection.size() == 1) {
element->setPosition(b.x, b.y + b.height + spacing);
b.height += element->getHeight() + spacing;
if(b.width-spacing > element->getWidth() && _bVertical) {
element->setSize(b.width-spacing, element->getHeight());
}
}
else {
ofRectangle last_shape = collection[collection.size()-2]->getShape();
element->setPosition(last_shape.x + last_shape.getWidth() + spacing, last_shape.y);
b.width = element->getPosition().x + element->getWidth() - b.x + spacing;
}
if(b.width < element->getWidth()) {
b.width = element->getWidth();
sizeChangedCB();
setNeedsRedraw();
}
element->unregisterMouseEvents();
ofxGuiGroupExtended * subgroup = dynamic_cast<ofxGuiGroupExtended*>(element);
if(subgroup!=NULL){
subgroup->filename = filename;
subgroup->parent = this;
subgroup->scaleWidthElements(.98);
}else{
if(parent!=NULL){
element->setSize(b.width*.98,element->getHeight());
element->setPosition(b.x + b.width-element->getWidth(),element->getPosition().y);
}
}
parameters.add(element->getParameter());
setNeedsRedraw();
}
//void ofxGuiGroupExtended::setWidthElements(float w){
// if(_bVertical) {
// for(int i=0;i<(int)collection.size();i++){
// float w_i = collection[i]->getWidth();
// if((int)w_i != (int)w) {
// collection[i]->setSize(w,collection[i]->getHeight());
// collection[i]->setPosition(b.x + b.width-w,collection[i]->getPosition().y);
// ofxGuiGroupExtended * subgroup = dynamic_cast<ofxGuiGroupExtended*>(collection[i]);
// if(subgroup!=NULL){
// subgroup->setWidthElements(w);
// cout << w/w_i << endl;
// }
// }
// }
// }
//}
void ofxGuiGroupExtended::scaleWidthElements(float factor){
float w = this->b.getWidth()*factor;
if(_bVertical) {
for(int i=0;i<(int)collection.size();i++){
collection[i]->setSize(w,collection[i]->getHeight());
collection[i]->setPosition(b.x + b.width-w,collection[i]->getPosition().y);
ofxGuiGroupExtended * subgroup = dynamic_cast<ofxGuiGroupExtended*>(collection[i]);
if(subgroup!=NULL){
subgroup->scaleWidthElements(factor);
}
}
}
else {
float x = spacing;
for(int i=(int)collection.size()-1;i>=0;i--){
float w_i = collection[i]->getWidth()*factor;
collection[i]->setSize(w_i,collection[i]->getHeight());
x += w_i;
collection[i]->setPosition(b.x + b.width-x,collection[i]->getPosition().y);
ofxGuiGroupExtended * subgroup = dynamic_cast<ofxGuiGroupExtended*>(collection[i]);
if(subgroup!=NULL){
subgroup->scaleWidthElements(factor);
}
}
}
sizeChangedCB();
setNeedsRedraw();
}
void ofxGuiGroupExtended::clear(){
collection.clear();
parameters.clear();
b.height = spacing + spacingNextElement ;
if(_bUseHeader) {
b.height += header;
}
sizeChangedCB();
}
bool ofxGuiGroupExtended::mouseMoved(ofMouseEventArgs & args){
return ofxGuiGroup::mouseMoved(args);
}
bool ofxGuiGroupExtended::mousePressed(ofMouseEventArgs & args){
if(setValue(args.x, args.y, true)){
return true;
}
if( bGuiActive ){
ofMouseEventArgs a = args;
for(int i = 0; i < (int)collection.size(); i++){
if(collection[i]->mousePressed(a)) return true;
}
}
return false;
}
bool ofxGuiGroupExtended::mouseDragged(ofMouseEventArgs & args){
if(setValue(args.x, args.y, false)){
return true;
}
if( bGuiActive ){
ofMouseEventArgs a = args;
for(int i = 0; i < (int)collection.size(); i++){
if(collection[i]->mouseDragged(a)) return true;
}
}
return false;
}
bool ofxGuiGroupExtended::mouseReleased(ofMouseEventArgs & args){
return ofxGuiGroup::mouseReleased(args);
}
bool ofxGuiGroupExtended::mouseScrolled(ofMouseEventArgs & args){
return ofxGuiGroup::mouseScrolled(args);
}
void ofxGuiGroupExtended::generateDraw(){
border.clear();
border.setFillColor(ofColor(thisBorderColor,180));
border.setFilled(true);
border.rectangle(b.x,b.y+ spacingNextElement,b.width+1,b.height);
if(_bUseHeader) {
headerBg.clear();
headerBg.setFillColor(thisHeaderBackgroundColor);
headerBg.setFilled(true);
headerBg.rectangle(b.x,b.y + spacingNextElement, b.width+1, header);
textMesh = getTextMesh(getName(), textPadding + b.x, header / 2 + 4 + b.y+ spacingNextElement);
if(minimized){
textMesh.append(getTextMesh("+", b.width-textPadding-8 + b.x, header / 2 + 4+ b.y+ spacingNextElement));
}else{
textMesh.append(getTextMesh("-", b.width-textPadding-8 + b.x, header / 2 + 4 + b.y+ spacingNextElement));
}
}
}
void ofxGuiGroupExtended::render(){
border.draw();
if(_bUseHeader) {
headerBg.draw();
}
ofBlendMode blendMode = ofGetStyle().blendingMode;
if(blendMode!=OF_BLENDMODE_ALPHA){
ofEnableAlphaBlending();
}
ofColor c = ofGetStyle().color;
if(_bUseHeader) {
ofSetColor(thisTextColor);
bindFontTexture();
textMesh.draw();
unbindFontTexture();
}
if(!minimized){
for(int i = 0; i < (int)collection.size(); i++){
collection[i]->draw();
}
}
ofSetColor(c);
if(blendMode!=OF_BLENDMODE_ALPHA){
ofEnableBlendMode(blendMode);
}
}
bool ofxGuiGroupExtended::setValue(float mx, float my, bool bCheck){
if( !isGuiDrawing() ){
bGuiActive = false;
return false;
}
if( bCheck ){
if( b.inside(mx, my) ){
bGuiActive = true;
ofRectangle minButton(b.x+b.width-textPadding*3,b.y,textPadding*3,header);
if(minButton.inside(mx,my)){
minimized = !minimized;
if(minimized){
minimize();
}else{
maximize();
}
return true;
}
}
}
return false;
}
void ofxGuiGroupExtended::minimize(){
minimized=true;
b.height = spacing + spacingNextElement + 1 /*border*/;
if(_bUseHeader) {
b.height += header;
}
if(parent) parent->sizeChangedCB();
setNeedsRedraw();
}
void ofxGuiGroupExtended::maximize(){
minimized=false;
if(_bVertical) {
for(int i=0;i<(int)collection.size();i++){
b.height += collection[i]->getHeight() + spacing;
}
}
else {
b.height = 0;
for(int i=0;i<(int)collection.size();i++){
if(b.height < collection[i]->getHeight()) {
b.height = collection[i]->getHeight();
}
}
b.height += spacing*2+spacingNextElement;
if(_bUseHeader) {
b.height += header;
}
}
if(parent) parent->sizeChangedCB();
setNeedsRedraw();
}
void ofxGuiGroupExtended::minimizeAll(){
for(int i=0;i<(int)collection.size();i++){
ofxGuiGroupExtended * group = dynamic_cast<ofxGuiGroupExtended*>(collection[i]);
if(group)group->minimize();
}
}
void ofxGuiGroupExtended::maximizeAll(){
for(int i=0;i<(int)collection.size();i++){
ofxGuiGroupExtended * group = dynamic_cast<ofxGuiGroupExtended*>(collection[i]);
if(group)group->maximize();
}
}
void ofxGuiGroupExtended::sizeChangedCB(){
float x,y;
if(parent){
x = b.x + spacing + spacingNextElement;
y = b.y + spacing + spacingNextElement;
}else{
x = b.x + spacing;
y = b.y + spacing;
}
if(_bUseHeader) {
y += header;
}
if(_bVertical) {
for(int i=0;i<(int)collection.size();i++){
collection[i]->setPosition(collection[i]->getPosition().x,y + spacing);
if(collection[i]->getWidth() < b.width - spacing) {
collection[i]->setSize(b.width - spacing, collection[i]->getHeight());
}
y += collection[i]->getHeight();
}
b.height = y - b.y;
}
else {
x -= spacing;
float max_h = 0;
for(int i=0;i<(int)collection.size();i++){
if(i == 0) {
collection[i]->setPosition(x,y + spacing);
}
else {
float x_i = collection[i-1]->getPosition().x + collection[i-1]->getWidth()+spacing;
collection[i]->setPosition(x, y+spacing);
}
x += collection[i]->getWidth() + spacing;
if(max_h < collection[i]->getHeight()) {
max_h = collection[i]->getHeight();
}
}
y += max_h+spacing;
x += spacing;
b.height = y - b.y;
b.width = x - b.x;
}
if(parent) parent->sizeChangedCB();
setNeedsRedraw();
}
void ofxGuiGroupExtended::setAlignHorizontal() {
_bVertical = false;
}
void ofxGuiGroupExtended::setAlignVertical() {
_bVertical = true;
}
void ofxGuiGroupExtended::showHeader(bool show) {
_bUseHeader = show;
sizeChangedCB();
setNeedsRedraw();
}
<commit_msg>not tested setWidthElements implementation<commit_after>#include "ofxGuiGroupExtended.h"
#include "ofGraphics.h"
using namespace std;
ofxGuiGroupExtended::ofxGuiGroupExtended(){
_bVertical = true;
_bUseHeader = true;
}
ofxGuiGroupExtended::ofxGuiGroupExtended(const ofParameterGroup & parameters, string filename, float x, float y)
:ofxGuiGroup(parameters, filename, x, y){
_bVertical = true;
_bUseHeader = true;
}
ofxGuiGroupExtended * ofxGuiGroupExtended::setup(string collectionName, string filename, float x, float y){
ofxGuiGroup::setup(collectionName,filename,x,y);
return this;
}
ofxGuiGroupExtended * ofxGuiGroupExtended::setup(const ofParameterGroup & _parameters, string _filename, float x, float y){
ofxGuiGroup::setup(_parameters,filename,x,y);
return this;
}
void ofxGuiGroupExtended::add(ofxBaseGui * element){
collection.push_back( element );
if(_bVertical || collection.size() == 1) {
element->setPosition(b.x, b.y + b.height + spacing);
b.height += element->getHeight() + spacing;
if(b.width-spacing > element->getWidth() && _bVertical) {
element->setSize(b.width-spacing, element->getHeight());
}
}
else {
ofRectangle last_shape = collection[collection.size()-2]->getShape();
element->setPosition(last_shape.x + last_shape.getWidth() + spacing, last_shape.y);
b.width = element->getPosition().x + element->getWidth() - b.x + spacing;
}
if(b.width < element->getWidth()) {
b.width = element->getWidth();
sizeChangedCB();
setNeedsRedraw();
}
element->unregisterMouseEvents();
ofxGuiGroupExtended * subgroup = dynamic_cast<ofxGuiGroupExtended*>(element);
if(subgroup!=NULL){
subgroup->filename = filename;
subgroup->parent = this;
subgroup->scaleWidthElements(.98);
}else{
if(parent!=NULL){
element->setSize(b.width*.98,element->getHeight());
element->setPosition(b.x + b.width-element->getWidth(),element->getPosition().y);
}
}
parameters.add(element->getParameter());
setNeedsRedraw();
}
void ofxGuiGroupExtended::setWidthElements(float w){
if((int)b.width != (int)w) {
scaleWidthElements(w / b.width);
}
}
void ofxGuiGroupExtended::scaleWidthElements(float factor){
float w = this->b.getWidth()*factor;
if(_bVertical) {
for(int i=0;i<(int)collection.size();i++){
collection[i]->setSize(w,collection[i]->getHeight());
collection[i]->setPosition(b.x + b.width-w,collection[i]->getPosition().y);
ofxGuiGroupExtended * subgroup = dynamic_cast<ofxGuiGroupExtended*>(collection[i]);
if(subgroup!=NULL){
subgroup->scaleWidthElements(factor);
}
}
}
else {
float x = spacing;
for(int i=(int)collection.size()-1;i>=0;i--){
float w_i = collection[i]->getWidth()*factor;
collection[i]->setSize(w_i,collection[i]->getHeight());
x += w_i;
collection[i]->setPosition(b.x + b.width-x,collection[i]->getPosition().y);
ofxGuiGroupExtended * subgroup = dynamic_cast<ofxGuiGroupExtended*>(collection[i]);
if(subgroup!=NULL){
subgroup->scaleWidthElements(factor);
}
}
}
sizeChangedCB();
setNeedsRedraw();
}
void ofxGuiGroupExtended::clear(){
collection.clear();
parameters.clear();
b.height = spacing + spacingNextElement ;
if(_bUseHeader) {
b.height += header;
}
sizeChangedCB();
}
bool ofxGuiGroupExtended::mouseMoved(ofMouseEventArgs & args){
return ofxGuiGroup::mouseMoved(args);
}
bool ofxGuiGroupExtended::mousePressed(ofMouseEventArgs & args){
if(setValue(args.x, args.y, true)){
return true;
}
if( bGuiActive ){
ofMouseEventArgs a = args;
for(int i = 0; i < (int)collection.size(); i++){
if(collection[i]->mousePressed(a)) return true;
}
}
return false;
}
bool ofxGuiGroupExtended::mouseDragged(ofMouseEventArgs & args){
if(setValue(args.x, args.y, false)){
return true;
}
if( bGuiActive ){
ofMouseEventArgs a = args;
for(int i = 0; i < (int)collection.size(); i++){
if(collection[i]->mouseDragged(a)) return true;
}
}
return false;
}
bool ofxGuiGroupExtended::mouseReleased(ofMouseEventArgs & args){
return ofxGuiGroup::mouseReleased(args);
}
bool ofxGuiGroupExtended::mouseScrolled(ofMouseEventArgs & args){
return ofxGuiGroup::mouseScrolled(args);
}
void ofxGuiGroupExtended::generateDraw(){
border.clear();
border.setFillColor(ofColor(thisBorderColor,180));
border.setFilled(true);
border.rectangle(b.x,b.y+ spacingNextElement,b.width+1,b.height);
if(_bUseHeader) {
headerBg.clear();
headerBg.setFillColor(thisHeaderBackgroundColor);
headerBg.setFilled(true);
headerBg.rectangle(b.x,b.y + spacingNextElement, b.width+1, header);
textMesh = getTextMesh(getName(), textPadding + b.x, header / 2 + 4 + b.y+ spacingNextElement);
if(minimized){
textMesh.append(getTextMesh("+", b.width-textPadding-8 + b.x, header / 2 + 4+ b.y+ spacingNextElement));
}else{
textMesh.append(getTextMesh("-", b.width-textPadding-8 + b.x, header / 2 + 4 + b.y+ spacingNextElement));
}
}
}
void ofxGuiGroupExtended::render(){
border.draw();
if(_bUseHeader) {
headerBg.draw();
}
ofBlendMode blendMode = ofGetStyle().blendingMode;
if(blendMode!=OF_BLENDMODE_ALPHA){
ofEnableAlphaBlending();
}
ofColor c = ofGetStyle().color;
if(_bUseHeader) {
ofSetColor(thisTextColor);
bindFontTexture();
textMesh.draw();
unbindFontTexture();
}
if(!minimized){
for(int i = 0; i < (int)collection.size(); i++){
collection[i]->draw();
}
}
ofSetColor(c);
if(blendMode!=OF_BLENDMODE_ALPHA){
ofEnableBlendMode(blendMode);
}
}
bool ofxGuiGroupExtended::setValue(float mx, float my, bool bCheck){
if( !isGuiDrawing() ){
bGuiActive = false;
return false;
}
if( bCheck ){
if( b.inside(mx, my) ){
bGuiActive = true;
ofRectangle minButton(b.x+b.width-textPadding*3,b.y,textPadding*3,header);
if(minButton.inside(mx,my)){
minimized = !minimized;
if(minimized){
minimize();
}else{
maximize();
}
return true;
}
}
}
return false;
}
void ofxGuiGroupExtended::minimize(){
minimized=true;
b.height = spacing + spacingNextElement + 1 /*border*/;
if(_bUseHeader) {
b.height += header;
}
if(parent) parent->sizeChangedCB();
setNeedsRedraw();
}
void ofxGuiGroupExtended::maximize(){
minimized=false;
if(_bVertical) {
for(int i=0;i<(int)collection.size();i++){
b.height += collection[i]->getHeight() + spacing;
}
}
else {
b.height = 0;
for(int i=0;i<(int)collection.size();i++){
if(b.height < collection[i]->getHeight()) {
b.height = collection[i]->getHeight();
}
}
b.height += spacing*2+spacingNextElement;
if(_bUseHeader) {
b.height += header;
}
}
if(parent) parent->sizeChangedCB();
setNeedsRedraw();
}
void ofxGuiGroupExtended::minimizeAll(){
for(int i=0;i<(int)collection.size();i++){
ofxGuiGroupExtended * group = dynamic_cast<ofxGuiGroupExtended*>(collection[i]);
if(group)group->minimize();
}
}
void ofxGuiGroupExtended::maximizeAll(){
for(int i=0;i<(int)collection.size();i++){
ofxGuiGroupExtended * group = dynamic_cast<ofxGuiGroupExtended*>(collection[i]);
if(group)group->maximize();
}
}
void ofxGuiGroupExtended::sizeChangedCB(){
float x,y;
if(parent){
x = b.x + spacing + spacingNextElement;
y = b.y + spacing + spacingNextElement;
}else{
x = b.x + spacing;
y = b.y + spacing;
}
if(_bUseHeader) {
y += header;
}
if(_bVertical) {
for(int i=0;i<(int)collection.size();i++){
collection[i]->setPosition(collection[i]->getPosition().x,y + spacing);
if(collection[i]->getWidth() < b.width - spacing) {
collection[i]->setSize(b.width - spacing, collection[i]->getHeight());
}
y += collection[i]->getHeight();
}
b.height = y - b.y;
}
else {
x -= spacing;
float max_h = 0;
for(int i=0;i<(int)collection.size();i++){
if(i == 0) {
collection[i]->setPosition(x,y + spacing);
}
else {
float x_i = collection[i-1]->getPosition().x + collection[i-1]->getWidth()+spacing;
collection[i]->setPosition(x, y+spacing);
}
x += collection[i]->getWidth() + spacing;
if(max_h < collection[i]->getHeight()) {
max_h = collection[i]->getHeight();
}
}
y += max_h+spacing;
x += spacing;
b.height = y - b.y;
b.width = x - b.x;
}
if(parent) parent->sizeChangedCB();
setNeedsRedraw();
}
void ofxGuiGroupExtended::setAlignHorizontal() {
_bVertical = false;
}
void ofxGuiGroupExtended::setAlignVertical() {
_bVertical = true;
}
void ofxGuiGroupExtended::showHeader(bool show) {
_bUseHeader = show;
sizeChangedCB();
setNeedsRedraw();
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
// boost
#include <boost/python.hpp>
#include <boost/python/detail/api_placeholder.hpp>
// stl
#include <sstream>
// mapnik
#include <mapnik/envelope.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/feature_layer_desc.hpp>
namespace
{
//user-friendly wrapper that uses Python dictionary
using namespace boost::python;
boost::shared_ptr<mapnik::datasource> create_datasource(const dict& d)
{
mapnik::parameters params;
boost::python::list keys=d.keys();
for (int i=0; i<len(keys); ++i)
{
std::string key = extract<std::string>(keys[i]);
object obj = d[key];
extract<std::string> ex(obj);
if (ex.check())
{
params[key] = ex();
}
}
return mapnik::datasource_cache::create(params);
}
std::string describe(boost::shared_ptr<mapnik::datasource> const& ds)
{
std::stringstream ss;
if (ds)
{
ss << ds->get_descriptor() << "\n";
}
else
{
ss << "Null\n";
}
return ss.str();
}
}
void export_datasource()
{
using namespace boost::python;
using mapnik::datasource;
class_<datasource,boost::shared_ptr<datasource>,
boost::noncopyable>("Datasource",no_init)
.def("envelope",&datasource::envelope)
.def("descriptor",&datasource::get_descriptor) //todo
.def("features",&datasource::features)
.def("params",&datasource::params,return_value_policy<copy_const_reference>(),
"The configuration parameters of the data source. "
"These vary depending on the type of data source.")
;
def("Describe",&describe);
def("CreateDatasource",&create_datasource);
}
<commit_msg>Reflect featureset and feature classes in Python. Featureset follows Python iterator protocol e.g:<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
// boost
#include <boost/python.hpp>
#include <boost/python/detail/api_placeholder.hpp>
// stl
#include <sstream>
// mapnik
#include <mapnik/envelope.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/feature_layer_desc.hpp>
namespace
{
//user-friendly wrapper that uses Python dictionary
using namespace boost::python;
boost::shared_ptr<mapnik::datasource> create_datasource(const dict& d)
{
mapnik::parameters params;
boost::python::list keys=d.keys();
for (int i=0; i<len(keys); ++i)
{
std::string key = extract<std::string>(keys[i]);
object obj = d[key];
extract<std::string> ex(obj);
if (ex.check())
{
params[key] = ex();
}
}
return mapnik::datasource_cache::create(params);
}
std::string describe(boost::shared_ptr<mapnik::datasource> const& ds)
{
std::stringstream ss;
if (ds)
{
ss << ds->get_descriptor() << "\n";
}
else
{
ss << "Null\n";
}
return ss.str();
}
}
inline object pass_through(object const& o) { return o; }
inline mapnik::feature_ptr next(mapnik::featureset_ptr const& itr)
{
mapnik::feature_ptr f = itr->next();
if (!f)
{
PyErr_SetString(PyExc_StopIteration, "No more features.");
boost::python::throw_error_already_set();
}
return f;
}
void export_datasource()
{
using namespace boost::python;
using mapnik::datasource;
using mapnik::Featureset;
using mapnik::Feature;
class_<Feature,boost::shared_ptr<Feature>,
boost::noncopyable>("Feature",no_init)
.def("id",&Feature::id)
.def("__str__",&Feature::to_string)
;
class_<Featureset,boost::shared_ptr<Featureset>,
boost::noncopyable>("Datasource",no_init)
.def("next",next)
.def("__iter__",pass_through)
;
class_<datasource,boost::shared_ptr<datasource>,
boost::noncopyable>("Datasource",no_init)
.def("envelope",&datasource::envelope)
.def("descriptor",&datasource::get_descriptor) //todo
.def("features",&datasource::features)
.def("features_at_point",&datasource::features_at_point)
.def("params",&datasource::params,return_value_policy<copy_const_reference>(),
"The configuration parameters of the data source. "
"These vary depending on the type of data source.")
;
def("Describe",&describe);
def("CreateDatasource",&create_datasource);
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#if defined(GRID_RENDERER)
// boost
#include <boost/python.hpp>
// mapnik
#include <mapnik/map.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/debug.hpp>
#include <mapnik/grid/grid_renderer.hpp>
#include <mapnik/grid/grid.hpp>
#include <mapnik/grid/grid_util.hpp>
#include <mapnik/grid/grid_view.hpp>
#include <mapnik/value_error.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/feature_kv_iterator.hpp>
#include "python_grid_utils.hpp"
// stl
#include <stdexcept>
namespace mapnik {
template <typename T>
void grid2utf(T const& grid_type,
boost::python::list& l,
std::vector<typename T::lookup_type>& key_order)
{
using keys_type = std::map< typename T::lookup_type, typename T::value_type>;
using keys_iterator = typename keys_type::const_iterator;
typename T::data_type const& data = grid_type.data();
typename T::feature_key_type const& feature_keys = grid_type.get_feature_keys();
typename T::feature_key_type::const_iterator feature_pos;
keys_type keys;
// start counting at utf8 codepoint 32, aka space character
std::uint16_t codepoint = 32;
unsigned array_size = data.width();
for (unsigned y = 0; y < data.height(); ++y)
{
std::uint16_t idx = 0;
const std::unique_ptr<Py_UNICODE[]> line(new Py_UNICODE[array_size]);
typename T::value_type const* row = data.getRow(y);
for (unsigned x = 0; x < data.width(); ++x)
{
typename T::value_type feature_id = row[x];
feature_pos = feature_keys.find(feature_id);
if (feature_pos != feature_keys.end())
{
mapnik::grid::lookup_type val = feature_pos->second;
keys_iterator key_pos = keys.find(val);
if (key_pos == keys.end())
{
// Create a new entry for this key. Skip the codepoints that
// can't be encoded directly in JSON.
if (codepoint == 34) ++codepoint; // Skip "
else if (codepoint == 92) ++codepoint; // Skip backslash
if (feature_id == mapnik::grid::base_mask)
{
keys[""] = codepoint;
key_order.push_back("");
}
else
{
keys[val] = codepoint;
key_order.push_back(val);
}
line[idx++] = static_cast<Py_UNICODE>(codepoint);
++codepoint;
}
else
{
line[idx++] = static_cast<Py_UNICODE>(key_pos->second);
}
}
// else, shouldn't get here...
}
l.append(boost::python::object(
boost::python::handle<>(
PyUnicode_FromUnicode(line.get(), array_size))));
}
}
template <typename T>
void grid2utf(T const& grid_type,
boost::python::list& l,
std::vector<typename T::lookup_type>& key_order,
unsigned int resolution)
{
using keys_type = std::map< typename T::lookup_type, typename T::value_type>;
using keys_iterator = typename keys_type::const_iterator;
typename T::feature_key_type const& feature_keys = grid_type.get_feature_keys();
typename T::feature_key_type::const_iterator feature_pos;
keys_type keys;
// start counting at utf8 codepoint 32, aka space character
std::uint16_t codepoint = 32;
unsigned array_size = std::ceil(grid_type.width()/static_cast<float>(resolution));
for (unsigned y = 0; y < grid_type.height(); y=y+resolution)
{
std::uint16_t idx = 0;
const std::unique_ptr<Py_UNICODE[]> line(new Py_UNICODE[array_size]);
mapnik::grid::value_type const* row = grid_type.getRow(y);
for (unsigned x = 0; x < grid_type.width(); x=x+resolution)
{
typename T::value_type feature_id = row[x];
feature_pos = feature_keys.find(feature_id);
if (feature_pos != feature_keys.end())
{
mapnik::grid::lookup_type val = feature_pos->second;
keys_iterator key_pos = keys.find(val);
if (key_pos == keys.end())
{
// Create a new entry for this key. Skip the codepoints that
// can't be encoded directly in JSON.
if (codepoint == 34) ++codepoint; // Skip "
else if (codepoint == 92) ++codepoint; // Skip backslash
if (feature_id == mapnik::grid::base_mask)
{
keys[""] = codepoint;
key_order.push_back("");
}
else
{
keys[val] = codepoint;
key_order.push_back(val);
}
line[idx++] = static_cast<Py_UNICODE>(codepoint);
++codepoint;
}
else
{
line[idx++] = static_cast<Py_UNICODE>(key_pos->second);
}
}
// else, shouldn't get here...
}
l.append(boost::python::object(
boost::python::handle<>(
PyUnicode_FromUnicode(line.get(), array_size))));
}
}
template <typename T>
void grid2utf2(T const& grid_type,
boost::python::list& l,
std::vector<typename T::lookup_type>& key_order,
unsigned int resolution)
{
using keys_type = std::map< typename T::lookup_type, typename T::value_type>;
using keys_iterator = typename keys_type::const_iterator;
typename T::data_type const& data = grid_type.data();
typename T::feature_key_type const& feature_keys = grid_type.get_feature_keys();
typename T::feature_key_type::const_iterator feature_pos;
keys_type keys;
// start counting at utf8 codepoint 32, aka space character
uint16_t codepoint = 32;
mapnik::grid::data_type target(data.width()/resolution,data.height()/resolution);
mapnik::scale_grid(target,grid_type.data(),0.0,0.0);
unsigned array_size = target.width();
for (unsigned y = 0; y < target.height(); ++y)
{
uint16_t idx = 0;
const std::unique_ptr<Py_UNICODE[]> line(new Py_UNICODE[array_size]);
mapnik::grid::value_type * row = target.getRow(y);
unsigned x;
for (x = 0; x < target.width(); ++x)
{
feature_pos = feature_keys.find(row[x]);
if (feature_pos != feature_keys.end())
{
mapnik::grid::lookup_type val = feature_pos->second;
keys_iterator key_pos = keys.find(val);
if (key_pos == keys.end())
{
// Create a new entry for this key. Skip the codepoints that
// can't be encoded directly in JSON.
if (codepoint == 34) ++codepoint; // Skip "
else if (codepoint == 92) ++codepoint; // Skip backslash
keys[val] = codepoint;
key_order.push_back(val);
line[idx++] = static_cast<Py_UNICODE>(codepoint);
++codepoint;
}
else
{
line[idx++] = static_cast<Py_UNICODE>(key_pos->second);
}
}
// else, shouldn't get here...
}
l.append(boost::python::object(
boost::python::handle<>(
PyUnicode_FromUnicode(line.get(), array_size))));
}
}
template <typename T>
void write_features(T const& grid_type,
boost::python::dict& feature_data,
std::vector<typename T::lookup_type> const& key_order)
{
typename T::feature_type const& g_features = grid_type.get_grid_features();
if (g_features.size() <= 0)
{
return;
}
std::set<std::string> const& attributes = grid_type.property_names();
typename T::feature_type::const_iterator feat_end = g_features.end();
for ( std::string const& key_item :key_order )
{
if (key_item.empty())
{
continue;
}
typename T::feature_type::const_iterator feat_itr = g_features.find(key_item);
if (feat_itr == feat_end)
{
continue;
}
bool found = false;
boost::python::dict feat;
mapnik::feature_ptr feature = feat_itr->second;
for ( std::string const& attr : attributes )
{
if (attr == "__id__")
{
feat[attr.c_str()] = feature->id();
}
else if (feature->has_key(attr))
{
found = true;
feat[attr.c_str()] = feature->get(attr);
}
}
if (found)
{
feature_data[feat_itr->first] = feat;
}
}
}
template <typename T>
void grid_encode_utf(T const& grid_type,
boost::python::dict & json,
bool add_features,
unsigned int resolution)
{
// convert buffer to utf and gather key order
boost::python::list l;
std::vector<typename T::lookup_type> key_order;
if (resolution != 1) {
// resample on the fly - faster, less accurate
mapnik::grid2utf<T>(grid_type,l,key_order,resolution);
// resample first - slower, more accurate
//mapnik::grid2utf2<T>(grid_type,l,key_order,resolution);
}
else
{
mapnik::grid2utf<T>(grid_type,l,key_order);
}
// convert key order to proper python list
boost::python::list keys_a;
for ( typename T::lookup_type const& key_id : key_order )
{
keys_a.append(key_id);
}
// gather feature data
boost::python::dict feature_data;
if (add_features) {
mapnik::write_features<T>(grid_type,feature_data,key_order);
}
json["grid"] = l;
json["keys"] = keys_a;
json["data"] = feature_data;
}
template <typename T>
boost::python::dict grid_encode( T const& grid, std::string const& format, bool add_features, unsigned int resolution)
{
if (format == "utf") {
boost::python::dict json;
grid_encode_utf<T>(grid,json,add_features,resolution);
return json;
}
else
{
std::stringstream s;
s << "'utf' is currently the only supported encoding format.";
throw mapnik::value_error(s.str());
}
}
template boost::python::dict grid_encode( mapnik::grid const& grid, std::string const& format, bool add_features, unsigned int resolution);
template boost::python::dict grid_encode( mapnik::grid_view const& grid, std::string const& format, bool add_features, unsigned int resolution);
/* new approach: key comes from grid object
* grid size should be same as the map
* encoding, resizing handled as method on grid object
* whether features are dumped is determined by argument not 'fields'
*/
void render_layer_for_grid(mapnik::Map const& map,
mapnik::grid & grid,
unsigned layer_idx, // TODO - layer by name or index
boost::python::list const& fields)
{
std::vector<mapnik::layer> const& layers = map.layers();
std::size_t layer_num = layers.size();
if (layer_idx >= layer_num) {
std::ostringstream s;
s << "Zero-based layer index '" << layer_idx << "' not valid, only '"
<< layer_num << "' layers are in map\n";
throw std::runtime_error(s.str());
}
// convert python list to std::set
boost::python::ssize_t num_fields = boost::python::len(fields);
for(boost::python::ssize_t i=0; i<num_fields; i++) {
boost::python::extract<std::string> name(fields[i]);
if (name.check())
{
grid.add_property_name(name());
}
else
{
std::stringstream s;
s << "list of field names must be strings";
throw mapnik::value_error(s.str());
}
}
// copy property names
std::set<std::string> attributes = grid.property_names();
// todo - make this a static constant
std::string known_id_key = "__id__";
if (attributes.find(known_id_key) != attributes.end())
{
attributes.erase(known_id_key);
}
std::string join_field = grid.get_key();
if (known_id_key != join_field &&
attributes.find(join_field) == attributes.end())
{
attributes.insert(join_field);
}
mapnik::grid_renderer<mapnik::grid> ren(map,grid,1.0,0,0);
mapnik::layer const& layer = layers[layer_idx];
ren.apply(layer,attributes);
}
}
#endif
<commit_msg>fix iterator type<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#if defined(GRID_RENDERER)
// boost
#include <boost/python.hpp>
// mapnik
#include <mapnik/map.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/debug.hpp>
#include <mapnik/grid/grid_renderer.hpp>
#include <mapnik/grid/grid.hpp>
#include <mapnik/grid/grid_util.hpp>
#include <mapnik/grid/grid_view.hpp>
#include <mapnik/value_error.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/feature_kv_iterator.hpp>
#include "python_grid_utils.hpp"
// stl
#include <stdexcept>
namespace mapnik {
template <typename T>
void grid2utf(T const& grid_type,
boost::python::list& l,
std::vector<typename T::lookup_type>& key_order)
{
using keys_type = std::map< typename T::lookup_type, typename T::value_type>;
using keys_iterator = typename keys_type::iterator;
typename T::data_type const& data = grid_type.data();
typename T::feature_key_type const& feature_keys = grid_type.get_feature_keys();
typename T::feature_key_type::const_iterator feature_pos;
keys_type keys;
// start counting at utf8 codepoint 32, aka space character
std::uint16_t codepoint = 32;
unsigned array_size = data.width();
for (unsigned y = 0; y < data.height(); ++y)
{
std::uint16_t idx = 0;
const std::unique_ptr<Py_UNICODE[]> line(new Py_UNICODE[array_size]);
typename T::value_type const* row = data.getRow(y);
for (unsigned x = 0; x < data.width(); ++x)
{
typename T::value_type feature_id = row[x];
feature_pos = feature_keys.find(feature_id);
if (feature_pos != feature_keys.end())
{
mapnik::grid::lookup_type val = feature_pos->second;
keys_iterator key_pos = keys.find(val);
if (key_pos == keys.end())
{
// Create a new entry for this key. Skip the codepoints that
// can't be encoded directly in JSON.
if (codepoint == 34) ++codepoint; // Skip "
else if (codepoint == 92) ++codepoint; // Skip backslash
if (feature_id == mapnik::grid::base_mask)
{
keys[""] = codepoint;
key_order.push_back("");
}
else
{
keys[val] = codepoint;
key_order.push_back(val);
}
line[idx++] = static_cast<Py_UNICODE>(codepoint);
++codepoint;
}
else
{
line[idx++] = static_cast<Py_UNICODE>(key_pos->second);
}
}
// else, shouldn't get here...
}
l.append(boost::python::object(
boost::python::handle<>(
PyUnicode_FromUnicode(line.get(), array_size))));
}
}
template <typename T>
void grid2utf(T const& grid_type,
boost::python::list& l,
std::vector<typename T::lookup_type>& key_order,
unsigned int resolution)
{
using keys_type = std::map< typename T::lookup_type, typename T::value_type>;
using keys_iterator = typename keys_type::iterator;
typename T::feature_key_type const& feature_keys = grid_type.get_feature_keys();
typename T::feature_key_type::const_iterator feature_pos;
keys_type keys;
// start counting at utf8 codepoint 32, aka space character
std::uint16_t codepoint = 32;
unsigned array_size = std::ceil(grid_type.width()/static_cast<float>(resolution));
for (unsigned y = 0; y < grid_type.height(); y=y+resolution)
{
std::uint16_t idx = 0;
const std::unique_ptr<Py_UNICODE[]> line(new Py_UNICODE[array_size]);
mapnik::grid::value_type const* row = grid_type.getRow(y);
for (unsigned x = 0; x < grid_type.width(); x=x+resolution)
{
typename T::value_type feature_id = row[x];
feature_pos = feature_keys.find(feature_id);
if (feature_pos != feature_keys.end())
{
mapnik::grid::lookup_type val = feature_pos->second;
keys_iterator key_pos = keys.find(val);
if (key_pos == keys.end())
{
// Create a new entry for this key. Skip the codepoints that
// can't be encoded directly in JSON.
if (codepoint == 34) ++codepoint; // Skip "
else if (codepoint == 92) ++codepoint; // Skip backslash
if (feature_id == mapnik::grid::base_mask)
{
keys[""] = codepoint;
key_order.push_back("");
}
else
{
keys[val] = codepoint;
key_order.push_back(val);
}
line[idx++] = static_cast<Py_UNICODE>(codepoint);
++codepoint;
}
else
{
line[idx++] = static_cast<Py_UNICODE>(key_pos->second);
}
}
// else, shouldn't get here...
}
l.append(boost::python::object(
boost::python::handle<>(
PyUnicode_FromUnicode(line.get(), array_size))));
}
}
template <typename T>
void grid2utf2(T const& grid_type,
boost::python::list& l,
std::vector<typename T::lookup_type>& key_order,
unsigned int resolution)
{
using keys_type = std::map< typename T::lookup_type, typename T::value_type>;
using keys_iterator = typename keys_type::iterator;
typename T::data_type const& data = grid_type.data();
typename T::feature_key_type const& feature_keys = grid_type.get_feature_keys();
typename T::feature_key_type::const_iterator feature_pos;
keys_type keys;
// start counting at utf8 codepoint 32, aka space character
uint16_t codepoint = 32;
mapnik::grid::data_type target(data.width()/resolution,data.height()/resolution);
mapnik::scale_grid(target,grid_type.data(),0.0,0.0);
unsigned array_size = target.width();
for (unsigned y = 0; y < target.height(); ++y)
{
uint16_t idx = 0;
const std::unique_ptr<Py_UNICODE[]> line(new Py_UNICODE[array_size]);
mapnik::grid::value_type * row = target.getRow(y);
unsigned x;
for (x = 0; x < target.width(); ++x)
{
feature_pos = feature_keys.find(row[x]);
if (feature_pos != feature_keys.end())
{
mapnik::grid::lookup_type val = feature_pos->second;
keys_iterator key_pos = keys.find(val);
if (key_pos == keys.end())
{
// Create a new entry for this key. Skip the codepoints that
// can't be encoded directly in JSON.
if (codepoint == 34) ++codepoint; // Skip "
else if (codepoint == 92) ++codepoint; // Skip backslash
keys[val] = codepoint;
key_order.push_back(val);
line[idx++] = static_cast<Py_UNICODE>(codepoint);
++codepoint;
}
else
{
line[idx++] = static_cast<Py_UNICODE>(key_pos->second);
}
}
// else, shouldn't get here...
}
l.append(boost::python::object(
boost::python::handle<>(
PyUnicode_FromUnicode(line.get(), array_size))));
}
}
template <typename T>
void write_features(T const& grid_type,
boost::python::dict& feature_data,
std::vector<typename T::lookup_type> const& key_order)
{
typename T::feature_type const& g_features = grid_type.get_grid_features();
if (g_features.size() <= 0)
{
return;
}
std::set<std::string> const& attributes = grid_type.property_names();
typename T::feature_type::const_iterator feat_end = g_features.end();
for ( std::string const& key_item :key_order )
{
if (key_item.empty())
{
continue;
}
typename T::feature_type::const_iterator feat_itr = g_features.find(key_item);
if (feat_itr == feat_end)
{
continue;
}
bool found = false;
boost::python::dict feat;
mapnik::feature_ptr feature = feat_itr->second;
for ( std::string const& attr : attributes )
{
if (attr == "__id__")
{
feat[attr.c_str()] = feature->id();
}
else if (feature->has_key(attr))
{
found = true;
feat[attr.c_str()] = feature->get(attr);
}
}
if (found)
{
feature_data[feat_itr->first] = feat;
}
}
}
template <typename T>
void grid_encode_utf(T const& grid_type,
boost::python::dict & json,
bool add_features,
unsigned int resolution)
{
// convert buffer to utf and gather key order
boost::python::list l;
std::vector<typename T::lookup_type> key_order;
if (resolution != 1) {
// resample on the fly - faster, less accurate
mapnik::grid2utf<T>(grid_type,l,key_order,resolution);
// resample first - slower, more accurate
//mapnik::grid2utf2<T>(grid_type,l,key_order,resolution);
}
else
{
mapnik::grid2utf<T>(grid_type,l,key_order);
}
// convert key order to proper python list
boost::python::list keys_a;
for ( typename T::lookup_type const& key_id : key_order )
{
keys_a.append(key_id);
}
// gather feature data
boost::python::dict feature_data;
if (add_features) {
mapnik::write_features<T>(grid_type,feature_data,key_order);
}
json["grid"] = l;
json["keys"] = keys_a;
json["data"] = feature_data;
}
template <typename T>
boost::python::dict grid_encode( T const& grid, std::string const& format, bool add_features, unsigned int resolution)
{
if (format == "utf") {
boost::python::dict json;
grid_encode_utf<T>(grid,json,add_features,resolution);
return json;
}
else
{
std::stringstream s;
s << "'utf' is currently the only supported encoding format.";
throw mapnik::value_error(s.str());
}
}
template boost::python::dict grid_encode( mapnik::grid const& grid, std::string const& format, bool add_features, unsigned int resolution);
template boost::python::dict grid_encode( mapnik::grid_view const& grid, std::string const& format, bool add_features, unsigned int resolution);
/* new approach: key comes from grid object
* grid size should be same as the map
* encoding, resizing handled as method on grid object
* whether features are dumped is determined by argument not 'fields'
*/
void render_layer_for_grid(mapnik::Map const& map,
mapnik::grid & grid,
unsigned layer_idx, // TODO - layer by name or index
boost::python::list const& fields)
{
std::vector<mapnik::layer> const& layers = map.layers();
std::size_t layer_num = layers.size();
if (layer_idx >= layer_num) {
std::ostringstream s;
s << "Zero-based layer index '" << layer_idx << "' not valid, only '"
<< layer_num << "' layers are in map\n";
throw std::runtime_error(s.str());
}
// convert python list to std::set
boost::python::ssize_t num_fields = boost::python::len(fields);
for(boost::python::ssize_t i=0; i<num_fields; i++) {
boost::python::extract<std::string> name(fields[i]);
if (name.check())
{
grid.add_property_name(name());
}
else
{
std::stringstream s;
s << "list of field names must be strings";
throw mapnik::value_error(s.str());
}
}
// copy property names
std::set<std::string> attributes = grid.property_names();
// todo - make this a static constant
std::string known_id_key = "__id__";
if (attributes.find(known_id_key) != attributes.end())
{
attributes.erase(known_id_key);
}
std::string join_field = grid.get_key();
if (known_id_key != join_field &&
attributes.find(join_field) == attributes.end())
{
attributes.insert(join_field);
}
mapnik::grid_renderer<mapnik::grid> ren(map,grid,1.0,0,0);
mapnik::layer const& layer = layers[layer_idx];
ren.apply(layer,attributes);
}
}
#endif
<|endoftext|> |
<commit_before>#include "Halide.h"
using namespace Halide;
class Conv3x3 : public Generator<Conv3x3> {
public:
GeneratorParam<Type> accumulator_type{"accumulator_type", Int(16)};
// Takes an 8 bit image; one channel.
Input<Buffer<uint8_t>> input{"input", 2};
Input<Buffer<int8_t>> mask{"mask", 2};
// Outputs an 8 bit image; one channel.
Output<Buffer<uint8_t>> output{"output", 2};
void generate() {
bounded_input(x, y) = BoundaryConditions::repeat_edge(input)(x, y);
Expr sum = cast(accumulator_type, 0);
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
sum += cast<int16_t>(bounded_input(x+j, y+i)) * cast<int16_t>(mask(j+1, i+1));
}
}
output(x, y) = cast<uint8_t>(clamp(sum >> 4, 0, 255));
}
void schedule() {
Var xi{"xi"}, yi{"yi"};
input.dim(0).set_min(0);
input.dim(1).set_min(0);
output.dim(0).set_min(0);
output.dim(1).set_min(0);
if (get_target().features_any_of({Target::HVX_64, Target::HVX_128})) {
const int vector_size = get_target().has_feature(Target::HVX_128) ? 128 : 64;
Expr input_stride = input.dim(1).stride();
input.dim(1).set_stride((input_stride/vector_size) * vector_size);
Expr output_stride = output_buffer.dim(1).stride();
output_buffer.dim(1).set_stride((output_stride/vector_size) * vector_size);
bounded_input.compute_root();
output
.hexagon()
.tile(x, y, xi, yi, vector_size, 4, TailStrategy::RoundUp)
.vectorize(xi)
.unroll(yi);
} else {
const int vector_size = natural_vector_size<uint8_t>();
output
.vectorize(x, vector_size)
.parallel(y, 16);
}
}
private:
Var x{"x"}, y{"y"};
Func bounded_input{"input_bounded"};
};
HALIDE_REGISTER_GENERATOR(Conv3x3, "conv3x3");
<commit_msg>update output_buffer -> output usage<commit_after>#include "Halide.h"
using namespace Halide;
class Conv3x3 : public Generator<Conv3x3> {
public:
GeneratorParam<Type> accumulator_type{"accumulator_type", Int(16)};
// Takes an 8 bit image; one channel.
Input<Buffer<uint8_t>> input{"input", 2};
Input<Buffer<int8_t>> mask{"mask", 2};
// Outputs an 8 bit image; one channel.
Output<Buffer<uint8_t>> output{"output", 2};
void generate() {
bounded_input(x, y) = BoundaryConditions::repeat_edge(input)(x, y);
Expr sum = cast(accumulator_type, 0);
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
sum += cast<int16_t>(bounded_input(x+j, y+i)) * cast<int16_t>(mask(j+1, i+1));
}
}
output(x, y) = cast<uint8_t>(clamp(sum >> 4, 0, 255));
}
void schedule() {
Var xi{"xi"}, yi{"yi"};
input.dim(0).set_min(0);
input.dim(1).set_min(0);
output.dim(0).set_min(0);
output.dim(1).set_min(0);
if (get_target().features_any_of({Target::HVX_64, Target::HVX_128})) {
const int vector_size = get_target().has_feature(Target::HVX_128) ? 128 : 64;
Expr input_stride = input.dim(1).stride();
input.dim(1).set_stride((input_stride/vector_size) * vector_size);
Expr output_stride = output.dim(1).stride();
output.dim(1).set_stride((output_stride/vector_size) * vector_size);
bounded_input.compute_root();
output
.hexagon()
.tile(x, y, xi, yi, vector_size, 4, TailStrategy::RoundUp)
.vectorize(xi)
.unroll(yi);
} else {
const int vector_size = natural_vector_size<uint8_t>();
output
.vectorize(x, vector_size)
.parallel(y, 16);
}
}
private:
Var x{"x"}, y{"y"};
Func bounded_input{"input_bounded"};
};
HALIDE_REGISTER_GENERATOR(Conv3x3, "conv3x3");
<|endoftext|> |
<commit_before>#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include "janus_io.h"
using namespace cv;
janus_image janus_read_image(const char *file)
{
Mat mat = imread(file, IMREAD_UNCHANGED);
if (!mat.data)
return NULL;
janus_image image = janus_allocate_image(mat.channels(), mat.cols, mat.rows);
assert(mat.isContinuous());
memcpy(image->data, mat.data, image->channels * image->width * image->height * sizeof(janus_data));
return image;
}
<commit_msg>first draft of opencv video decoding<commit_after>#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include "janus_io.h"
using namespace cv;
static janus_image janusFromOpenCV(const Mat &mat)
{
if (!mat.data)
return NULL;
janus_image image = janus_allocate_image(mat.channels(), mat.cols, mat.rows);
assert(mat.isContinuous());
memcpy(image->data, mat.data, image->channels * image->width * image->height * sizeof(janus_data));
return image;
}
janus_image janus_read_image(const char *file)
{
return janusFromOpenCV(imread(file, IMREAD_UNCHANGED));
}
struct janus_video_type
{
VideoCapture videoCapture;
janus_video_type(const char *file)
: videoCapture(file) {}
};
janus_video janus_open_video(const char *file)
{
return new janus_video_type(file);
}
janus_image janus_read_frame(janus_video video)
{
Mat mat;
video->videoCapture.read(mat);
return janusFromOpenCV(mat);
}
void janus_close_video(janus_video video)
{
delete video;
}
<|endoftext|> |
<commit_before>/*
==============================================================================
GridCell.cpp
Created: 23 Jan 2015 7:02:25pm
Author: Daniel Lindenfelser
==============================================================================
*/
#include "GridCell.h"
SoundboardGridCell::SoundboardGridCell(Player *p) : player(p), index(-1), progressState(true)
{
setRepaintsOnMouseActivity(true);
if (player)
{
player->getThumbnail()->addChangeListener(this);
player->addChangeListener(this);
}
}
SoundboardGridCell::~SoundboardGridCell()
{
if (player)
{
player->getThumbnail()->removeChangeListener(this);
player->removeChangeListener(this);
}
}
void SoundboardGridCell::mouseUp(const MouseEvent &event)
{
if (player)
{
Rectangle<float> loopArea(0.0f, 0.0f, getHeight() * 0.5f, getHeight() * 0.5f);
Rectangle<float> timerArea(0.0f, getHeight() - getHeight() * 0.5f, getHeight() * 0.5f, getHeight() * 0.5f);
Rectangle<float> fadeoutArea(getWidth() - getHeight() * 0.5f, 0.0f, getHeight() * 0.5f, getHeight() * 0.5f);
Rectangle<float> stopArea(getWidth() - getHeight() * 0.5f, getHeight() - getHeight() * 0.5f, getHeight() * 0.5f, getHeight() * 0.5f);
if (loopArea.contains(event.position))
{
player->setLooping(!player->isLooping());
}
else if (fadeoutArea.contains(event.position))
{
if (!player->isFading()) {
if (player->isPlaying()) {
player->startFadeOut();
} else if (player->isStopped() || player->isPaused()) {
player->startFadeIn();
}
}
}
else if (stopArea.contains(event.position))
{
player->stop();
}
else if (timerArea.contains(event.position))
{
progressState = !progressState;
}
else
{
if (player->isPlaying())
{
player->pause();
}
else
{
player->play();
}
}
repaint();
}
}
void SoundboardGridCell::paint(Graphics &g)
{
auto border = g.getClipBounds().reduced(1).toFloat();
auto cell = border.reduced(2).toFloat();
g.setColour(ThemeBackground1);
g.fillAll();
g.setColour(ThemeBackground3);
g.fillRect(border);
if (player)
{
Colour colour;
if (player->isPlayed())
{
colour = ThemeGreen;
}
else if (player->isFading())
{
colour = ThemeOrange;
}
else if (player->isLooping())
{
colour = ThemeBlue;
}
else
{
colour = ThemeYellow;
}
g.setColour(colour.withAlpha(0.2f));
g.fillRoundedRectangle(cell, 2);
g.setColour(colour.withAlpha(0.2f));
auto thumbArea = cell.reduced(0, 5).toType<int>();
if (player->getThumbnail()->getTotalLength() > 0.0)
{
player->getThumbnail()->drawChannel(g, thumbArea, 0, player->getThumbnail()->getTotalLength(), 1, 1.0f);
}
g.setColour(colour.brighter(0.4f));
g.drawHorizontalLine(static_cast<int>(g.getClipBounds().getHeight() * 0.5f - 1),
g.getClipBounds().getX() + 3.0f,
g.getClipBounds().getWidth() - 3.0f);
int iconSize = getHeight() * 0.5f;
int iconX = (getWidth() * 0.5f ) - (iconSize * 0.5f);
int iconY = (getHeight() * 0.5f) - (iconSize * 0.5f);
if (player->isPlayed())
{
FontAwesome.drawAt(g, FontAwesome.getIcon(FontAwesome_Play, iconSize, colour.withAlpha(0.9f)), iconX, iconY);
}
else if (player->isFading())
{
g.setColour(colour.withAlpha(0.5f));
g.fillRoundedRectangle(cell.getX(), cell.getY(), cell.getWidth() * player->getGain(), cell.getHeight(), 2);
FontAwesome.drawAt(g, FontAwesome.getIcon(FontAwesome_Pause, iconSize, colour.withAlpha(0.9f)), iconX, iconY);
}
else if (player->isLooping())
{
g.setColour(colour.withAlpha(0.5f));
g.fillRoundedRectangle(cell.getX(),
cell.getY(),
cell.getWidth() * player->getProgress(),
cell.getHeight(),
2);
g.setColour(colour.withAlpha(0.9f));
g.setFont(getFontAwesome(getHeight() * 0.5f));
if (player->isPlaying())
{
FontAwesome.drawAt(g, FontAwesome.getIcon(FontAwesome_Pause, iconSize, colour.withAlpha(0.9f)), iconX, iconY);
}
else
{
FontAwesome.drawAt(g, FontAwesome.getIcon(FontAwesome_Play, iconSize, colour.withAlpha(0.9f)), iconX, iconY);
}
}
else
{
g.setColour(colour.withAlpha(0.5f));
g.fillRoundedRectangle(cell.getX(),
cell.getY(),
cell.getWidth() * player->getProgress(),
cell.getHeight(),
2);
if (player->isPlaying())
{
FontAwesome.drawAt(g, FontAwesome.getIcon(FontAwesome_Pause, iconSize, colour.withAlpha(0.9f)), iconX, iconY);
}
else
{
FontAwesome.drawAt(g, FontAwesome.getIcon(FontAwesome_Play, iconSize, colour.withAlpha(0.9f)), iconX, iconY);
}
}
auto info = cell.reduced(1).toType<int>();
g.resetToDefaultState();
g.setFont(getHeight() * 0.15f);
g.setColour(ThemeForeground1);
g.drawText(player->getProgressString(progressState),
info.getX(),
info.getY(),
info.getWidth(),
info.getHeight(),
Justification::bottomLeft,
false);
g.drawText(player->getTitle(),
info.getX(),
info.getY(),
info.getWidth(),
info.getHeight(),
Justification::centredTop,
false);
if (isMouseOver(true))
{
iconSize = getHeight() * 0.25f;
Colour iconColour = colour;
g.setColour(ThemeForeground1);
auto helperRect = cell.reduced(3).toType<int>();
if (player->isLooping())
{
iconColour = colour;
}
else
{
iconColour = ThemeForeground1.withAlpha(0.5f);
}
FontAwesome.drawAt(g, FontAwesome.getIcon(FontAwesome_Refresh, iconSize, iconColour),
helperRect.getX(),
helperRect.getY());
if (player->isPlayed())
{
FontAwesome.drawAt(g, FontAwesome.getIcon(FontAwesome_Square_O, iconSize, colour),
helperRect.getWidth() - iconSize + helperRect.getX(),
helperRect.getHeight() - iconSize + + helperRect.getY());
}
else
{
if (!player->isPaused() && !player->isPlaying())
{
iconColour = ThemeForeground1.withAlpha(0.25f);
}
else
{
iconColour = ThemeForeground1.withAlpha(0.5f);
}
FontAwesome.drawAt(g, FontAwesome.getIcon(FontAwesome_Square, iconSize, colour),
helperRect.getWidth() - iconSize + helperRect.getX(),
helperRect.getHeight() - iconSize + + helperRect.getY());
}
Icon icon;
if (player->isFading())
{
iconColour = colour;
}
else
{
iconColour = ThemeForeground1.withAlpha(0.5f);
}
if (player->isPlaying()) {
icon = FontAwesome_Sort_Amount_Desc;
} else {
icon = FontAwesome_Sort_Amount_Asc;
}
FontAwesome.drawAt(g, FontAwesome.getRotatedIcon(icon, iconSize, iconColour, 0.5f),
helperRect.getWidth() - iconSize + helperRect.getX(),
helperRect.getX());
}
}
else
{
g.setColour(ThemeForeground2);
g.drawHorizontalLine(static_cast<int>(g.getClipBounds().getHeight() * 0.5f - 1),
g.getClipBounds().getX() + 3.0f,
g.getClipBounds().getWidth() - 3.0f);
}
}
void SoundboardGridCell::changeListenerCallback(ChangeBroadcaster * /*source*/)
{
repaint();
}
void SoundboardGridCell::setIndex(int value)
{
index = value;
}
int SoundboardGridCell::getIndex()
{
return index;
}
<commit_msg>fix wrong color usage<commit_after>/*
==============================================================================
GridCell.cpp
Created: 23 Jan 2015 7:02:25pm
Author: Daniel Lindenfelser
==============================================================================
*/
#include "GridCell.h"
SoundboardGridCell::SoundboardGridCell(Player *p) : player(p), index(-1), progressState(true)
{
setRepaintsOnMouseActivity(true);
if (player)
{
player->getThumbnail()->addChangeListener(this);
player->addChangeListener(this);
}
}
SoundboardGridCell::~SoundboardGridCell()
{
if (player)
{
player->getThumbnail()->removeChangeListener(this);
player->removeChangeListener(this);
}
}
void SoundboardGridCell::mouseUp(const MouseEvent &event)
{
if (player)
{
Rectangle<float> loopArea(0.0f, 0.0f, getHeight() * 0.5f, getHeight() * 0.5f);
Rectangle<float> timerArea(0.0f, getHeight() - getHeight() * 0.5f, getHeight() * 0.5f, getHeight() * 0.5f);
Rectangle<float> fadeoutArea(getWidth() - getHeight() * 0.5f, 0.0f, getHeight() * 0.5f, getHeight() * 0.5f);
Rectangle<float> stopArea(getWidth() - getHeight() * 0.5f, getHeight() - getHeight() * 0.5f, getHeight() * 0.5f, getHeight() * 0.5f);
if (loopArea.contains(event.position))
{
player->setLooping(!player->isLooping());
}
else if (fadeoutArea.contains(event.position))
{
if (!player->isFading()) {
if (player->isPlaying()) {
player->startFadeOut();
} else if (player->isStopped() || player->isPaused()) {
player->startFadeIn();
}
}
}
else if (stopArea.contains(event.position))
{
player->stop();
}
else if (timerArea.contains(event.position))
{
progressState = !progressState;
}
else
{
if (player->isPlaying())
{
player->pause();
}
else
{
player->play();
}
}
repaint();
}
}
void SoundboardGridCell::paint(Graphics &g)
{
auto border = g.getClipBounds().reduced(1).toFloat();
auto cell = border.reduced(2).toFloat();
g.setColour(ThemeBackground1);
g.fillAll();
g.setColour(ThemeBackground3);
g.fillRect(border);
if (player)
{
Colour colour;
if (player->isPlayed())
{
colour = ThemeGreen;
}
else if (player->isFading())
{
colour = ThemeOrange;
}
else if (player->isLooping())
{
colour = ThemeBlue;
}
else
{
colour = ThemeYellow;
}
g.setColour(colour.withAlpha(0.2f));
g.fillRoundedRectangle(cell, 2);
g.setColour(colour.withAlpha(0.2f));
auto thumbArea = cell.reduced(0, 5).toType<int>();
if (player->getThumbnail()->getTotalLength() > 0.0)
{
player->getThumbnail()->drawChannel(g, thumbArea, 0, player->getThumbnail()->getTotalLength(), 1, 1.0f);
}
g.setColour(colour.brighter(0.4f));
g.drawHorizontalLine(static_cast<int>(g.getClipBounds().getHeight() * 0.5f - 1),
g.getClipBounds().getX() + 3.0f,
g.getClipBounds().getWidth() - 3.0f);
int iconSize = getHeight() * 0.5f;
int iconX = (getWidth() * 0.5f ) - (iconSize * 0.5f);
int iconY = (getHeight() * 0.5f) - (iconSize * 0.5f);
if (player->isPlayed())
{
FontAwesome.drawAt(g, FontAwesome.getIcon(FontAwesome_Play, iconSize, colour.withAlpha(0.9f)), iconX, iconY);
}
else if (player->isFading())
{
g.setColour(colour.withAlpha(0.5f));
g.fillRoundedRectangle(cell.getX(), cell.getY(), cell.getWidth() * player->getGain(), cell.getHeight(), 2);
FontAwesome.drawAt(g, FontAwesome.getIcon(FontAwesome_Pause, iconSize, colour.withAlpha(0.9f)), iconX, iconY);
}
else if (player->isLooping())
{
g.setColour(colour.withAlpha(0.5f));
g.fillRoundedRectangle(cell.getX(),
cell.getY(),
cell.getWidth() * player->getProgress(),
cell.getHeight(),
2);
g.setColour(colour.withAlpha(0.9f));
g.setFont(getFontAwesome(getHeight() * 0.5f));
if (player->isPlaying())
{
FontAwesome.drawAt(g, FontAwesome.getIcon(FontAwesome_Pause, iconSize, colour.withAlpha(0.9f)), iconX, iconY);
}
else
{
FontAwesome.drawAt(g, FontAwesome.getIcon(FontAwesome_Play, iconSize, colour.withAlpha(0.9f)), iconX, iconY);
}
}
else
{
g.setColour(colour.withAlpha(0.5f));
g.fillRoundedRectangle(cell.getX(),
cell.getY(),
cell.getWidth() * player->getProgress(),
cell.getHeight(),
2);
if (player->isPlaying())
{
FontAwesome.drawAt(g, FontAwesome.getIcon(FontAwesome_Pause, iconSize, colour.withAlpha(0.9f)), iconX, iconY);
}
else
{
FontAwesome.drawAt(g, FontAwesome.getIcon(FontAwesome_Play, iconSize, colour.withAlpha(0.9f)), iconX, iconY);
}
}
auto info = cell.reduced(1).toType<int>();
g.resetToDefaultState();
g.setFont(getHeight() * 0.15f);
g.setColour(ThemeForeground1);
g.drawText(player->getProgressString(progressState),
info.getX(),
info.getY(),
info.getWidth(),
info.getHeight(),
Justification::bottomLeft,
false);
g.drawText(player->getTitle(),
info.getX(),
info.getY(),
info.getWidth(),
info.getHeight(),
Justification::centredTop,
false);
if (isMouseOver(true))
{
iconSize = getHeight() * 0.25f;
Colour iconColour = colour.withAlpha(0.9f);
g.setColour(ThemeForeground1);
auto helperRect = cell.reduced(3).toType<int>();
if (player->isLooping())
{
iconColour = colour.withAlpha(0.9f);
}
else
{
iconColour = ThemeForeground1.withAlpha(0.5f);
}
FontAwesome.drawAt(g, FontAwesome.getIcon(FontAwesome_Refresh, iconSize, iconColour),
helperRect.getX(),
helperRect.getY());
if (player->isPlayed())
{
FontAwesome.drawAt(g, FontAwesome.getIcon(FontAwesome_Square_O, iconSize, colour),
helperRect.getWidth() - iconSize + helperRect.getX(),
helperRect.getHeight() - iconSize + + helperRect.getY());
}
else
{
if (!player->isPaused() && !player->isPlaying())
{
iconColour = ThemeForeground1.withAlpha(0.25f);
}
else
{
iconColour = ThemeForeground1.withAlpha(0.5f);
}
FontAwesome.drawAt(g, FontAwesome.getIcon(FontAwesome_Square, iconSize, iconColour),
helperRect.getWidth() - iconSize + helperRect.getX(),
helperRect.getHeight() - iconSize + + helperRect.getY());
}
Icon icon;
if (player->isFading())
{
iconColour = colour.withAlpha(0.9f);
}
else
{
iconColour = ThemeForeground1.withAlpha(0.5f);
}
if (player->isPlaying()) {
icon = FontAwesome_Sort_Amount_Desc;
} else {
icon = FontAwesome_Sort_Amount_Asc;
}
FontAwesome.drawAt(g, FontAwesome.getRotatedIcon(icon, iconSize, iconColour, 0.5f),
helperRect.getWidth() - iconSize + helperRect.getX(),
helperRect.getX());
}
}
else
{
g.setColour(ThemeForeground2);
g.drawHorizontalLine(static_cast<int>(g.getClipBounds().getHeight() * 0.5f - 1),
g.getClipBounds().getX() + 3.0f,
g.getClipBounds().getWidth() - 3.0f);
}
}
void SoundboardGridCell::changeListenerCallback(ChangeBroadcaster * /*source*/)
{
repaint();
}
void SoundboardGridCell::setIndex(int value)
{
index = value;
}
int SoundboardGridCell::getIndex()
{
return index;
}
<|endoftext|> |
<commit_before>// glfwTest2VS.cpp : main project file.
#include "stdafx.h"
#include <iostream>
//using namespace std;
// GLEW
#define GLEW_STATIC
#include <GL/glew.h>
#include "Shader.h"
#include "SerialClass.h"
#include "Leap.h"
// GLFW
#include <GLFW/glfw3.h>
#include <SOIL/SOIL.h>
using namespace Leap;
// Function prototypes
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);
void arduinoTest();
void leapTest();
class SampleListener : public Leap::Listener {
public:
virtual void onConnect(const Leap::Controller&);
virtual void onFrame(const Leap::Controller&);
};
void SampleListener::onConnect(const Leap::Controller& controller) {
std::cout << "Connected" << std::endl;
}
void SampleListener::onFrame(const Leap::Controller& controller) {
//std::cout << "Frame available" << std::endl;
}
SampleListener listener;
Controller controller;
// The MAIN function, from here we start our application and run our Program/Game loop
int main()
{
// Init GLFW
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
GLFWwindow* window = glfwCreateWindow(800, 600, "RIVRVS", nullptr, nullptr); // Windowed
glfwMakeContextCurrent(window);
// Set the required callback functions
glfwSetKeyCallback(window, key_callback);
// Initialize GLEW to setup the OpenGL Function pointers
glewExperimental = GL_TRUE;
glewInit();
// Define the viewport dimensions
glViewport(0, 0, 800, 600);
Shader ourShader("VertexShader.vert", "FragmentShader.frag");
// Set up our vertex data (and buffer(s)) and attribute pointers
GLfloat vertices[] = {
//positions //colors
0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f
};
GLuint VBO, VAO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
// Bind our Vertex Array Object first, then bind and set our buffers and pointers.
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
//position attributes
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
//color attribute
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(1);
glBindVertexArray(0); // Unbind VAO (it's always a good thing to unbind any buffer/array to prevent strange bugs)
// glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
controller.setPolicy(Leap::Controller::POLICY_IMAGES);
controller.addListener(listener);
// Game loop
while (!glfwWindowShouldClose(window))
{
// Check and call events
glfwPollEvents();
// Render
// Clear the colorbuffer
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// activates shader
ourShader.Use();
GLfloat yOffset = 0.5f;
glUniform1f(glGetUniformLocation(ourShader.Program, "yOffset"), 1.0f);
//Draw the triangle
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 3);
glBindVertexArray(0);
// Swap the buffers
glfwSwapBuffers(window);
}
glfwTerminate();
return 0;
}
void arduinoTest(){
printf("Welcome to the serial test app!\n\n");
Serial* SP = new Serial("\\\\.\\COM3"); // adjust as needed
if (SP->IsConnected()){
std::cout << "We're connected" << std::endl;
}
else{
std::cout << "Failed to connect" << std::endl;
}
SP->WriteData("3", 256);
}
void leapTest(){
Frame frame = controller.frame();
ImageList images = frame.images();
Image image = images[0];
const unsigned char* image_buffer = image.data();
// std::cout << "Image" << 0 << " : " << image.width() << std::endl;
std::cout << image << std::endl;
if (image.width() > 1){
std::cout << "width : " << image.width() << " height: " << image.height() << std::endl;
SOIL_save_image("TestImage.bmp",1, image.width(), image.height(),1, image_buffer);
}
}
// Is called whenever a key is pressed/released via GLFW
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
if (key == GLFW_KEY_SPACE && action == GLFW_PRESS){
//arduinoTest();
leapTest();
}
if (key == GLFW_KEY_M && action == GLFW_PRESS){
}
}
<commit_msg>Minor changed to rivrs<commit_after>// glfwTest2VS.cpp : main project file.
#include "stdafx.h"
#include <iostream>
//using namespace std;
// GLEW
#define GLEW_STATIC
#include <GL/glew.h>
#include "Shader.h"
#include "SerialClass.h"
#include "Leap.h"
// GLFW
#include <GLFW/glfw3.h>
#include <SOIL/SOIL.h>
using namespace Leap;
// Function prototypes
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);
void arduinoTest();
void leapTest();
class SampleListener : public Leap::Listener {
public:
virtual void onConnect(const Leap::Controller&);
virtual void onFrame(const Leap::Controller&);
};
void SampleListener::onConnect(const Leap::Controller& controller) {
std::cout << "Connected" << std::endl;
}
void SampleListener::onFrame(const Leap::Controller& controller) {
//std::cout << "Frame available" << std::endl;
}
SampleListener listener;
Controller controller;
// The MAIN function, from here we start our application and run our Program/Game loop
int main()
{
// Init GLFW
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
GLFWwindow* window = glfwCreateWindow(800, 600, "RIVRVS", nullptr, nullptr); // Windowed
glfwMakeContextCurrent(window);
// Set the required callback functions
glfwSetKeyCallback(window, key_callback);
// Initialize GLEW to setup the OpenGL Function pointers
glewExperimental = GL_TRUE;
glewInit();
// Define the viewport dimensions
glViewport(0, 0, 800, 600);
Shader ourShader("VertexShader.vert", "FragmentShader.frag");
// Set up our vertex data (and buffer(s)) and attribute pointers
GLfloat vertices[] = {
//positions //colors
0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f
};
GLuint VBO, VAO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
// Bind our Vertex Array Object first, then bind and set our buffers and pointers.
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
//position attributes
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
//color attribute
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(1);
glBindVertexArray(0); // Unbind VAO (it's always a good thing to unbind any buffer/array to prevent strange bugs)
// glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
controller.setPolicy(Leap::Controller::POLICY_IMAGES);
controller.addListener(listener);
// Game loop
while (!glfwWindowShouldClose(window))
{
// Check and call events
glfwPollEvents();
// Render
// Clear the colorbuffer
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// activates shader
ourShader.Use();
GLfloat yOffset = 0.5f;
glUniform1f(glGetUniformLocation(ourShader.Program, "yOffset"), 1.0f);
//Draw the triangle
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 3);
glBindVertexArray(0);
// Swap the buffers
glfwSwapBuffers(window);
}
glfwTerminate();
return 0;
}
void arduinoTest(){
printf("Welcome to the serial test app!\n\n");
Serial* SP = new Serial("\\\\.\\COM3"); // adjust as needed
if (SP->IsConnected()){
std::cout << "We're connected" << std::endl;
}
else{
std::cout << "Failed to connect" << std::endl;
}
SP->WriteData("3", 256);
}
void leapTest(){
Frame frame = controller.frame();
ImageList images = frame.images();
Image image = images[0];
const unsigned char* image_buffer = image.data();
// std::cout << "Image" << 0 << " : " << image.width() << std::endl;
std::cout << image << std::endl;
if (image.width() > 1){
std::cout << "width : " << image.width() << " height: " << image.height() << std::endl;
SOIL_save_image("TestImage.bmp",1, image.width(), image.height(),1, image_buffer);
}
}
// Is called whenever a key is pressed/released via GLFW
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
if (key == GLFW_KEY_SPACE && action == GLFW_PRESS){
arduinoTest();
//leapTest();
}
if (key == GLFW_KEY_M && action == GLFW_PRESS){
}
}
<|endoftext|> |
<commit_before>/*-
* Copyright (c) 2005-2008 Benjamin Close <Benjamin.Close@clearchain.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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 <string.h>
#ifdef WIN32
#include <strstream>
#else /* UNIX */
#include <iostream>
#include <unistd.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <errno.h>
#endif
#include "Socket.h"
namespace wcl {
/**
* For Win32 winsock needs to be initialised before
* we can use the subsystem. This is done in the first constructor call to
* Socket. But we need to know if it's been done or not
*/
#ifdef WIN32
static bool win32init = false;
static WORD sockVersion = MAKEWORD(1,1); // We'd like Winsock version 1.1
static WSADATA wsaData;
#endif
/**
* Constructor, create a socket which has not yet got a file descriptor
* allocated to it. This can only be called by subclasses to its the sub classes
* responsibility to create the socket.
*/
Socket::Socket():
sockfd(-1),blocking(BLOCKING)
{
memset( &this->address, 0, sizeof( this->address ));
#ifdef WIN32
if(!win32init){
WSAStartup(sockVersion, &wsaData);
win32init=true;
}
#endif
#if defined(__linux) || defined(MACOSX)
/* Block the SIGPIPE signal to avoid it being sent when a read on a closed socket happens */
sigset_t mask;
/* Initialise the signal mask */
sigemptyset(&mask);
/* Add the new signal to the mask */
sigaddset(&mask, SIGPIPE);
/* Set the new signal to be blocked */
sigprocmask(SIG_BLOCK, &mask, NULL);
#endif
}
/**
* Destructor, this closes the socket if its open
*/
Socket::~Socket()
{
if ( this->isValid()){
this->close();
}
}
/**
* Close the socket if it is open
*/
void Socket::close()
{
if ( this->isValid()){
#ifdef WIN32
::closesocket( this->sockfd );
#else
::close( this->sockfd );
#endif
this->sockfd = -1;
}
}
/**
* Indicate if the socket object is valid.
* This is a lightweight call that checks class internals only
*
* @return true if the socket object is valid, false if it is not
*/
bool Socket::isValid() const
{
return (this->sockfd != -1);
}
/**
* Bind the socket to a given port on any address of the local host
*
* @param port The port to bind the socket to
* @return true if the bind was successful, false if socket was invalid or the bind failed
*/
bool Socket::bind( const unsigned port )
{
if ( !this->isValid()){
return false;
}
this->address.sin_family = AF_INET;
this->address.sin_addr.s_addr = INADDR_ANY;
this->address.sin_port = htons ( port );
if ( ::bind ( this->sockfd, (struct sockaddr *)&this->address, sizeof(this->address)) == -1 ){
return false;
}
return true;
}
/**
* Attempt to read data from a socket into a buffer. This method
* will read data and return as soon as it can. It will not block until
* the given size has been read. If you want this functionality use readuntil.
* If the remote socket is closed a SocketException is thrown.
*
* @param buffer The buffer to read into
* @param size The size of the buffer
* @return The amount of data read if all ok, -1 on a read error, not caused
* by the close of a socket, 0 on a graceful close Note, the amount
* of data actually read may not match what you requested. This function
* will return as soon as some data has been read
* @throws SocketException if the remote end has forcable closed the socket
*/
ssize_t Socket::read ( void *buffer, size_t size )
{
if ( !isValid()){
return -1;
}
#ifdef WIN32
ssize_t retval = ::recv(this->sockfd, (char*)buffer, size, 0x0);
if( retval == SOCKET_ERROR ){
throw new SocketException(this);
}
return retval;
#else
ssize_t retval = ::read(this->sockfd, buffer, size );
if ( retval == -1 && errno == ECONNRESET){
throw new SocketException(this);
}
return retval;
#endif
}
/**
* Attempt to read data from a socket into a buffer. This method
* will block until the requested size has been read. If you don't want
* the socket to block, (even if it's nonblocking) use read. Please note
* if using this on a blocking socket, it will act like a busy loop thrashing.
*
* @param buffer The buffer to read into
* @param size The amount of data to read, the buffer msut be at least this size
* @throws SocketException if the remote end has forcable closed the socket
*/
void Socket::readUntil ( void *buffer, size_t size )
{
ssize_t amount;
while( size > 0 ){
amount = this->read( buffer, size );
// We just can't increment a void * pointer as we don't know what it is
// pointing too. However, we know that ::read returns in bytes so we
// cast to a type which can be validly incremented
buffer = amount + (uint8_t *)buffer;
size-=amount;
}
}
/**
* Will attempt to write to a socket form a buffer. This method will block
* until the requested size has been written.
*
* @param buffer The buffer to read from.
* @param size The amount of data to write, the buffer must be at least this size.
* @throws SocketException if the remote peer has forced the socket closes.
*/
void Socket::writeUntil ( void *buffer, size_t size )
{
ssize_t amount;
while( size > 0 ){
amount = this->write( buffer, size );
// We just can't increment a void * pointer as we don't know what it is
// pointing too. However, we know that ::read returns in bytes so we
// cast to a type which can be validly incremented
buffer = amount + (uint8_t *)buffer;
size-=amount;
}
}
/**
* Attempt to write size characters from buffer to the socket.
* This method throws an exception if the remote end has forcable closed
* the socket.
*
* @param buffer The buffer containing the data to write
* @param size The amount of characters to write, the buffer must be this big
* @return The amount of charaters written
* @throws SockcetException if the remote peer has forced the socket * closed
*/
ssize_t Socket::write( const void *buffer, size_t size )
{
if ( !isValid()){
return -1;
}
#ifdef WIN32
ssize_t retval = ::send(this->sockfd, (const char *)buffer, size, 0x0);
if ( retval == SOCKET_ERROR ){
throw new SocketException(this);
}
return retval;
#else
ssize_t retval = ::write( this->sockfd, buffer, size );
if ( retval == -1 ){
throw new SocketException(this);
}
return retval;
#endif
}
/**
* Write the given string to the socket.
*
* @param string The string to write
* @return -1 if the socket is invalid, or the number of bytes written otherwise
* @throws SocketException if the write fails.
*/
ssize_t Socket::write( const std::string &string )
{
return this->write( string.c_str(), string.size());
}
/**
* Set the blocking mode of this socket.
* The blocking mode of a socket indicates whether read / accept / write calls will
* block. Win32 does not support non blocking sockets without a HWND hence this library doesnt
*
* @param mode The mode to set this socket too
* @return true if the call was successful, false otherwise
*/
bool Socket::setBlockingMode( const BlockingMode mode)
{
int flags;
if ( !isValid()){
return false;
}
#ifdef WIN32
/**
* Windows does non blocking very, very differently.
* hence we don't support it. We return false to indicate this.
*/
return false;
#else /* UNIX */
// In order to set the blocking flag, we must be careful not
// to stop on any other flags that have been set. Hence
// we obtain all the flags and adjust the blocking flag only
flags = ::fcntl(this->sockfd, F_GETFL, 0 /* ALLFLAGS */);
switch( mode ) {
case BLOCKING:
flags &=~O_NONBLOCK;
if ( ::fcntl( this->sockfd, F_SETFL, flags ) == 0 ){
this->blocking = mode;
return true;
}
break;
case NONBLOCKING:
flags |= O_NONBLOCK;
if ( ::fcntl( this->sockfd, F_SETFL, flags ) == 0 ){
this->blocking = mode;
return true;
}
break;
}
return false;
#endif
}
/**
* Obtain whether the socket is set to blocking or non blocking mode.
* Note: A windows socket will always be blocking
*
* @return BLOCKING or NONBLOCKING depending on the socket state, if the socket has not been setup
* then it is in the default state of BLOCKING.
*/
Socket::BlockingMode Socket::getBlockingMode() const
{
return this->blocking;
}
/**
* Return the file descriptor associated with this socket
*
* @return the socket descriptor, -1 if its in error
*/
int Socket::operator *() const
{
return this->sockfd;
}
/**
* Obtain the amount of bytes currently available for reading
*
* @return The amount of bytes available or 0 if the socket is closed
* @throws SocketException if the remote has closed the socket
*/
ssize_t Socket::getAvailableCount()
{
ssize_t bytesAvailable;
int status = ioctl (this->socketfd, FIONREAD, &bytesAvailable);
if ( status == -1 && errno == ECONNRESET){
throw new SocketException(this);
}
return bytesAvailable;
}
/*==============================================================================
*
* SocketException Class Methods
*
*=============================================================================*/
/**
* Construct a socket exception with the specified reason
*
* @param reason The reason the exception occurred
*/
SocketException::SocketException( const Socket *s )
{
this->sockid = **s;
#ifdef WIN32
this->errornumber = WSAGetLastError();
#else
this->errornumber = errno; /* errno defined in errno.h */
#endif
}
SocketException::~SocketException()
{}
int SocketException::getCause() const
{
return this->errornumber;
}
/**
* Obtain the reason why the socket exception was
* thrown
*
* @return The reason this socket exception occurred
*/
const std::string SocketException::getReason() const
{
#ifdef WIN32
std::strstream s;
s << "Winsock Errno:";
s << this->errornumber;
s << std::ends;
return s.str();
#else
return strerror( this->errornumber );
#endif
}
} // namespace wcl
<commit_msg>network: Fix getAvailableCount() so it compiles<commit_after>/*-
* Copyright (c) 2005-2008 Benjamin Close <Benjamin.Close@clearchain.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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 <string.h>
#ifdef WIN32
#include <strstream>
#else /* UNIX */
#include <iostream>
#include <unistd.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/ioctl.h>
#endif
#include "Socket.h"
namespace wcl {
/**
* For Win32 winsock needs to be initialised before
* we can use the subsystem. This is done in the first constructor call to
* Socket. But we need to know if it's been done or not
*/
#ifdef WIN32
static bool win32init = false;
static WORD sockVersion = MAKEWORD(1,1); // We'd like Winsock version 1.1
static WSADATA wsaData;
#endif
/**
* Constructor, create a socket which has not yet got a file descriptor
* allocated to it. This can only be called by subclasses to its the sub classes
* responsibility to create the socket.
*/
Socket::Socket():
sockfd(-1),blocking(BLOCKING)
{
memset( &this->address, 0, sizeof( this->address ));
#ifdef WIN32
if(!win32init){
WSAStartup(sockVersion, &wsaData);
win32init=true;
}
#endif
#if defined(__linux) || defined(MACOSX)
/* Block the SIGPIPE signal to avoid it being sent when a read on a closed socket happens */
sigset_t mask;
/* Initialise the signal mask */
sigemptyset(&mask);
/* Add the new signal to the mask */
sigaddset(&mask, SIGPIPE);
/* Set the new signal to be blocked */
sigprocmask(SIG_BLOCK, &mask, NULL);
#endif
}
/**
* Destructor, this closes the socket if its open
*/
Socket::~Socket()
{
if ( this->isValid()){
this->close();
}
}
/**
* Close the socket if it is open
*/
void Socket::close()
{
if ( this->isValid()){
#ifdef WIN32
::closesocket( this->sockfd );
#else
::close( this->sockfd );
#endif
this->sockfd = -1;
}
}
/**
* Indicate if the socket object is valid.
* This is a lightweight call that checks class internals only
*
* @return true if the socket object is valid, false if it is not
*/
bool Socket::isValid() const
{
return (this->sockfd != -1);
}
/**
* Bind the socket to a given port on any address of the local host
*
* @param port The port to bind the socket to
* @return true if the bind was successful, false if socket was invalid or the bind failed
*/
bool Socket::bind( const unsigned port )
{
if ( !this->isValid()){
return false;
}
this->address.sin_family = AF_INET;
this->address.sin_addr.s_addr = INADDR_ANY;
this->address.sin_port = htons ( port );
if ( ::bind ( this->sockfd, (struct sockaddr *)&this->address, sizeof(this->address)) == -1 ){
return false;
}
return true;
}
/**
* Attempt to read data from a socket into a buffer. This method
* will read data and return as soon as it can. It will not block until
* the given size has been read. If you want this functionality use readuntil.
* If the remote socket is closed a SocketException is thrown.
*
* @param buffer The buffer to read into
* @param size The size of the buffer
* @return The amount of data read if all ok, -1 on a read error, not caused
* by the close of a socket, 0 on a graceful close Note, the amount
* of data actually read may not match what you requested. This function
* will return as soon as some data has been read
* @throws SocketException if the remote end has forcable closed the socket
*/
ssize_t Socket::read ( void *buffer, size_t size )
{
if ( !isValid()){
return -1;
}
#ifdef WIN32
ssize_t retval = ::recv(this->sockfd, (char*)buffer, size, 0x0);
if( retval == SOCKET_ERROR ){
throw new SocketException(this);
}
return retval;
#else
ssize_t retval = ::read(this->sockfd, buffer, size );
if ( retval == -1 && errno == ECONNRESET){
throw new SocketException(this);
}
return retval;
#endif
}
/**
* Attempt to read data from a socket into a buffer. This method
* will block until the requested size has been read. If you don't want
* the socket to block, (even if it's nonblocking) use read. Please note
* if using this on a blocking socket, it will act like a busy loop thrashing.
*
* @param buffer The buffer to read into
* @param size The amount of data to read, the buffer msut be at least this size
* @throws SocketException if the remote end has forcable closed the socket
*/
void Socket::readUntil ( void *buffer, size_t size )
{
ssize_t amount;
while( size > 0 ){
amount = this->read( buffer, size );
// We just can't increment a void * pointer as we don't know what it is
// pointing too. However, we know that ::read returns in bytes so we
// cast to a type which can be validly incremented
buffer = amount + (uint8_t *)buffer;
size-=amount;
}
}
/**
* Will attempt to write to a socket form a buffer. This method will block
* until the requested size has been written.
*
* @param buffer The buffer to read from.
* @param size The amount of data to write, the buffer must be at least this size.
* @throws SocketException if the remote peer has forced the socket closes.
*/
void Socket::writeUntil ( void *buffer, size_t size )
{
ssize_t amount;
while( size > 0 ){
amount = this->write( buffer, size );
// We just can't increment a void * pointer as we don't know what it is
// pointing too. However, we know that ::read returns in bytes so we
// cast to a type which can be validly incremented
buffer = amount + (uint8_t *)buffer;
size-=amount;
}
}
/**
* Attempt to write size characters from buffer to the socket.
* This method throws an exception if the remote end has forcable closed
* the socket.
*
* @param buffer The buffer containing the data to write
* @param size The amount of characters to write, the buffer must be this big
* @return The amount of charaters written
* @throws SockcetException if the remote peer has forced the socket * closed
*/
ssize_t Socket::write( const void *buffer, size_t size )
{
if ( !isValid()){
return -1;
}
#ifdef WIN32
ssize_t retval = ::send(this->sockfd, (const char *)buffer, size, 0x0);
if ( retval == SOCKET_ERROR ){
throw new SocketException(this);
}
return retval;
#else
ssize_t retval = ::write( this->sockfd, buffer, size );
if ( retval == -1 ){
throw new SocketException(this);
}
return retval;
#endif
}
/**
* Write the given string to the socket.
*
* @param string The string to write
* @return -1 if the socket is invalid, or the number of bytes written otherwise
* @throws SocketException if the write fails.
*/
ssize_t Socket::write( const std::string &string )
{
return this->write( string.c_str(), string.size());
}
/**
* Set the blocking mode of this socket.
* The blocking mode of a socket indicates whether read / accept / write calls will
* block. Win32 does not support non blocking sockets without a HWND hence this library doesnt
*
* @param mode The mode to set this socket too
* @return true if the call was successful, false otherwise
*/
bool Socket::setBlockingMode( const BlockingMode mode)
{
int flags;
if ( !isValid()){
return false;
}
#ifdef WIN32
/**
* Windows does non blocking very, very differently.
* hence we don't support it. We return false to indicate this.
*/
return false;
#else /* UNIX */
// In order to set the blocking flag, we must be careful not
// to stop on any other flags that have been set. Hence
// we obtain all the flags and adjust the blocking flag only
flags = ::fcntl(this->sockfd, F_GETFL, 0 /* ALLFLAGS */);
switch( mode ) {
case BLOCKING:
flags &=~O_NONBLOCK;
if ( ::fcntl( this->sockfd, F_SETFL, flags ) == 0 ){
this->blocking = mode;
return true;
}
break;
case NONBLOCKING:
flags |= O_NONBLOCK;
if ( ::fcntl( this->sockfd, F_SETFL, flags ) == 0 ){
this->blocking = mode;
return true;
}
break;
}
return false;
#endif
}
/**
* Obtain whether the socket is set to blocking or non blocking mode.
* Note: A windows socket will always be blocking
*
* @return BLOCKING or NONBLOCKING depending on the socket state, if the socket has not been setup
* then it is in the default state of BLOCKING.
*/
Socket::BlockingMode Socket::getBlockingMode() const
{
return this->blocking;
}
/**
* Return the file descriptor associated with this socket
*
* @return the socket descriptor, -1 if its in error
*/
int Socket::operator *() const
{
return this->sockfd;
}
/**
* Obtain the amount of bytes currently available for reading
*
* @return The amount of bytes available or 0 if the socket is closed
* @throws SocketException if the remote has closed the socket
*/
ssize_t Socket::getAvailableCount()
{
ssize_t bytesAvailable;
int status = ioctl (this->sockfd, FIONREAD, &bytesAvailable);
if ( status == -1 && errno == ECONNRESET){
throw new SocketException(this);
}
return bytesAvailable;
}
/*==============================================================================
*
* SocketException Class Methods
*
*=============================================================================*/
/**
* Construct a socket exception with the specified reason
*
* @param reason The reason the exception occurred
*/
SocketException::SocketException( const Socket *s )
{
this->sockid = **s;
#ifdef WIN32
this->errornumber = WSAGetLastError();
#else
this->errornumber = errno; /* errno defined in errno.h */
#endif
}
SocketException::~SocketException()
{}
int SocketException::getCause() const
{
return this->errornumber;
}
/**
* Obtain the reason why the socket exception was
* thrown
*
* @return The reason this socket exception occurred
*/
const std::string SocketException::getReason() const
{
#ifdef WIN32
std::strstream s;
s << "Winsock Errno:";
s << this->errornumber;
s << std::ends;
return s.str();
#else
return strerror( this->errornumber );
#endif
}
} // namespace wcl
<|endoftext|> |
<commit_before>
#ifndef _SILL_MATRIX_BASE_HPP_
#define _SILL_MATRIX_BASE_HPP_
#include <sill/base/string_functions.hpp>
#include <sill/math/linear_algebra/linear_algebra_base.hpp>
#include <sill/serialization/serialize.hpp>
namespace sill {
/**
* Matrix base class
*
* @tparam T Type of data element (e.g., float).
* @tparam SizeType Type of index (e.g., arma::u32).
*/
template <typename T, typename SizeType>
class matrix_base {
// Public types
//==========================================================================
public:
typedef linear_algebra_base<T,SizeType> la_base;
typedef typename la_base::value_type value_type;
typedef typename la_base::size_type size_type;
typedef typename la_base::const_iterator const_iterator;
typedef typename la_base::iterator iterator;
typedef typename la_base::const_index_iterator const_index_iterator;
typedef typename la_base::index_iterator index_iterator;
// Constructors
//==========================================================================
//! Default constructor (for an empty matrix).
matrix_base()
: n_rows(0), n_cols(0) { }
//! Constructor for a matrix with m rows and n columns.
matrix_base(size_type m, size_type n)
: n_rows(m), n_cols(n) { }
// Serialization
//==========================================================================
void save(oarchive& ar) const {
ar << n_rows << n_cols;
}
void load(iarchive& ar) {
ar >> n_rows >> n_cols;
}
// Getters and setters: dimensions
//==========================================================================
//! Number of rows.
size_type num_rows() const { return n_rows; }
//! Number of columns.
size_type num_cols() const { return n_cols; }
//! Total number of elements (rows x columns).
//! NOTE: This is hard-coded to use size_t to support larger matrices.
size_t size() const { return (size_t)n_rows * (size_t)n_cols; }
// Utilities
//==========================================================================
//! Print to the given output stream.
virtual void print(std::ostream& out) const {
out << "[" << n_rows << " x " << n_cols << " matrix]";
}
// Operators
//==========================================================================
//! Equality operator.
bool operator==(const matrix_base& other) const {
return (n_rows == other.n_rows && n_cols == other.n_cols);
}
// Public data
//==========================================================================
//! Number of rows.
//! This is public to match Armadillo's interface.
size_type n_rows;
//! Number of columns.
//! This is public to match Armadillo's interface.
size_type n_cols;
}; // class matrix_base
template <typename T, typename SizeType>
std::ostream&
operator<<(std::ostream& out, const matrix_base<T,SizeType>& mat) {
mat.print(out);
return out;
}
} // namespace sill
#endif // #ifndef _SILL_MATRIX_BASE_HPP_
<commit_msg>adding virtual destructors<commit_after>
#ifndef _SILL_MATRIX_BASE_HPP_
#define _SILL_MATRIX_BASE_HPP_
#include <sill/base/string_functions.hpp>
#include <sill/math/linear_algebra/linear_algebra_base.hpp>
#include <sill/serialization/serialize.hpp>
namespace sill {
/**
* Matrix base class
*
* @tparam T Type of data element (e.g., float).
* @tparam SizeType Type of index (e.g., arma::u32).
*/
template <typename T, typename SizeType>
class matrix_base {
// Public types
//==========================================================================
public:
typedef linear_algebra_base<T,SizeType> la_base;
typedef typename la_base::value_type value_type;
typedef typename la_base::size_type size_type;
typedef typename la_base::const_iterator const_iterator;
typedef typename la_base::iterator iterator;
typedef typename la_base::const_index_iterator const_index_iterator;
typedef typename la_base::index_iterator index_iterator;
// Constructors
//==========================================================================
//! Default constructor (for an empty matrix).
matrix_base()
: n_rows(0), n_cols(0) { }
//! Constructor for a matrix with m rows and n columns.
matrix_base(size_type m, size_type n)
: n_rows(m), n_cols(n) { }
virtual ~matrix_base() { }
// Serialization
//==========================================================================
void save(oarchive& ar) const {
ar << n_rows << n_cols;
}
void load(iarchive& ar) {
ar >> n_rows >> n_cols;
}
// Getters and setters: dimensions
//==========================================================================
//! Number of rows.
size_type num_rows() const { return n_rows; }
//! Number of columns.
size_type num_cols() const { return n_cols; }
//! Total number of elements (rows x columns).
//! NOTE: This is hard-coded to use size_t to support larger matrices.
size_t size() const { return (size_t)n_rows * (size_t)n_cols; }
// Utilities
//==========================================================================
//! Print to the given output stream.
virtual void print(std::ostream& out) const {
out << "[" << n_rows << " x " << n_cols << " matrix]";
}
// Operators
//==========================================================================
//! Equality operator.
bool operator==(const matrix_base& other) const {
return (n_rows == other.n_rows && n_cols == other.n_cols);
}
// Public data
//==========================================================================
//! Number of rows.
//! This is public to match Armadillo's interface.
size_type n_rows;
//! Number of columns.
//! This is public to match Armadillo's interface.
size_type n_cols;
}; // class matrix_base
template <typename T, typename SizeType>
std::ostream&
operator<<(std::ostream& out, const matrix_base<T,SizeType>& mat) {
mat.print(out);
return out;
}
} // namespace sill
#endif // #ifndef _SILL_MATRIX_BASE_HPP_
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// Keyboard.cc
//------------------------------------------------------------------------------
#include "Keyboard.h"
#include <cctype>
namespace YAKC {
using namespace Oryol;
//------------------------------------------------------------------------------
static bool
is_joystick_key(Key::Code key) {
switch (key) {
case Key::Left:
case Key::Right:
case Key::Down:
case Key::Up:
case Key::Space:
return true;
default:
return false;
}
}
//------------------------------------------------------------------------------
static uint8_t
translate_special_key(const yakc* emu, Key::Code key, bool shift, bool ctrl) {
if ((emu->num_joysticks() > 0) && emu->is_joystick_enabled() && is_joystick_key(key)) {
return 0;
}
if (emu->is_system(system::any_zx)) {
switch (key) {
case Key::Space: return 0x20;
case Key::Left: return 0x08;
case Key::Right: return 0x09;
case Key::Down: return 0x0A;
case Key::Up: return 0x0B;
case Key::Enter: return 0x0D;
case Key::BackSpace: return 0x0C;
case Key::Escape: return 0x07;
case Key::LeftControl: return 0x0F; // unused, for SymShift
default: return 0;
}
}
else if (emu->is_system(system::acorn_atom)) {
// http://www.vintagecomputer.net/fjkraan/comp/atom/atap/atap03.html#131
switch (key) {
case Key::Space: return 0x20;
case Key::Left: return 0x08;
case Key::Right: return 0x09;
case Key::Down: return 0x0A;
case Key::Up: return 0x0B;
case Key::Enter: return 0x0D;
case Key::BackSpace: return 0x01;
case Key::Escape: return ctrl ? 0x1E : 0x1B; // Home, Esc
// Atom ctrl+key codes:
case Key::G: return ctrl ? 0x07:0; // Ctrl+G: bleep
case Key::H: return ctrl ? 0x08:0; // Ctrl+H: left
case Key::I: return ctrl ? 0x09:0; // Ctrl+I: right
case Key::J: return ctrl ? 0x0A:0; // Ctrl+J: down
case Key::K: return ctrl ? 0x0B:0; // Ctrl+K: up
case Key::L: return ctrl ? 0x0C:0; // Ctrl+L: formfeed
case Key::M: return ctrl ? 0x0D:0; // Ctrl+M: return
case Key::N: return ctrl ? 0x0E:0; // Ctrl+N: pagemode on
case Key::O: return ctrl ? 0x0F:0; // Ctrl+O: pagemode off
case Key::U: return ctrl ? 0x15:0; // Ctrl+U: end screen
case Key::X: return ctrl ? 0x18:0; // Ctrl+X: cancel
case Key::LeftBracket: return ctrl ? 0x1B:0; // Ctrl+[: escape
default: return 0;
}
}
else if (emu->is_system(system::any_cpc)) {
switch (key) {
case Key::Space: return 0x20;
case Key::Left: return 0x08;
case Key::Right: return 0x09;
case Key::Down: return 0x0A;
case Key::Up: return 0x0B;
case Key::Enter: return 0x0D;
case Key::LeftShift: return 0x02;
case Key::BackSpace: return shift ? 0x0C : 0x01; // 0x0C: clear screen
case Key::Escape: return shift ? 0x13 : 0x03; // 0x13: break
case Key::F1: return 0xF1;
case Key::F2: return 0xF2;
case Key::F3: return 0xF3;
case Key::F4: return 0xF4;
case Key::F5: return 0xF5;
case Key::F6: return 0xF6;
case Key::F7: return 0xF7;
case Key::F8: return 0xF8;
case Key::F9: return 0xF9;
case Key::F10: return 0xFA;
case Key::F11: return 0xFB;
case Key::F12: return 0xFC;
default: return 0;
}
}
else {
switch (key) {
case Key::Space: return 0x20;
case Key::Left: return 0x08;
case Key::Right: return 0x09;
case Key::Down: return 0x0A;
case Key::Up: return 0x0B;
case Key::Enter: return 0x0D;
case Key::BackSpace: return shift ? 0x0C : 0x01; // 0x0C: clear screen
case Key::Escape: return shift ? 0x13 : 0x03; // 0x13: break
case Key::F1: return 0xF1;
case Key::F2: return 0xF2;
case Key::F3: return 0xF3;
case Key::F4: return 0xF4;
case Key::F5: return 0xF5;
case Key::F6: return 0xF6;
case Key::F7: return 0xF7;
case Key::F8: return 0xF8;
case Key::F9: return 0xF9;
case Key::F10: return 0xFA;
case Key::F11: return 0xFB;
case Key::F12: return 0xFC;
default: return 0;
}
}
}
//------------------------------------------------------------------------------
void
Keyboard::Setup(yakc& emu_) {
o_assert_dbg(!this->emu);
this->emu = &emu_;
Input::SubscribeEvents([this](const InputEvent& e) {
if (!this->hasInputFocus) {
return;
}
if (e.Type == InputEvent::WChar) {
if ((e.WCharCode > 32) && (e.WCharCode < 127)) {
uint8_t ascii = (uint8_t) e.WCharCode;
// invert case (not on ZX or CPC machines)
if (!(this->emu->is_system(system::any_zx)||this->emu->is_system(system::any_cpc))) {
if (std::islower(ascii)) {
ascii = std::toupper(ascii);
}
else if (std::isupper(ascii)) {
ascii = std::tolower(ascii);
}
}
this->emu->on_ascii(ascii);
}
}
else if (e.Type == InputEvent::KeyDown) {
// translate any non-alphanumeric keys (Enter, Esc, cursor keys etc...)
bool shift = Input::KeyPressed(Key::LeftShift);
bool ctrl = Input::KeyPressed(Key::LeftControl);
uint8_t keycode = translate_special_key(this->emu, e.KeyCode, shift, ctrl);
if (0 != keycode) {
this->emu->on_key_down(keycode);
}
// simulated joystick
if ((this->emu->num_joysticks() > 0) && this->emu->is_joystick_enabled()) {
if (e.KeyCode == Key::Left) {
this->cur_kbd_joy |= joystick::left;
}
else if (e.KeyCode == Key::Right) {
this->cur_kbd_joy |= joystick::right;
}
else if (e.KeyCode == Key::Up) {
this->cur_kbd_joy |= joystick::up;
}
else if (e.KeyCode == Key::Down) {
this->cur_kbd_joy |= joystick::down;
}
else if (e.KeyCode == Key::Space) {
this->cur_kbd_joy |= joystick::btn0;
}
else if (e.KeyCode == Key::LeftControl) {
this->cur_kbd_joy |= joystick::btn1;
}
}
else {
this->cur_kbd_joy = 0;
}
}
else if (e.Type == InputEvent::KeyUp) {
// translate any non-alphanumeric keys (Enter, Esc, cursor keys etc...)
bool shift = Input::KeyPressed(Key::LeftShift);
bool ctrl = Input::KeyPressed(Key::LeftControl);
uint8_t keycode = translate_special_key(this->emu, e.KeyCode, shift, ctrl);
if (0 != keycode) {
this->emu->on_key_up(keycode);
}
// simulated joystick
if ((this->emu->num_joysticks() > 0) && this->emu->is_joystick_enabled()) {
if (e.KeyCode == Key::Left) {
this->cur_kbd_joy &= ~joystick::left;
}
else if (e.KeyCode == Key::Right) {
this->cur_kbd_joy &= ~joystick::right;
}
else if (e.KeyCode == Key::Up) {
this->cur_kbd_joy &= ~joystick::up;
}
else if (e.KeyCode == Key::Down) {
this->cur_kbd_joy &= ~joystick::down;
}
else if (e.KeyCode == Key::Space) {
this->cur_kbd_joy &= ~joystick::btn0;
}
else if (e.KeyCode == Key::LeftControl) {
this->cur_kbd_joy &= ~joystick::btn1;
}
}
else {
this->cur_kbd_joy = 0;
}
}
});
}
//------------------------------------------------------------------------------
void
Keyboard::Discard() {
o_assert_dbg(this->emu);
Input::UnsubscribeEvents(this->callbackId);
}
//------------------------------------------------------------------------------
void
Keyboard::HandleInput() {
o_assert_dbg(this->emu);
this->cur_pad_joy = 0;
if (this->hasInputFocus) {
// gamepad input (FIXME: add support for 2nd joystick!)
if (Input::GamepadAttached(0)) {
if (Input::GamepadButtonPressed(0, GamepadButton::A)) {
this->cur_pad_joy |= joystick::btn0;
}
if (Input::GamepadButtonPressed(0, GamepadButton::B)) {
this->cur_pad_joy |= joystick::btn1;
}
if (Input::GamepadButtonPressed(0, GamepadButton::DPadLeft)) {
this->cur_pad_joy |= joystick::left;
}
if (Input::GamepadButtonPressed(0, GamepadButton::DPadRight)) {
this->cur_pad_joy |= joystick::right;
}
if (Input::GamepadButtonPressed(0, GamepadButton::DPadUp)) {
this->cur_pad_joy |= joystick::up;
}
if (Input::GamepadButtonPressed(0, GamepadButton::DPadDown)) {
this->cur_pad_joy |= joystick::down;
}
const float deadZone = 0.3f;
float x = Input::GamepadAxisValue(0, GamepadAxis::LeftStickHori) +
Input::GamepadAxisValue(0, GamepadAxis::RightStickHori);
float y = Input::GamepadAxisValue(0, GamepadAxis::LeftStickVert) +
Input::GamepadAxisValue(0, GamepadAxis::RightStickVert);
if (x < -deadZone) {
this->cur_pad_joy |= joystick::left;
}
else if (x > deadZone) {
this->cur_pad_joy |= joystick::right;
}
if (y < -deadZone) {
this->cur_pad_joy |= joystick::up;
}
else if (y > deadZone) {
this->cur_pad_joy |= joystick::down;
}
}
if (!this->playbackBuffer.Empty()) {
this->handleTextPlayback();
}
this->emu->on_joystick(this->cur_kbd_joy, this->cur_pad_joy);
}
}
//------------------------------------------------------------------------------
void
Keyboard::StartPlayback(Buffer&& buf) {
this->playbackBuffer = std::move(buf);
this->playbackPos = 0;
}
//------------------------------------------------------------------------------
void
Keyboard::handleTextPlayback() {
if (this->playbackPos < this->playbackBuffer.Size()) {
if (this->playbackCounter-- > 0) {
this->emu->on_ascii(this->playbackChar);
}
else {
// give the system some time before the next character
this->playbackFlipFlop = !this->playbackFlipFlop;
if (this->playbackFlipFlop) {
this->playbackCounter = 4;
// feed the next character from buffer
// filter out unwanted characters and convert
do {
this->playbackChar = this->playbackBuffer.Data()[this->playbackPos++];
}
while ((this->playbackChar == '\t') || (this->playbackChar == '\r'));
if (this->playbackChar == '\n') {
this->playbackChar = 0x0D;
}
}
else {
this->playbackCounter = 4;
}
}
}
else {
this->playbackBuffer.Clear();
this->playbackPos = 0;
}
}
} // namespace YAKC
<commit_msg>fix text input streaming (fixes #31)<commit_after>//------------------------------------------------------------------------------
// Keyboard.cc
//------------------------------------------------------------------------------
#include "Keyboard.h"
#include <cctype>
namespace YAKC {
using namespace Oryol;
//------------------------------------------------------------------------------
static bool
is_joystick_key(Key::Code key) {
switch (key) {
case Key::Left:
case Key::Right:
case Key::Down:
case Key::Up:
case Key::Space:
return true;
default:
return false;
}
}
//------------------------------------------------------------------------------
static uint8_t
translate_special_key(const yakc* emu, Key::Code key, bool shift, bool ctrl) {
if ((emu->num_joysticks() > 0) && emu->is_joystick_enabled() && is_joystick_key(key)) {
return 0;
}
if (emu->is_system(system::any_zx)) {
switch (key) {
case Key::Space: return 0x20;
case Key::Left: return 0x08;
case Key::Right: return 0x09;
case Key::Down: return 0x0A;
case Key::Up: return 0x0B;
case Key::Enter: return 0x0D;
case Key::BackSpace: return 0x0C;
case Key::Escape: return 0x07;
case Key::LeftControl: return 0x0F; // unused, for SymShift
default: return 0;
}
}
else if (emu->is_system(system::acorn_atom)) {
// http://www.vintagecomputer.net/fjkraan/comp/atom/atap/atap03.html#131
switch (key) {
case Key::Space: return 0x20;
case Key::Left: return 0x08;
case Key::Right: return 0x09;
case Key::Down: return 0x0A;
case Key::Up: return 0x0B;
case Key::Enter: return 0x0D;
case Key::BackSpace: return 0x01;
case Key::Escape: return ctrl ? 0x1E : 0x1B; // Home, Esc
// Atom ctrl+key codes:
case Key::G: return ctrl ? 0x07:0; // Ctrl+G: bleep
case Key::H: return ctrl ? 0x08:0; // Ctrl+H: left
case Key::I: return ctrl ? 0x09:0; // Ctrl+I: right
case Key::J: return ctrl ? 0x0A:0; // Ctrl+J: down
case Key::K: return ctrl ? 0x0B:0; // Ctrl+K: up
case Key::L: return ctrl ? 0x0C:0; // Ctrl+L: formfeed
case Key::M: return ctrl ? 0x0D:0; // Ctrl+M: return
case Key::N: return ctrl ? 0x0E:0; // Ctrl+N: pagemode on
case Key::O: return ctrl ? 0x0F:0; // Ctrl+O: pagemode off
case Key::U: return ctrl ? 0x15:0; // Ctrl+U: end screen
case Key::X: return ctrl ? 0x18:0; // Ctrl+X: cancel
case Key::LeftBracket: return ctrl ? 0x1B:0; // Ctrl+[: escape
default: return 0;
}
}
else if (emu->is_system(system::any_cpc)) {
switch (key) {
case Key::Space: return 0x20;
case Key::Left: return 0x08;
case Key::Right: return 0x09;
case Key::Down: return 0x0A;
case Key::Up: return 0x0B;
case Key::Enter: return 0x0D;
case Key::LeftShift: return 0x02;
case Key::BackSpace: return shift ? 0x0C : 0x01; // 0x0C: clear screen
case Key::Escape: return shift ? 0x13 : 0x03; // 0x13: break
case Key::F1: return 0xF1;
case Key::F2: return 0xF2;
case Key::F3: return 0xF3;
case Key::F4: return 0xF4;
case Key::F5: return 0xF5;
case Key::F6: return 0xF6;
case Key::F7: return 0xF7;
case Key::F8: return 0xF8;
case Key::F9: return 0xF9;
case Key::F10: return 0xFA;
case Key::F11: return 0xFB;
case Key::F12: return 0xFC;
default: return 0;
}
}
else {
switch (key) {
case Key::Space: return 0x20;
case Key::Left: return 0x08;
case Key::Right: return 0x09;
case Key::Down: return 0x0A;
case Key::Up: return 0x0B;
case Key::Enter: return 0x0D;
case Key::BackSpace: return shift ? 0x0C : 0x01; // 0x0C: clear screen
case Key::Escape: return shift ? 0x13 : 0x03; // 0x13: break
case Key::F1: return 0xF1;
case Key::F2: return 0xF2;
case Key::F3: return 0xF3;
case Key::F4: return 0xF4;
case Key::F5: return 0xF5;
case Key::F6: return 0xF6;
case Key::F7: return 0xF7;
case Key::F8: return 0xF8;
case Key::F9: return 0xF9;
case Key::F10: return 0xFA;
case Key::F11: return 0xFB;
case Key::F12: return 0xFC;
default: return 0;
}
}
}
//------------------------------------------------------------------------------
void
Keyboard::Setup(yakc& emu_) {
o_assert_dbg(!this->emu);
this->emu = &emu_;
Input::SubscribeEvents([this](const InputEvent& e) {
if (!this->hasInputFocus) {
return;
}
if (e.Type == InputEvent::WChar) {
if ((e.WCharCode > 32) && (e.WCharCode < 127)) {
uint8_t ascii = (uint8_t) e.WCharCode;
// invert case (not on ZX or CPC machines)
if (!(this->emu->is_system(system::any_zx)||this->emu->is_system(system::any_cpc))) {
if (std::islower(ascii)) {
ascii = std::toupper(ascii);
}
else if (std::isupper(ascii)) {
ascii = std::tolower(ascii);
}
}
this->emu->on_ascii(ascii);
}
}
else if (e.Type == InputEvent::KeyDown) {
// translate any non-alphanumeric keys (Enter, Esc, cursor keys etc...)
bool shift = Input::KeyPressed(Key::LeftShift);
bool ctrl = Input::KeyPressed(Key::LeftControl);
uint8_t keycode = translate_special_key(this->emu, e.KeyCode, shift, ctrl);
if (0 != keycode) {
this->emu->on_key_down(keycode);
}
// simulated joystick
if ((this->emu->num_joysticks() > 0) && this->emu->is_joystick_enabled()) {
if (e.KeyCode == Key::Left) {
this->cur_kbd_joy |= joystick::left;
}
else if (e.KeyCode == Key::Right) {
this->cur_kbd_joy |= joystick::right;
}
else if (e.KeyCode == Key::Up) {
this->cur_kbd_joy |= joystick::up;
}
else if (e.KeyCode == Key::Down) {
this->cur_kbd_joy |= joystick::down;
}
else if (e.KeyCode == Key::Space) {
this->cur_kbd_joy |= joystick::btn0;
}
else if (e.KeyCode == Key::LeftControl) {
this->cur_kbd_joy |= joystick::btn1;
}
}
else {
this->cur_kbd_joy = 0;
}
}
else if (e.Type == InputEvent::KeyUp) {
// translate any non-alphanumeric keys (Enter, Esc, cursor keys etc...)
bool shift = Input::KeyPressed(Key::LeftShift);
bool ctrl = Input::KeyPressed(Key::LeftControl);
uint8_t keycode = translate_special_key(this->emu, e.KeyCode, shift, ctrl);
if (0 != keycode) {
this->emu->on_key_up(keycode);
}
// simulated joystick
if ((this->emu->num_joysticks() > 0) && this->emu->is_joystick_enabled()) {
if (e.KeyCode == Key::Left) {
this->cur_kbd_joy &= ~joystick::left;
}
else if (e.KeyCode == Key::Right) {
this->cur_kbd_joy &= ~joystick::right;
}
else if (e.KeyCode == Key::Up) {
this->cur_kbd_joy &= ~joystick::up;
}
else if (e.KeyCode == Key::Down) {
this->cur_kbd_joy &= ~joystick::down;
}
else if (e.KeyCode == Key::Space) {
this->cur_kbd_joy &= ~joystick::btn0;
}
else if (e.KeyCode == Key::LeftControl) {
this->cur_kbd_joy &= ~joystick::btn1;
}
}
else {
this->cur_kbd_joy = 0;
}
}
});
}
//------------------------------------------------------------------------------
void
Keyboard::Discard() {
o_assert_dbg(this->emu);
Input::UnsubscribeEvents(this->callbackId);
}
//------------------------------------------------------------------------------
void
Keyboard::HandleInput() {
o_assert_dbg(this->emu);
this->cur_pad_joy = 0;
if (this->hasInputFocus) {
// gamepad input (FIXME: add support for 2nd joystick!)
if (Input::GamepadAttached(0)) {
if (Input::GamepadButtonPressed(0, GamepadButton::A)) {
this->cur_pad_joy |= joystick::btn0;
}
if (Input::GamepadButtonPressed(0, GamepadButton::B)) {
this->cur_pad_joy |= joystick::btn1;
}
if (Input::GamepadButtonPressed(0, GamepadButton::DPadLeft)) {
this->cur_pad_joy |= joystick::left;
}
if (Input::GamepadButtonPressed(0, GamepadButton::DPadRight)) {
this->cur_pad_joy |= joystick::right;
}
if (Input::GamepadButtonPressed(0, GamepadButton::DPadUp)) {
this->cur_pad_joy |= joystick::up;
}
if (Input::GamepadButtonPressed(0, GamepadButton::DPadDown)) {
this->cur_pad_joy |= joystick::down;
}
const float deadZone = 0.3f;
float x = Input::GamepadAxisValue(0, GamepadAxis::LeftStickHori) +
Input::GamepadAxisValue(0, GamepadAxis::RightStickHori);
float y = Input::GamepadAxisValue(0, GamepadAxis::LeftStickVert) +
Input::GamepadAxisValue(0, GamepadAxis::RightStickVert);
if (x < -deadZone) {
this->cur_pad_joy |= joystick::left;
}
else if (x > deadZone) {
this->cur_pad_joy |= joystick::right;
}
if (y < -deadZone) {
this->cur_pad_joy |= joystick::up;
}
else if (y > deadZone) {
this->cur_pad_joy |= joystick::down;
}
}
if (!this->playbackBuffer.Empty()) {
this->handleTextPlayback();
}
this->emu->on_joystick(this->cur_kbd_joy, this->cur_pad_joy);
}
}
//------------------------------------------------------------------------------
void
Keyboard::StartPlayback(Buffer&& buf) {
this->playbackBuffer = std::move(buf);
this->playbackPos = 0;
}
//------------------------------------------------------------------------------
void
Keyboard::handleTextPlayback() {
if (this->playbackPos < this->playbackBuffer.Size()) {
// give the system some time between characters
if (this->playbackCounter-- == 0) {
this->playbackCounter = 10;
// feed the next character from buffer
// filter out unwanted characters and convert
uint8_t chr = this->playbackBuffer.Data()[this->playbackPos++];
if (chr != '\t' && chr != '\r') {
if (chr == '\n') {
chr = 0x0D;
}
this->emu->on_ascii(chr);
}
}
}
else {
this->playbackBuffer.Clear();
this->playbackPos = 0;
}
}
} // namespace YAKC
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <stdexcept>
#include <iostream>
#include <boost/math/special_functions/gamma.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <stan/math/functions/lgamma.hpp>
TEST(MathsSpecialFunctions, lgamma) {
// only brought in for Posix and ANSI C99
// no need to include anything on thse compilers
// see: http://www.johndcook.com/cpp_gamma.html
EXPECT_TRUE(boost::math::isinf(lgamma(0.0)));
}
TEST(MathsSpecialFunctions, lgammaStanMath) {
EXPECT_THROW(stan::math::lgamma(0.0), std::domain_error);
}
TEST(MathsSpecialFunctions, lgammaStanMathUsing) {
using stan::math::lgamma;
EXPECT_THROW(lgamma(0.0), std::domain_error);
}
TEST(MathsSpecialFunctions, lgammaUsingBoost) {
using boost::math::lgamma;
EXPECT_THROW(lgamma(0.0),std::domain_error);
}
TEST(MathsSpecialFunctions, lgammaExplicitBoost) {
EXPECT_THROW(boost::math::lgamma(0.0), std::domain_error);
}
// C++ 11 now
// TEST(MathsSpecialFunctions, lgammaExplicitStd) {
// EXPECT_NO_THROW(std::lgamma(0.0));
// }
<commit_msg>added NaN test for lgamma<commit_after>#include <stan/math/functions/lgamma.hpp>
#include <boost/math/special_functions/gamma.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <gtest/gtest.h>
TEST(MathFunctions, lgamma) {
// only brought in for Posix and ANSI C99
// no need to include anything on thse compilers
// see: http://www.johndcook.com/cpp_gamma.html
EXPECT_TRUE(boost::math::isinf(lgamma(0.0)));
}
TEST(MathFunctions, lgammaStanMath) {
EXPECT_THROW(stan::math::lgamma(0.0), std::domain_error);
}
TEST(MathFunctions, lgammaStanMathUsing) {
using stan::math::lgamma;
EXPECT_THROW(lgamma(0.0), std::domain_error);
}
TEST(MathFunctions, lgammaUsingBoost) {
using boost::math::lgamma;
EXPECT_THROW(lgamma(0.0),std::domain_error);
}
TEST(MathFunctions, lgammaExplicitBoost) {
EXPECT_THROW(boost::math::lgamma(0.0), std::domain_error);
}
// C++ 11 now
// TEST(MathFunctions, lgammaExplicitStd) {
// EXPECT_NO_THROW(std::lgamma(0.0));
// }
TEST(MathFunctions, lgamma_nan) {
double nan = std::numeric_limits<double>::quiet_NaN();
EXPECT_PRED1(boost::math::isnan<double>,
stan::math::lgamma(nan));
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.