text stringlengths 54 60.6k |
|---|
<commit_before>#include <kernel/userver.hh>
#include <object/cxx-conversions.hh>
#include <object/global.hh>
#include <object/symbols.hh>
#include <runner/raise.hh>
#include <runner/runner.hh>
#include <runner/sneaker.hh>
#include <sched/scheduler.hh>
static const char *
not_loaded_yet = ("\n(this is typical of lookup errors occuring before"
" the completion of the initialization)");
namespace runner
{
using namespace object;
// We can use void as the current method because it cannot be used
// as a function call parameter.
const rObject& raise_current_method = void_class;
void
raise_urbi_skip(libport::Symbol exn_name,
rObject arg1,
rObject arg2,
rObject arg3,
rObject arg4)
{
raise_urbi(exn_name, arg1, arg2, arg3, arg4, true);
}
void
raise_urbi(libport::Symbol exn_name,
rObject arg1,
rObject arg2,
rObject arg3,
rObject arg4,
bool skip)
{
__passert(global_class->slot_has(exn_name),
"cannot throw Urbi exception " + exn_name.name_get ()
+ not_loaded_yet);
const rObject& exn = global_class->slot_get(exn_name);
Runner& r = dbg::runner_or_sneaker_get();
objects_type args;
args.push_back(exn);
do
{
if (arg1)
{
if (arg1 == raise_current_method)
args.push_back(to_urbi(r.innermost_call_get()));
else
args.push_back(arg1);
}
else
break;
if (arg2)
args.push_back(arg2);
else
break;
if (arg3)
args.push_back(arg3);
else
break;
if (arg4)
args.push_back(arg4);
else
break;
} while (false);
r.raise(args[0]->call(SYMBOL(new), args), skip);
pabort("Unreachable");
}
void
raise_lookup_error(libport::Symbol msg, const object::rObject& obj)
{
__passert(global_class->slot_has(SYMBOL(LookupError)),
"cannot raise LookupError about " + msg.name_get()
+ not_loaded_yet);
raise_urbi_skip(SYMBOL(LookupError),
to_urbi(msg),
obj);
}
void
raise_const_error()
{
__passert(global_class->slot_has(SYMBOL(ConstError)),
std::string("cannot raise ConstError")
+ not_loaded_yet);
raise_urbi_skip(SYMBOL(ConstError));
}
void
raise_arity_error(unsigned effective,
unsigned expected)
{
raise_urbi_skip(SYMBOL(ArityError),
raise_current_method,
to_urbi(effective),
to_urbi(expected));
}
void
raise_arity_error(unsigned effective,
unsigned minimum,
unsigned maximum)
{
raise_urbi_skip(SYMBOL(ArityError),
raise_current_method,
to_urbi(effective),
to_urbi(minimum),
to_urbi(maximum));
}
void
raise_argument_type_error(unsigned idx,
rObject effective,
rObject expected,
rObject method_name)
{
raise_urbi_skip(SYMBOL(ArgumentTypeError),
method_name,
to_urbi(idx),
expected,
effective);
}
void
raise_bad_integer_error(libport::ufloat effective,
const std::string& fmt)
{
raise_urbi_skip(SYMBOL(BadIntegerError),
raise_current_method,
to_urbi(fmt),
to_urbi(effective));
}
void
raise_primitive_error(const std::string& message)
{
raise_urbi_skip(SYMBOL(PrimitiveError),
raise_current_method,
to_urbi(message));
}
void
raise_unexpected_void_error()
{
raise_urbi_skip(SYMBOL(UnexpectedVoidError));
}
}
<commit_msg>runner: remove 'not_loaded_yet' variable when compiling with DNDEBUG<commit_after>#include <kernel/userver.hh>
#include <object/cxx-conversions.hh>
#include <object/global.hh>
#include <object/symbols.hh>
#include <runner/raise.hh>
#include <runner/runner.hh>
#include <runner/sneaker.hh>
#include <sched/scheduler.hh>
#ifndef NDEBUG
static const char *
not_loaded_yet = ("\n(this is typical of lookup errors occuring before"
" the completion of the initialization)");
#endif
namespace runner
{
using namespace object;
// We can use void as the current method because it cannot be used
// as a function call parameter.
const rObject& raise_current_method = void_class;
void
raise_urbi_skip(libport::Symbol exn_name,
rObject arg1,
rObject arg2,
rObject arg3,
rObject arg4)
{
raise_urbi(exn_name, arg1, arg2, arg3, arg4, true);
}
void
raise_urbi(libport::Symbol exn_name,
rObject arg1,
rObject arg2,
rObject arg3,
rObject arg4,
bool skip)
{
__passert(global_class->slot_has(exn_name),
"cannot throw Urbi exception " + exn_name.name_get ()
+ not_loaded_yet);
const rObject& exn = global_class->slot_get(exn_name);
Runner& r = dbg::runner_or_sneaker_get();
objects_type args;
args.push_back(exn);
do
{
if (arg1)
{
if (arg1 == raise_current_method)
args.push_back(to_urbi(r.innermost_call_get()));
else
args.push_back(arg1);
}
else
break;
if (arg2)
args.push_back(arg2);
else
break;
if (arg3)
args.push_back(arg3);
else
break;
if (arg4)
args.push_back(arg4);
else
break;
} while (false);
r.raise(args[0]->call(SYMBOL(new), args), skip);
pabort("Unreachable");
}
void
raise_lookup_error(libport::Symbol msg, const object::rObject& obj)
{
__passert(global_class->slot_has(SYMBOL(LookupError)),
"cannot raise LookupError about " + msg.name_get()
+ not_loaded_yet);
raise_urbi_skip(SYMBOL(LookupError),
to_urbi(msg),
obj);
}
void
raise_const_error()
{
__passert(global_class->slot_has(SYMBOL(ConstError)),
std::string("cannot raise ConstError")
+ not_loaded_yet);
raise_urbi_skip(SYMBOL(ConstError));
}
void
raise_arity_error(unsigned effective,
unsigned expected)
{
raise_urbi_skip(SYMBOL(ArityError),
raise_current_method,
to_urbi(effective),
to_urbi(expected));
}
void
raise_arity_error(unsigned effective,
unsigned minimum,
unsigned maximum)
{
raise_urbi_skip(SYMBOL(ArityError),
raise_current_method,
to_urbi(effective),
to_urbi(minimum),
to_urbi(maximum));
}
void
raise_argument_type_error(unsigned idx,
rObject effective,
rObject expected,
rObject method_name)
{
raise_urbi_skip(SYMBOL(ArgumentTypeError),
method_name,
to_urbi(idx),
expected,
effective);
}
void
raise_bad_integer_error(libport::ufloat effective,
const std::string& fmt)
{
raise_urbi_skip(SYMBOL(BadIntegerError),
raise_current_method,
to_urbi(fmt),
to_urbi(effective));
}
void
raise_primitive_error(const std::string& message)
{
raise_urbi_skip(SYMBOL(PrimitiveError),
raise_current_method,
to_urbi(message));
}
void
raise_unexpected_void_error()
{
raise_urbi_skip(SYMBOL(UnexpectedVoidError));
}
}
<|endoftext|> |
<commit_before>// $Id$
//
// Copyright (C) 2008 Greg Landrum
// All Rights Reserved
//
#include <RDGeneral/Invariant.h>
#include <GraphMol/RDKitBase.h>
#include <GraphMol/SmilesParse/SmilesParse.h>
#include <GraphMol/SmilesParse/SmilesWrite.h>
#include <GraphMol/Substruct/SubstructMatch.h>
#include <GraphMol/Depictor/RDDepictor.h>
#include <GraphMol/FileParsers/FileParsers.h>
#include <RDGeneral/RDLog.h>
#include <vector>
#include <algorithm>
using namespace RDKit;
void BuildSimpleMolecule(){
// build the molecule: C/C=C\C
RWMol *mol=new RWMol();
// add atoms and bonds:
mol->addAtom(new Atom(6)); // atom 0
mol->addAtom(new Atom(6)); // atom 1
mol->addAtom(new Atom(6)); // atom 2
mol->addAtom(new Atom(6)); // atom 3
mol->addBond(0,1,Bond::SINGLE); // bond 0
mol->addBond(1,2,Bond::DOUBLE); // bond 1
mol->addBond(2,3,Bond::SINGLE); // bond 2
// setup the stereochem:
mol->getBondWithIdx(0)->setBondDir(Bond::ENDUPRIGHT);
mol->getBondWithIdx(2)->setBondDir(Bond::ENDDOWNRIGHT);
// do the chemistry perception:
RDKit::MolOps::sanitizeMol(*mol);
// Get the canonical SMILES, include stereochemistry:
std::string smiles;
smiles = MolToSmiles(*(static_cast<ROMol *>(mol)),true);
BOOST_LOG(rdInfoLog)<<" sample 1 SMILES: " <<smiles<<std::endl;
}
void WorkWithRingInfo(){
// use a more complicated molecule to demonstrate querying about
// ring information
ROMol *mol=SmilesToMol("OC1CCC2C1CCCC2");
// the molecule from SmilesToMol is already sanitized, so we don't
// need to worry about that.
// work with ring information
RingInfo *ringInfo = mol->getRingInfo();
TEST_ASSERT(ringInfo->numRings()==2);
// can ask how many rings an atom is in:
TEST_ASSERT(ringInfo->numAtomRings(0)==0);
TEST_ASSERT(ringInfo->numAtomRings(1)==1);
TEST_ASSERT(ringInfo->numAtomRings(4)==2);
// same with bonds:
TEST_ASSERT(ringInfo->numBondRings(0)==0);
TEST_ASSERT(ringInfo->numBondRings(1)==1);
// can check if an atom is in a ring of a particular size:
TEST_ASSERT(!ringInfo->isAtomInRingOfSize(0,5));
TEST_ASSERT(ringInfo->isAtomInRingOfSize(1,5));
TEST_ASSERT(ringInfo->isAtomInRingOfSize(4,5));
TEST_ASSERT(ringInfo->isAtomInRingOfSize(4,6));
// same with bonds:
TEST_ASSERT(!ringInfo->isBondInRingOfSize(0,5));
TEST_ASSERT(ringInfo->isBondInRingOfSize(1,5));
// can also get the full list of rings as atom indices:
VECT_INT_VECT atomRings; // VECT_INT_VECT is vector< vector<int> >
atomRings=ringInfo->atomRings();
TEST_ASSERT(atomRings.size()==2);
TEST_ASSERT(atomRings[0].size()==5);
TEST_ASSERT(atomRings[1].size()==6);
// this sort is just here for test/demo purposes:
std::sort(atomRings[0].begin(),atomRings[0].end());
TEST_ASSERT(atomRings[0][0]==1);
TEST_ASSERT(atomRings[0][1]==2);
TEST_ASSERT(atomRings[0][2]==3);
TEST_ASSERT(atomRings[0][3]==4);
TEST_ASSERT(atomRings[0][4]==5);
// same with bonds:
VECT_INT_VECT bondRings; // VECT_INT_VECT is vector< vector<int> >
bondRings=ringInfo->bondRings();
TEST_ASSERT(bondRings.size()==2);
TEST_ASSERT(bondRings[0].size()==5);
TEST_ASSERT(bondRings[1].size()==6);
// the same trick played above with the contents of each ring
// can be played, but we won't
// count the number of rings of size 5:
unsigned int nRingsSize5=0;
for(VECT_INT_VECT_CI ringIt=atomRings.begin();
ringIt!=atomRings.end();++ringIt){
if(ringIt->size()==5) nRingsSize5++;
}
TEST_ASSERT(nRingsSize5==1);
delete mol;
// count the number of atoms in 5-rings where all the atoms
// are aromatic:
mol=SmilesToMol("C1CC2=C(C1)C1=C(NC3=C1C=CC=C3)C=C2");
ringInfo = mol->getRingInfo();
atomRings=ringInfo->atomRings();
unsigned int nMatchingAtoms=0;
for(VECT_INT_VECT_CI ringIt=atomRings.begin();
ringIt!=atomRings.end();++ringIt){
if(ringIt->size()!=5){
continue;
}
bool isAromatic=true;
for(INT_VECT_CI atomIt=ringIt->begin();
atomIt!=ringIt->end();++atomIt){
if(!mol->getAtomWithIdx(*atomIt)->getIsAromatic()){
isAromatic=false;
break;
}
}
if(isAromatic){
nMatchingAtoms+=5;
}
}
TEST_ASSERT(nMatchingAtoms==5);
delete mol;
// count the number of rings where all the bonds
// are aromatic.
mol=SmilesToMol("c1cccc2c1CCCC2");
ringInfo = mol->getRingInfo();
bondRings=ringInfo->bondRings();
unsigned int nAromaticRings=0;
for(VECT_INT_VECT_CI ringIt=bondRings.begin();
ringIt!=bondRings.end();++ringIt){
bool isAromatic=true;
for(INT_VECT_CI bondIt=ringIt->begin();
bondIt!=ringIt->end();++bondIt){
if(!mol->getBondWithIdx(*bondIt)->getIsAromatic()){
isAromatic=false;
break;
}
}
if(isAromatic) nAromaticRings++;
}
TEST_ASSERT(nAromaticRings==1);
delete mol;
}
void WorkWithSmarts(){
// demonstrate the use of substructure searching
ROMol *mol=SmilesToMol("ClCC=CCC");
// a simple SMARTS pattern for rotatable bonds:
ROMol *pattern=SmartsToMol("[!$(*#*)&!D1]-&!@[!$(*#*)&!D1]");
std::vector<MatchVectType> matches;
unsigned int nMatches;
nMatches=SubstructMatch(*mol,*pattern,matches);
TEST_ASSERT(nMatches==2);
TEST_ASSERT(matches.size()==2); // <- there are two rotatable bonds
// a MatchVect is a vector of std::pairs with (patternIdx, molIdx):
TEST_ASSERT(matches[0].size()==2);
TEST_ASSERT(matches[0][0].first==0);
TEST_ASSERT(matches[0][0].second==1);
TEST_ASSERT(matches[0][1].first==1);
TEST_ASSERT(matches[0][1].second==2);
delete pattern;
delete mol;
}
void DepictDemo(){
// demonstrate the use of the depiction-generation code2D coordinates:
ROMol *mol=SmilesToMol("ClCC=CCC");
// generate the 2D coordinates:
RDDepict::compute2DCoords(*mol);
// generate a mol block (could also go to a file):
std::string molBlock=MolToMolBlock(*mol);
BOOST_LOG(rdInfoLog)<<molBlock;
delete mol;
}
void CleanupMolecule(){
// build: C1CC1C(:O):O
RWMol *mol=new RWMol();
// add atoms and bonds:
mol->addAtom(new Atom(6)); // atom 0
mol->addAtom(new Atom(6)); // atom 1
mol->addAtom(new Atom(6)); // atom 2
mol->addAtom(new Atom(6)); // atom 3
mol->addAtom(new Atom(8)); // atom 4
mol->addAtom(new Atom(8)); // atom 5
mol->addBond(3,4,Bond::AROMATIC); // bond 0
mol->addBond(3,5,Bond::AROMATIC); // bond 1
mol->addBond(3,2,Bond::SINGLE); // bond 2
mol->addBond(2,1,Bond::SINGLE); // bond 3
mol->addBond(1,0,Bond::SINGLE); // bond 4
mol->addBond(0,2,Bond::SINGLE); // bond 5
// instead of calling sanitize mol, which would generate an error,
// we'll perceive the rings, then take care of aromatic bonds
// that aren't in a ring, then sanitize:
MolOps::findSSSR(*mol);
for(ROMol::BondIterator bondIt=mol->beginBonds();
bondIt!=mol->endBonds();++bondIt){
if( ((*bondIt)->getIsAromatic() ||
(*bondIt)->getBondType()==Bond::AROMATIC)
&& !mol->getRingInfo()->numBondRings((*bondIt)->getIdx()) ){
(*bondIt)->setIsAromatic(false);
// NOTE: this isn't really reasonable:
(*bondIt)->setBondType(Bond::SINGLE);
}
}
// now it's safe to sanitize:
RDKit::MolOps::sanitizeMol(*mol);
// Get the canonical SMILES, include stereochemistry:
std::string smiles;
smiles = MolToSmiles(*(static_cast<ROMol *>(mol)),true);
BOOST_LOG(rdInfoLog)<<" fixed SMILES: " <<smiles<<std::endl;
}
int
main(int argc, char *argv[])
{
RDLog::InitLogs();
CleanupMolecule();
BuildSimpleMolecule();
WorkWithRingInfo();
WorkWithSmarts();
DepictDemo();
}
<commit_msg>update this<commit_after>// $Id$
//
// Copyright (C) 2008-2010 Greg Landrum
// All Rights Reserved
//
// Can be built with:
// g++ -o sample.exe sample.cpp -I$RDBASE/Code -I$RDBASE/Extern \
// -L$RDBASE/lib -L$RDBASE/bin -lFileParsers -lSmilesParse -lDepictor \
// -lSubstructMatch -lGraphMol -lDataStructs -lRDGeometryLib -lRDGeneral
//
#include <RDGeneral/Invariant.h>
#include <GraphMol/RDKitBase.h>
#include <GraphMol/SmilesParse/SmilesParse.h>
#include <GraphMol/SmilesParse/SmilesWrite.h>
#include <GraphMol/Substruct/SubstructMatch.h>
#include <GraphMol/Depictor/RDDepictor.h>
#include <GraphMol/FileParsers/FileParsers.h>
#include <RDGeneral/RDLog.h>
#include <vector>
#include <algorithm>
using namespace RDKit;
void BuildSimpleMolecule(){
// build the molecule: C/C=C\C
RWMol *mol=new RWMol();
// add atoms and bonds:
mol->addAtom(new Atom(6)); // atom 0
mol->addAtom(new Atom(6)); // atom 1
mol->addAtom(new Atom(6)); // atom 2
mol->addAtom(new Atom(6)); // atom 3
mol->addBond(0,1,Bond::SINGLE); // bond 0
mol->addBond(1,2,Bond::DOUBLE); // bond 1
mol->addBond(2,3,Bond::SINGLE); // bond 2
// setup the stereochem:
mol->getBondWithIdx(0)->setBondDir(Bond::ENDUPRIGHT);
mol->getBondWithIdx(2)->setBondDir(Bond::ENDDOWNRIGHT);
// do the chemistry perception:
RDKit::MolOps::sanitizeMol(*mol);
// Get the canonical SMILES, include stereochemistry:
std::string smiles;
smiles = MolToSmiles(*(static_cast<ROMol *>(mol)),true);
BOOST_LOG(rdInfoLog)<<" sample 1 SMILES: " <<smiles<<std::endl;
}
void WorkWithRingInfo(){
// use a more complicated molecule to demonstrate querying about
// ring information
ROMol *mol=SmilesToMol("OC1CCC2C1CCCC2");
// the molecule from SmilesToMol is already sanitized, so we don't
// need to worry about that.
// work with ring information
RingInfo *ringInfo = mol->getRingInfo();
TEST_ASSERT(ringInfo->numRings()==2);
// can ask how many rings an atom is in:
TEST_ASSERT(ringInfo->numAtomRings(0)==0);
TEST_ASSERT(ringInfo->numAtomRings(1)==1);
TEST_ASSERT(ringInfo->numAtomRings(4)==2);
// same with bonds:
TEST_ASSERT(ringInfo->numBondRings(0)==0);
TEST_ASSERT(ringInfo->numBondRings(1)==1);
// can check if an atom is in a ring of a particular size:
TEST_ASSERT(!ringInfo->isAtomInRingOfSize(0,5));
TEST_ASSERT(ringInfo->isAtomInRingOfSize(1,5));
TEST_ASSERT(ringInfo->isAtomInRingOfSize(4,5));
TEST_ASSERT(ringInfo->isAtomInRingOfSize(4,6));
// same with bonds:
TEST_ASSERT(!ringInfo->isBondInRingOfSize(0,5));
TEST_ASSERT(ringInfo->isBondInRingOfSize(1,5));
// can also get the full list of rings as atom indices:
VECT_INT_VECT atomRings; // VECT_INT_VECT is vector< vector<int> >
atomRings=ringInfo->atomRings();
TEST_ASSERT(atomRings.size()==2);
TEST_ASSERT(atomRings[0].size()==5);
TEST_ASSERT(atomRings[1].size()==6);
// this sort is just here for test/demo purposes:
std::sort(atomRings[0].begin(),atomRings[0].end());
TEST_ASSERT(atomRings[0][0]==1);
TEST_ASSERT(atomRings[0][1]==2);
TEST_ASSERT(atomRings[0][2]==3);
TEST_ASSERT(atomRings[0][3]==4);
TEST_ASSERT(atomRings[0][4]==5);
// same with bonds:
VECT_INT_VECT bondRings; // VECT_INT_VECT is vector< vector<int> >
bondRings=ringInfo->bondRings();
TEST_ASSERT(bondRings.size()==2);
TEST_ASSERT(bondRings[0].size()==5);
TEST_ASSERT(bondRings[1].size()==6);
// the same trick played above with the contents of each ring
// can be played, but we won't
// count the number of rings of size 5:
unsigned int nRingsSize5=0;
for(VECT_INT_VECT_CI ringIt=atomRings.begin();
ringIt!=atomRings.end();++ringIt){
if(ringIt->size()==5) nRingsSize5++;
}
TEST_ASSERT(nRingsSize5==1);
delete mol;
// count the number of atoms in 5-rings where all the atoms
// are aromatic:
mol=SmilesToMol("C1CC2=C(C1)C1=C(NC3=C1C=CC=C3)C=C2");
ringInfo = mol->getRingInfo();
atomRings=ringInfo->atomRings();
unsigned int nMatchingAtoms=0;
for(VECT_INT_VECT_CI ringIt=atomRings.begin();
ringIt!=atomRings.end();++ringIt){
if(ringIt->size()!=5){
continue;
}
bool isAromatic=true;
for(INT_VECT_CI atomIt=ringIt->begin();
atomIt!=ringIt->end();++atomIt){
if(!mol->getAtomWithIdx(*atomIt)->getIsAromatic()){
isAromatic=false;
break;
}
}
if(isAromatic){
nMatchingAtoms+=5;
}
}
TEST_ASSERT(nMatchingAtoms==5);
delete mol;
// count the number of rings where all the bonds
// are aromatic.
mol=SmilesToMol("c1cccc2c1CCCC2");
ringInfo = mol->getRingInfo();
bondRings=ringInfo->bondRings();
unsigned int nAromaticRings=0;
for(VECT_INT_VECT_CI ringIt=bondRings.begin();
ringIt!=bondRings.end();++ringIt){
bool isAromatic=true;
for(INT_VECT_CI bondIt=ringIt->begin();
bondIt!=ringIt->end();++bondIt){
if(!mol->getBondWithIdx(*bondIt)->getIsAromatic()){
isAromatic=false;
break;
}
}
if(isAromatic) nAromaticRings++;
}
TEST_ASSERT(nAromaticRings==1);
delete mol;
}
void WorkWithSmarts(){
// demonstrate the use of substructure searching
ROMol *mol=SmilesToMol("ClCC=CCC");
// a simple SMARTS pattern for rotatable bonds:
ROMol *pattern=SmartsToMol("[!$(*#*)&!D1]-&!@[!$(*#*)&!D1]");
std::vector<MatchVectType> matches;
unsigned int nMatches;
nMatches=SubstructMatch(*mol,*pattern,matches);
TEST_ASSERT(nMatches==2);
TEST_ASSERT(matches.size()==2); // <- there are two rotatable bonds
// a MatchVect is a vector of std::pairs with (patternIdx, molIdx):
TEST_ASSERT(matches[0].size()==2);
TEST_ASSERT(matches[0][0].first==0);
TEST_ASSERT(matches[0][0].second==1);
TEST_ASSERT(matches[0][1].first==1);
TEST_ASSERT(matches[0][1].second==2);
delete pattern;
delete mol;
}
void DepictDemo(){
// demonstrate the use of the depiction-generation code2D coordinates:
ROMol *mol=SmilesToMol("ClCC=CCC");
// generate the 2D coordinates:
RDDepict::compute2DCoords(*mol);
// generate a mol block (could also go to a file):
std::string molBlock=MolToMolBlock(*mol);
BOOST_LOG(rdInfoLog)<<molBlock;
delete mol;
}
void CleanupMolecule(){
// an example of doing some cleaning up of a molecule before
// calling the sanitizeMol function()
// build: C1CC1C(:O):O
RWMol *mol=new RWMol();
// add atoms and bonds:
mol->addAtom(new Atom(6)); // atom 0
mol->addAtom(new Atom(6)); // atom 1
mol->addAtom(new Atom(6)); // atom 2
mol->addAtom(new Atom(6)); // atom 3
mol->addAtom(new Atom(8)); // atom 4
mol->addAtom(new Atom(8)); // atom 5
mol->addBond(3,4,Bond::AROMATIC); // bond 0
mol->addBond(3,5,Bond::AROMATIC); // bond 1
mol->addBond(3,2,Bond::SINGLE); // bond 2
mol->addBond(2,1,Bond::SINGLE); // bond 3
mol->addBond(1,0,Bond::SINGLE); // bond 4
mol->addBond(0,2,Bond::SINGLE); // bond 5
// instead of calling sanitize mol, which would generate an error,
// we'll perceive the rings, then take care of aromatic bonds
// that aren't in a ring, then sanitize:
MolOps::findSSSR(*mol);
for(ROMol::BondIterator bondIt=mol->beginBonds();
bondIt!=mol->endBonds();++bondIt){
if( ((*bondIt)->getIsAromatic() ||
(*bondIt)->getBondType()==Bond::AROMATIC)
&& !mol->getRingInfo()->numBondRings((*bondIt)->getIdx()) ){
// remove the aromatic flag on the bond:
(*bondIt)->setIsAromatic(false);
// and cleanup its attached atoms as well (they were
// also marked aromatic when the bond was added)
(*bondIt)->getBeginAtom()->setIsAromatic(false);
(*bondIt)->getEndAtom()->setIsAromatic(false);
// NOTE: this isn't really reasonable:
(*bondIt)->setBondType(Bond::SINGLE);
}
}
// now it's safe to sanitize:
RDKit::MolOps::sanitizeMol(*mol);
// Get the canonical SMILES, include stereochemistry:
std::string smiles;
smiles = MolToSmiles(*(static_cast<ROMol *>(mol)),true);
BOOST_LOG(rdInfoLog)<<" fixed SMILES: " <<smiles<<std::endl;
}
int
main(int argc, char *argv[])
{
RDLog::InitLogs();
BuildSimpleMolecule();
WorkWithRingInfo();
WorkWithSmarts();
DepictDemo();
CleanupMolecule();
}
<|endoftext|> |
<commit_before>#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <Arduino.h>
#include <string.h>
#include <sapiArduino.h>
#include <EEPROM.h>
static String createCred(const char* id, const char* pass);
static String getJsessionid(String line);
static String getValidationkey(String line);
static int getStatusCode(String line);
static String buildMultipart(String boundary, FileInfo info);
static String createMetadata(FileInfo info, String Id);
static String getId(String line);
static String createGetBody(String Id);
String sendMetadata(Session login, FileInfo file, String Id);
int saveFile(Session log, FileInfo file, String Id);
//do the login at onemediahub.com, get the jSessionid, validationkey and returns a number code 0, if the login is happened successfully, 1 failed to stabiliz connetion with the host
//2 username or password is wrong, 3 anexatly error in response from server
int doLogin(const char* username, const char* password, Session* login){
WiFiClientSecure client;
const char* host = "onemediahub.com";
const int httpsPort = 443;
if(!client.connect(host, httpsPort)){
return WiFi_NOT_CONNECTED;
}
String user = createCred(username, password);
String url = "/sapi/login?action=login";
String request = "POST " + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Content-Type: application/x-www-form-urlencoded\r\n" +
"Content-Length: " + user.length() + "\r\n" +
"Connection: close\r\n" +
"\r\n"+
user;
client.print(request);
String line= "";
String control = "p";
while (client.connected()||(control!=line)) {
control = line;
line += client.readStringUntil('\n');
if (line == "\r") {
break;
}
}
client.read();
login->jsonid = getJsessionid(line);
login->key = getValidationkey(line);
if(login->jsonid == NULL){
return JSESSIONID_MISS;
}
if(login->key == NULL){
return AUTENTICATION_KEY_NOT_FOUND;
}
return getStatusCode(line);
}
int uploadBuffer(Session login, const char* buffer, long length){
FileInfo file = {"NoName.txt", "text/plain", buffer, length};
return uploadFile(login, file);
}
int uploadFile(Session login, FileInfo file){
const char* host = "onemediahub.com";
const int httpsPort = 443;
WiFiClientSecure client;
if(!client.connect(host, httpsPort)){
return WiFi_NOT_CONNECTED;
}
String url = "/sapi/upload?action=save&validationkey=" + login.key;
String boundary = "46w9f0apovnw23951faydgi";
String body = buildMultipart(boundary,file);
//perch non fare una funzione per la request?
String request = String("POST ") + url + " HTTP/1.1\r\n" + //rfc http 1.1
"Host: " + host + "\r\n" +
"Cookie: JSESSIONID=" + login.jsonid + "\r\n" +
"Content-Type: multipart/form-data;boundary=" + boundary + "\r\n" +
"Content-Length: " + body.length() + "\r\n" +
"Connection: close" + "\r\n" +
"\r\n"+
body;
client.print(request);
String line= "";
String control = "p";
while ((control!=line)) {
control = line;
line += client.readStringUntil('\n');
if (line == "\r") {
break;
}
}
client.read();
return getStatusCode(line);
}
int resumableUploadFile(Session login, FileInfo file){
int statusCode;
String Id = sendMetadata(login, file, "");
if (Id != NULL){
statusCode = saveFile(login, file, Id);
}
return statusCode;
}
int dowloadWithId(String Id, FileInfo* file, Session login){
WiFiClientSecure client;
const char* host = "onemediahub.com";
const int httpsPort = 443;
if(!client.connect(host, httpsPort)){
return WiFi_NOT_CONNECTED;
}
String body = createGetBody(Id);
String url = "/sapi/media?action=get&validationkey=" + login.key;
String request = "GET " + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Cookie: JSESSIONID=" + login.jsonid + "\r\n" +
"Connection: close\r\n" +
"\r\n"+
body;
client.print(request);
Serial.println(request);
String line= "";
String control = "p";
while (client.connected()||(control!=line)) {
control = line;
line += client.readStringUntil('\n');
if (line == "\r") {
break;
}
}
client.read();
Serial.println("download: ");
Serial.println(line);
return getStatusCode(line);
}
//create the login=username&password=account-infomation
static String createCred(const char* id, const char* pass){
String login="login=";
String e="&";
String other="password=";
String postData;
postData = postData + login + id + e + other + pass;
return postData;
}
static String getJsessionid(String line){
String token = "\"jsessionid\":\"";
int index = line.indexOf("\"jsessionid\":\"" );
index += token.length();
int endindex = line.indexOf("\"", index);
return line.substring(index,endindex);
}
static String getValidationkey(String line){
String token = "\"validationkey\":\"";
int index = line.indexOf("\"validationkey\":\"" );
index += token.length();
int endindex = line.indexOf("\"", index);
return line.substring(index,endindex);
}
int getStatusCode(String line){
String token = "HTTP/1.1 ";
token = line.substring(token.length(),(token.length()+3));
switch(token.toInt()){
case 200:
return LOGIN_OK;
break;
case 401:
return AUTENTICATION_FAILED;
break;
default:
return GENERIC_ERROR;
break;
}
}
String buildMultipart(String boundary, FileInfo info){
String multipart;
multipart += "--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=\"data\"\r\n\r\n" +
"{" +
"\"data\":{" +
"\"name\":\"" + info.name + "\"," +
"\"creationdate\":\""+ info.date + "\"," +
"\"modificationdate\":\""+ info.date + "\"," +
"\"contenttype\":\"" + info.type + "\"," +
"\"size\":" + info.length + "," +
"\"folderid\":-1" +
"}" +
"}\r\n" +
"--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=\"file\"; filename=\"" + info.name + "\"\r\n" +
"Content-Type: \"" + info.type + "\"\r\n\r\n" +
info.content + "\r\n" +
"--" + boundary + "--";
return multipart;
}
String sendMetadata(Session login, FileInfo file, String Id){
WiFiClientSecure client;
const char* host = "onemediahub.com";
const int httpsPort = 443;
if(!client.connect(host, httpsPort)){
return "no log";
}
String url = "/sapi/upload/file?action=save-metadata&validationkey=" + login.key;
String body = createMetadata(file, Id);
String request = String("POST ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Cookie: JSESSIONID=" + login.jsonid + "\r\n" +
"Content-Type: application/json\r\n" +
"Content-Length: " + body.length() + "\r\n" +
"Connection: close" + "\r\n" +
"\r\n"+
body;
client.print(request);
Serial.println(request);
String line= "";
String control = "p";
while (client.connected()||(control!=line)) {
control = line;
line += client.readStringUntil('\n');
if (line == "\r") {
break;
}
}
client.read();
Serial.println(line);
return getId(line);
}
String createMetadata(FileInfo info, String Id){
String metadata;
metadata += "{";
metadata += "\"data\":{";
metadata += "\"name\":\"" + info.name + "\"," +
Id +
"\"creationdate\":\""+ info.date + "\"," +
"\"modificationdate\":\""+ info.date + "\"," +
"\"contenttype\":\"" + info.type + "\"," +
"\"size\":" + info.length + "," +
"\"folderid\":-1" +
"}" +
"}";
return metadata;
}
String getId(String line){
String token = "\"id\":\"";
int index = line.indexOf("\"id\":\"" );
index += token.length();
int endindex = line.indexOf("\"", index);
return line.substring(index,endindex);
}
int saveFile(Session log, FileInfo file, String Id){
WiFiClientSecure client;
const char* host = "onemediahub.com";
const int httpsPort = 443;
if(!client.connect(host, httpsPort)){
return WiFi_NOT_CONNECTED;
}
String url = "/sapi/upload/file?action=save&validationkey=" + log.key;
String request = String("POST ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"x-funambol-id: " + Id + "\r\n" +
"x-funambol-file-size:" + file.content.length() + "\r\n" +
"Cookie: JSESSIONID=" + log.jsonid + "\r\n" +
"Content-Type: text/plain\r\n" +
"Content-Length: " + file.content.length() + "\r\n" +
"Connection: close" + "\r\n" +
"\r\n"+
file.content;
client.print(request);
Serial.print(request);
String line= "";
String control = "p";
while ((control!=line)) {
control = line;
line += client.readStringUntil('\n');
if (line == "\r") {
break;
}
}
client.read();
Serial.print(line);
if(line.indexOf("\"MED-1000\"" )>0){
return 1000;
}
return 0;
}
String createGetBody(String Id){
String request;
request += "{";
request += "\"data\":{";
request += "\"ids\":[\"" +
Id +
"\"]," +
"\"fields\":[" +
"\"url\"" +
"]" +
"}"+
"}";
return request;
}
void storageId(String Id){
for(int a = 0; a < Id.length(); a++){
EEPROM.write(a, Id[a]);
}
EEPROM.commit();
}
String readId(){
char Id[20];
int a = 0;
Id[a] = EEPROM.read(a);
while(int(Id[a]) != 0){
a++;
Id[a] = EEPROM.read(a);
}
return Id;
}
<commit_msg>added download<commit_after>#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <Arduino.h>
#include <string.h>
#include <sapiArduino.h>
#include <EEPROM.h>
static String createCred(const char* id, const char* pass);
static String getJsessionid(String line);
static String getValidationkey(String line);
static int getStatusCode(String line);
static String buildMultipart(String boundary, FileInfo info);
static String createMetadata(FileInfo info, String Id);
static String getId(String line);
static String createGetBody(String Id);
String sendMetadata(Session login, FileInfo file, String Id);
int saveFile(Session log, FileInfo file, String Id);
//do the login at onemediahub.com, get the jSessionid, validationkey and returns a number code 0, if the login is happened successfully, 1 failed to stabiliz connetion with the host
//2 username or password is wrong, 3 anexatly error in response from server
int doLogin(const char* username, const char* password, Session* login){
WiFiClientSecure client;
const char* host = "onemediahub.com";
const int httpsPort = 443;
if(!client.connect(host, httpsPort)){
return WiFi_NOT_CONNECTED;
}
String user = createCred(username, password);
String url = "/sapi/login?action=login";
String request = "POST " + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Content-Type: application/x-www-form-urlencoded\r\n" +
"Content-Length: " + user.length() + "\r\n" +
"Connection: close\r\n" +
"\r\n"+
user;
client.print(request);
String line= "";
String control = "p";
while (client.connected()||(control!=line)) {
control = line;
line += client.readStringUntil('\n');
if (line == "\r") {
break;
}
}
client.read();
login->jsonid = getJsessionid(line);
login->key = getValidationkey(line);
if(login->jsonid == NULL){
return JSESSIONID_MISS;
}
if(login->key == NULL){
return AUTENTICATION_KEY_NOT_FOUND;
}
return getStatusCode(line);
}
int uploadBuffer(Session login, const char* buffer, long length){
FileInfo file = {"NoName.txt", "text/plain", buffer, length};
return uploadFile(login, file);
}
int uploadFile(Session login, FileInfo file){
const char* host = "onemediahub.com";
const int httpsPort = 443;
WiFiClientSecure client;
if(!client.connect(host, httpsPort)){
return WiFi_NOT_CONNECTED;
}
String url = "/sapi/upload?action=save&validationkey=" + login.key;
String boundary = "46w9f0apovnw23951faydgi";
String body = buildMultipart(boundary,file);
//perch non fare una funzione per la request?
String request = String("POST ") + url + " HTTP/1.1\r\n" + //rfc http 1.1
"Host: " + host + "\r\n" +
"Cookie: JSESSIONID=" + login.jsonid + "\r\n" +
"Content-Type: multipart/form-data;boundary=" + boundary + "\r\n" +
"Content-Length: " + body.length() + "\r\n" +
"Connection: close" + "\r\n" +
"\r\n"+
body;
client.print(request);
String line= "";
String control = "p";
while ((control!=line)) {
control = line;
line += client.readStringUntil('\n');
if (line == "\r") {
break;
}
}
client.read();
return getStatusCode(line);
}
int resumableUploadFile(Session login, FileInfo file){
int statusCode;
String Id = sendMetadata(login, file, "");
if (Id != NULL){
statusCode = saveFile(login, file, Id);
}
return statusCode;
}
int dowloadWithId(String Id, FileInfo* file, Session login){
WiFiClientSecure client;
const char* host = "onemediahub.com";
const int httpsPort = 443;
if(!client.connect(host, httpsPort)){
return WiFi_NOT_CONNECTED;
}
String body = createGetBody(Id);
String url = "/sapi/media?action=get&origin=omh&validationkey=" + login.key;
String request = "POST " + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Cookie: JSESSIONID=" + login.jsonid + "\r\n" +
"Content-Type: application/json \r\n" +
"Content-Length: " + body.length() + "\r\n" +
"Connection: close\r\n" +
"\r\n"+
body;
client.print(request);
Serial.println(request);
String line= "";
String control = "p";
while (client.connected()||(control!=line)) {
control = line;
line += client.readStringUntil('\n');
if (line == "\r") {
break;
}
}
client.read();
Serial.println("download: ");
Serial.println(line);
return getStatusCode(line);
}
//create the login=username&password=account-infomation
static String createCred(const char* id, const char* pass){
String login="login=";
String e="&";
String other="password=";
String postData;
postData = postData + login + id + e + other + pass;
return postData;
}
static String getJsessionid(String line){
String token = "\"jsessionid\":\"";
int index = line.indexOf("\"jsessionid\":\"" );
index += token.length();
int endindex = line.indexOf("\"", index);
return line.substring(index,endindex);
}
static String getValidationkey(String line){
String token = "\"validationkey\":\"";
int index = line.indexOf("\"validationkey\":\"" );
index += token.length();
int endindex = line.indexOf("\"", index);
return line.substring(index,endindex);
}
int getStatusCode(String line){
String token = "HTTP/1.1 ";
token = line.substring(token.length(),(token.length()+3));
switch(token.toInt()){
case 200:
return LOGIN_OK;
break;
case 401:
return AUTENTICATION_FAILED;
break;
default:
return GENERIC_ERROR;
break;
}
}
String buildMultipart(String boundary, FileInfo info){
String multipart;
multipart += "--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=\"data\"\r\n\r\n" +
"{" +
"\"data\":{" +
"\"name\":\"" + info.name + "\"," +
"\"creationdate\":\""+ info.date + "\"," +
"\"modificationdate\":\""+ info.date + "\"," +
"\"contenttype\":\"" + info.type + "\"," +
"\"size\":" + info.length + "," +
"\"folderid\":-1" +
"}" +
"}\r\n" +
"--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=\"file\"; filename=\"" + info.name + "\"\r\n" +
"Content-Type: \"" + info.type + "\"\r\n\r\n" +
info.content + "\r\n" +
"--" + boundary + "--";
return multipart;
}
String sendMetadata(Session login, FileInfo file, String Id){
WiFiClientSecure client;
const char* host = "onemediahub.com";
const int httpsPort = 443;
if(!client.connect(host, httpsPort)){
return "no log";
}
String url = "/sapi/upload/file?action=save-metadata&validationkey=" + login.key;
String body = createMetadata(file, Id);
String request = String("POST ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Cookie: JSESSIONID=" + login.jsonid + "\r\n" +
"Content-Type: application/json\r\n" +
"Content-Length: " + body.length() + "\r\n" +
"Connection: close" + "\r\n" +
"\r\n"+
body;
client.print(request);
Serial.println(request);
String line= "";
String control = "p";
while (client.connected()||(control!=line)) {
control = line;
line += client.readStringUntil('\n');
if (line == "\r") {
break;
}
}
client.read();
Serial.println(line);
return getId(line);
}
String createMetadata(FileInfo info, String Id){
String metadata;
metadata += "{";
metadata += "\"data\":{";
metadata += "\"name\":\"" + info.name + "\"," +
Id +
"\"creationdate\":\""+ info.date + "\"," +
"\"modificationdate\":\""+ info.date + "\"," +
"\"contenttype\":\"" + info.type + "\"," +
"\"size\":" + info.length + "," +
"\"folderid\":-1" +
"}" +
"}";
return metadata;
}
String getId(String line){
String token = "\"id\":\"";
int index = line.indexOf("\"id\":\"" );
index += token.length();
int endindex = line.indexOf("\"", index);
return line.substring(index,endindex);
}
int saveFile(Session log, FileInfo file, String Id){
WiFiClientSecure client;
const char* host = "onemediahub.com";
const int httpsPort = 443;
if(!client.connect(host, httpsPort)){
return WiFi_NOT_CONNECTED;
}
String url = "/sapi/upload/file?action=save&validationkey=" + log.key;
String request = String("POST ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"x-funambol-id: " + Id + "\r\n" +
"x-funambol-file-size:" + file.content.length() + "\r\n" +
"Cookie: JSESSIONID=" + log.jsonid + "\r\n" +
"Content-Type: text/plain\r\n" +
"Content-Length: " + file.content.length() + "\r\n" +
"Connection: close" + "\r\n" +
"\r\n"+
file.content;
client.print(request);
Serial.print(request);
String line= "";
String control = "p";
while ((control!=line)) {
control = line;
line += client.readStringUntil('\n');
if (line == "\r") {
break;
}
}
client.read();
Serial.print(line);
if(line.indexOf("\"MED-1000\"" )>0){
return 1000;
}
return 0;
}
String createGetBody(String Id){
String request;
request += "{";
request += "\"data\":{";
request += "\"ids\":[\"" +
Id +
"\"]," +
"\"fields\":[" +
"\"url\"" +
"]" +
"}"+
"}";
return request;
}
void storageId(String Id){
for(int a = 0; a < Id.length(); a++){
EEPROM.write(a, Id[a]);
}
EEPROM.commit();
}
String readId(){
char Id[20];
int a = 0;
Id[a] = EEPROM.read(a);
while(int(Id[a]) != 0){
a++;
Id[a] = EEPROM.read(a);
}
return Id;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) Shunya KIMURA <brmtrain@gmail.com>
* Use and distribution of this program is licensed under the
* BSD license. See the COPYING file for full text.
*
* Original version TinySegmenter was written by Taku Kudo <taku@chasen.org>
* The license is below.
* TinySegmenter 0.1 -- Super compact Japanese tokenizer in Javascript
* (c) 2008 Taku Kudo <taku@chasen.org>
* TinySegmenter is freely distributable under the terms of a new BSD licence.
* For details, see http://chasen.org/~taku/software/TinySegmenter/LICENCE.txt
* http://www.chasen.org/~taku/software/TinySegmenter/
*
*/
#include <fcntl.h> //stat stat_buf
#include "tinysegmenterxx.hpp"
const unsigned int MAX_BUF_SIZ = 65536;
void printUsage(std::string& fileName)
{
std::cerr << std::endl;
std::cerr << fileName << " : the utility of tinysegmenter(Japanese setence segmenter)." << std::endl;
std::cerr << " " << fileName << " [options] filepath" << std::endl;
std::cerr << " " << fileName << " < filepath" << std::endl;
std::cerr << " -s, --separator=[tab|zero|return(default)]" << std::endl;
std::cerr << " -h, --help" << std::endl;
std::cerr << " -v, --version" << std::endl;
exit(0);
}
void procArgs(int argc, char** argv, std::string& separator, std::string& inputPath)
{
std::string fileName = argv[0];
for(int i = 1; i < argc; i++){
std::string argBuf = argv[i];
if(argBuf == "-s"){
separator = argv[++i];
} else if((argBuf.find("--separator=")) != std::string::npos){
unsigned int idx = argBuf.find("=");
separator = argv[i] + idx + 1;
} else if(argBuf == "--help" || argBuf == "-h"){
printUsage(fileName);
} else if(argBuf == "--version" || argBuf == "-v"){
std::string body;
tinysegmenterxx::util::getVersion(body);
std::cerr << body << std::endl;
exit(EXIT_SUCCESS);
} else {
if(i == argc - 1){
inputPath = argBuf;
break;
}
printUsage(fileName);
}
}
if(inputPath.size() < 1){
printUsage(fileName);
}
if(separator.size() < 1){
separator = '\n';
} else if(separator == "zero"){
separator = '\0';
} else if(separator == "tab"){
separator = '\t';
} else if(separator == "return"){
separator = '\n';
} else {
std::cerr << "unknown option: -s " << separator << std::endl;
std::cerr << "-s needs [zero|tab]" << std::endl;
exit(1);
}
}
int main(int argc, char** argv)
{
std::string fileName = argv[0];
tinysegmenterxx::Segmenter sg;
if(argc > 1){
std::string inputPath;
std::string separator;
procArgs(argc, argv, separator, inputPath);
struct stat stat_buf;
size_t fileSiz = 0;
if(stat(inputPath.c_str(), &stat_buf) == 0){
fileSiz = stat_buf.st_size;
}
char* buf = NULL;
int bufSiz = fileSiz;
if(fileSiz >= MAX_BUF_SIZ){
bufSiz = 0;
buf = new char[fileSiz + 1];
}
char inputBuf[bufSiz + 1];
if(!buf) buf = inputBuf;
std::ifstream ifs;
ifs.open(inputPath.c_str(), std::ios::in);
if(!ifs){
std::cerr << "cant open file:" << inputPath << std::endl;
exit(1);
}
ifs.read(buf, fileSiz);
buf[fileSiz] = '\0';
std::string line = buf;
tinysegmenterxx::Segmentes segs;
sg.segment(line, segs);
for(unsigned int i = 0; i < segs.size(); i++){
std::cout << segs[i] << separator;
}
if(buf != inputBuf) delete[] buf;
} else {
std::string buf;
while(std::cin){
std::string line;
std::cin >> line;
buf.append(line);
buf.append("\n");
}
tinysegmenterxx::Segmentes segs;
sg.segment(buf, segs);
for(unsigned int i = 0; i < segs.size(); i++){
std::cout << segs[i] << std::endl;
}
}
return 0;
}
<commit_msg>[wiki]update<commit_after>/*
* Copyright (C) Shunya KIMURA <brmtrain@gmail.com>
* Use and distribution of this program is licensed under the
* BSD license. See the COPYING file for full text.
*
* Original version TinySegmenter was written by Taku Kudo <taku@chasen.org>
* The license is below.
* TinySegmenter 0.1 -- Super compact Japanese tokenizer in Javascript
* (c) 2008 Taku Kudo <taku@chasen.org>
* TinySegmenter is freely distributable under the terms of a new BSD licence.
* For details, see http://chasen.org/~taku/software/TinySegmenter/LICENCE.txt
* http://www.chasen.org/~taku/software/TinySegmenter/
*
*/
#include <fcntl.h> //stat stat_buf
#include "tinysegmenterxx.hpp"
const unsigned int MAX_BUF_SIZ = 65536;
void printUsage(std::string& fileName)
{
std::cerr << std::endl;
std::cerr << fileName << " : Super compact Japanese tokenizer in C++." << std::endl;
std::cerr << " " << fileName << " [options] filepath" << std::endl;
std::cerr << " " << fileName << " < filepath" << std::endl;
std::cerr << " -s, --separator=[tab|zero|return(default)]" << std::endl;
std::cerr << " -h, --help" << std::endl;
std::cerr << " -v, --version" << std::endl;
exit(0);
}
void procArgs(int argc, char** argv, std::string& separator, std::string& inputPath)
{
std::string fileName = argv[0];
for(int i = 1; i < argc; i++){
std::string argBuf = argv[i];
if(argBuf == "-s"){
separator = argv[++i];
} else if((argBuf.find("--separator=")) != std::string::npos){
unsigned int idx = argBuf.find("=");
separator = argv[i] + idx + 1;
} else if(argBuf == "--help" || argBuf == "-h"){
printUsage(fileName);
} else if(argBuf == "--version" || argBuf == "-v"){
std::string body;
tinysegmenterxx::util::getVersion(body);
std::cerr << body << std::endl;
exit(EXIT_SUCCESS);
} else {
if(i == argc - 1){
inputPath = argBuf;
break;
}
printUsage(fileName);
}
}
if(inputPath.size() < 1){
printUsage(fileName);
}
if(separator.size() < 1){
separator = '\n';
} else if(separator == "zero"){
separator = '\0';
} else if(separator == "tab"){
separator = '\t';
} else if(separator == "return"){
separator = '\n';
} else {
std::cerr << "unknown option: -s " << separator << std::endl;
std::cerr << "-s needs [zero|tab]" << std::endl;
exit(1);
}
}
int main(int argc, char** argv)
{
std::string fileName = argv[0];
tinysegmenterxx::Segmenter sg;
if(argc > 1){
std::string inputPath;
std::string separator;
procArgs(argc, argv, separator, inputPath);
struct stat stat_buf;
size_t fileSiz = 0;
if(stat(inputPath.c_str(), &stat_buf) == 0){
fileSiz = stat_buf.st_size;
}
char* buf = NULL;
int bufSiz = fileSiz;
if(fileSiz >= MAX_BUF_SIZ){
bufSiz = 0;
buf = new char[fileSiz + 1];
}
char inputBuf[bufSiz + 1];
if(!buf) buf = inputBuf;
std::ifstream ifs;
ifs.open(inputPath.c_str(), std::ios::in);
if(!ifs){
std::cerr << "cant open file:" << inputPath << std::endl;
exit(1);
}
ifs.read(buf, fileSiz);
buf[fileSiz] = '\0';
std::string line = buf;
tinysegmenterxx::Segmentes segs;
sg.segment(line, segs);
for(unsigned int i = 0; i < segs.size(); i++){
std::cout << segs[i] << separator;
}
if(buf != inputBuf) delete[] buf;
} else {
std::string buf;
while(std::cin){
std::string line;
std::cin >> line;
buf.append(line);
buf.append("\n");
}
tinysegmenterxx::Segmentes segs;
sg.segment(buf, segs);
for(unsigned int i = 0; i < segs.size(); i++){
std::cout << segs[i] << std::endl;
}
}
return 0;
}
<|endoftext|> |
<commit_before>/***************************************************************************
** **
** Copyright (C) 2009-2010 Nokia Corporation. **
** **
** Author: Ilya Dogolazky <ilya.dogolazky@nokia.com> **
** Author: Simo Piiroinen <simo.piiroinen@nokia.com> **
** Author: Victor Portnov <ext-victor.portnov@nokia.com> **
** **
** This file is part of Timed **
** **
** Timed 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. **
** **
** Timed 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 Timed. If not, see http://www.gnu.org/licenses/ **
** **
***************************************************************************/
#include "adaptor.h"
#include "timed.h"
#include "event.h"
#include "timed/imagetype.h"
#include "timed/log.h"
#include "f.h"
#include <qmlog>
#include <QMetaType>
int main(int ac, char **av)
{
int syslog_level = qmlog::Full ;
int varlog_level = qmlog::Full ;
#if F_IMAGE_TYPE
#warning F_IMAGE_TYPE !
// string image_type = getenv("IMAGE_TYPE") ?: "" ;
string image_type = imagetype() ;
bool debug_flag = access(F_FORCE_DEBUG_PATH, F_OK) == 0 ;
if (not debug_flag)
{
if (image_type=="PR")
syslog_level = qmlog::None, varlog_level = qmlog::None ;
else if(image_type=="RD")
syslog_level = qmlog::Notice ;
else if(image_type=="TR")
syslog_level = qmlog::Info ;
}
#endif
// qmlog::init() ;
#if 0
qmlog::log_syslog *syslog = new qmlog::log_syslog(syslog_level) ;
#else
qmlog::syslog()->reduce_max_level(syslog_level) ;
#endif
qmlog::log_file *varlog = new qmlog::log_file("/var/log/timed.log", varlog_level) ;
varlog->enable_fields(qmlog::Monotonic_Milli | qmlog::Time_Milli) ;
if (not isatty(2)) // stderr is not a terminal -> no stderr logging
delete qmlog::stderr() ;
#if 0
qmlog::object.get_current_dispatcher()->bind_slave(LIBTIMED_LOGGING_DISPATCHER) ;
#else
LIBTIMED_LOGGING_DISPATCHER->set_proxy(qmlog::dispatcher()) ;
#endif
log_notice("time daemon started, debug_flag=%d, syslog_level=%d /var/log-level=%d", debug_flag, qmlog::syslog()->log_level(), varlog->log_level()) ;
#if F_IMAGE_TYPE
log_notice("image_type='%s'", image_type.c_str()) ;
#endif
// system("hwclock -s") ; // temporary hack
try
{
#if 0
customization_settings::check_customization(ac, av);
#endif
event_t::codec_initializer() ;
Timed *server = new Timed(ac,av) ;
int result = server->exec() ;
string halt = server->is_halted() ;
if (!halt.empty())
{
const char *cud = "clear-device", *rfs = "restore-original-settings" ;
if(halt==cud || halt==rfs)
{
log_info("halt: '%s' requested", halt.c_str()) ;
const char *rm_all_files = "rm -rf /var/cache/timed/*" ;
const char *rm_settings = "rm -rf /var/cache/timed/settings*" ;
const char *cmd = halt==cud ? rm_all_files : rm_settings ;
int res = system(cmd) ;
if (res != 0)
log_critical("'%s' failed with res=%d: %m", cmd, res) ;
else
log_info("cache files erased successfully by '%s'", cmd) ;
}
else
log_warning("unknown parameter in halt() request: '%s'", halt.c_str()) ;
log_info("Go to sleep, good night!") ;
for(;;)
sleep(99999) ;
}
return result ;
}
catch(const iodata::validator::exception &e)
{
log_critical("%s", e.info().c_str()) ;
}
catch(const iodata::exception &e)
{
log_critical("iodata::exception %s", e.info().c_str()) ;
}
catch(const std::exception &e)
{
log_critical("oops, unknown std::exception: %s", e.what()) ;
}
catch(...)
{
log_critical("oops, unknown exception of unknown type ...") ;
}
return 1 ;
}
<commit_msg>some clean up<commit_after>/***************************************************************************
** **
** Copyright (C) 2009-2010 Nokia Corporation. **
** **
** Author: Ilya Dogolazky <ilya.dogolazky@nokia.com> **
** Author: Simo Piiroinen <simo.piiroinen@nokia.com> **
** Author: Victor Portnov <ext-victor.portnov@nokia.com> **
** **
** This file is part of Timed **
** **
** Timed 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. **
** **
** Timed 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 Timed. If not, see http://www.gnu.org/licenses/ **
** **
***************************************************************************/
#include "adaptor.h"
#include "timed.h"
#include "event.h"
#include "timed/imagetype.h"
#include "timed/log.h"
#include "f.h"
#include <qmlog>
#include <QMetaType>
int main(int ac, char **av)
{
int syslog_level = qmlog::Full ;
int varlog_level = qmlog::Full ;
#if F_IMAGE_TYPE
string image_type = imagetype() ;
bool debug_flag = access(F_FORCE_DEBUG_PATH, F_OK) == 0 ;
if (not debug_flag)
{
if (image_type=="PR")
syslog_level = varlog_level = qmlog::None ;
else if(image_type=="RD")
syslog_level = qmlog::Notice ;
else if(image_type=="TR")
syslog_level = qmlog::Info ;
}
#endif
qmlog::syslog()->reduce_max_level(syslog_level) ;
qmlog::log_file *varlog = new qmlog::log_file("/var/log/timed.log", varlog_level) ;
varlog->enable_fields(qmlog::Monotonic_Milli | qmlog::Time_Milli) ;
if (not isatty(2)) // stderr is not a terminal -> no stderr logging
delete qmlog::stderr() ;
LIBTIMED_LOGGING_DISPATCHER->set_proxy(qmlog::dispatcher()) ;
log_notice("time daemon started, debug_flag=%d, syslog-level=%d /var/log-level=%d", debug_flag, qmlog::syslog()->log_level(), varlog->log_level()) ;
#if F_IMAGE_TYPE
log_notice("image_type='%s'", image_type.c_str()) ;
#endif
try
{
event_t::codec_initializer() ;
Timed *server = new Timed(ac,av) ;
int result = server->exec() ;
string halt = server->is_halted() ;
if (!halt.empty())
{
const char *cud = "clear-device", *rfs = "restore-original-settings" ;
if(halt==cud || halt==rfs)
{
log_info("halt: '%s' requested", halt.c_str()) ;
const char *rm_all_files = "rm -rf /var/cache/timed/*" ;
const char *rm_settings = "rm -rf /var/cache/timed/settings*" ;
const char *cmd = halt==cud ? rm_all_files : rm_settings ;
int res = system(cmd) ;
if (res != 0)
log_critical("'%s' failed with res=%d: %m", cmd, res) ;
else
log_info("cache files erased successfully by '%s'", cmd) ;
}
else
log_warning("unknown parameter in halt() request: '%s'", halt.c_str()) ;
log_info("Go to sleep, good night!") ;
for(;;)
sleep(99999) ;
}
return result ;
}
catch(const iodata::validator::exception &e)
{
log_critical("%s", e.info().c_str()) ;
}
catch(const iodata::exception &e)
{
log_critical("iodata::exception %s", e.info().c_str()) ;
}
catch(const std::exception &e)
{
log_critical("oops, unknown std::exception: %s", e.what()) ;
}
catch(...)
{
log_critical("oops, unknown exception of unknown type ...") ;
}
return 1 ;
}
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (C) 2003 by Unai Garro *
* ugarro@users.sourceforge.net *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#include <unistd.h>
#include <pwd.h>
#include <iostream>
#include <qhbox.h>
#include <qvbox.h>
#include <qvgroupbox.h>
#include <qlayout.h>
#include <qpixmap.h>
#include <qpushbutton.h>
#include <kconfig.h>
#include <kapp.h>
#include <kstandarddirs.h>
#include <klocale.h>
#include "setupwizard.h"
SetupWizard::SetupWizard(QWidget *parent, const char *name, bool modal, WFlags f):KWizard(parent,name, modal,f)
{
welcomePage= new WelcomePage(this);
addPage(welcomePage,i18n("Welcome to Krecipes"));
permissionsSetupPage=new PermissionsSetupPage(this);
addPage(permissionsSetupPage,i18n("Database Permissions"));
serverSetupPage = new ServerSetupPage(this);
addPage(serverSetupPage,i18n("Server Settings"));
savePage = new SavePage(this);
addPage(savePage,i18n("Finish and Save Settings"));
setFinishEnabled(savePage,true); // Enable finish button
setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
connect(finishButton(),SIGNAL(clicked()),this,SLOT(save()));
}
SetupWizard::~SetupWizard()
{
}
WelcomePage::WelcomePage(QWidget *parent):QWidget(parent)
{
QGridLayout *layout=new QGridLayout(this,1,1,0,0);
QSpacerItem *spacer_top=new QSpacerItem(10,10,QSizePolicy::Minimum, QSizePolicy::Fixed);
layout->addItem(spacer_top,0,1);
QSpacerItem *spacer_left=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(spacer_left,1,0);
QPixmap logoPixmap (locate("data", "krecipes/pics/wizard.png"));
logo=new QLabel(this);
logo->setPixmap(logoPixmap);
logo->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(logo,1,1);
QSpacerItem *spacer_from_image=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(spacer_from_image,1,2);
welcomeText=new QLabel(this);
welcomeText->setText(i18n("Thank you very much for choosing Krecipes.\nIt looks like this is the first time you are using it. This wizard will help you with the initial setup so that you can start using it quickly.\n\nWelcome and enjoy cooking! ;-) "));
welcomeText->setMinimumWidth(200);
welcomeText->setMaximumWidth(10000);
welcomeText->setSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::Minimum);
welcomeText->setAlignment( int( QLabel::WordBreak | QLabel::AlignTop |QLabel::AlignJustify ) );
layout->addWidget(welcomeText,1,3);
}
PermissionsSetupPage::PermissionsSetupPage(QWidget *parent):QWidget(parent)
{
QGridLayout *layout=new QGridLayout(this,1,1,0,0);
QSpacerItem *spacer_top=new QSpacerItem(10,10,QSizePolicy::Minimum, QSizePolicy::Fixed);
layout->addItem(spacer_top,0,1);
QSpacerItem *spacer_left=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(spacer_left,1,0);
// Explanation Text
permissionsText=new QLabel(this);
permissionsText->setText(i18n("This dialog will allow you to specify a MySQL account that has the necessary permissions access the KRecipes MySQL database.<br><br><b>Most users that use Krecipes and MySQL for the first time can just leave the default parameters and press Next.</b> <br><br>If you set a MySQL root password before, or you have already permissions as normal user, click on the appropriate option. Otherwise the account 'root' will be used, with no password."));
permissionsText->setMinimumWidth(200);
permissionsText->setMaximumWidth(10000);
permissionsText->setSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::Minimum);
permissionsText->setAlignment( int( QLabel::WordBreak | QLabel::AlignTop |QLabel::AlignJustify ) );
layout->addWidget(permissionsText,1,3);
// Logo
QPixmap permissionsSetupPixmap (locate("data", "krecipes/pics/dbpermissions.png"));
logo=new QLabel(this);
logo->setPixmap(permissionsSetupPixmap);
logo->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addMultiCellWidget(logo,1,8,1,1);
// Spacer to separate the logo
QSpacerItem *logoSpacer=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(logoSpacer,1,2);
// "The user already has permissions" checkbox
noSetupCheckBox=new QCheckBox(i18n("I have already set the necessary permissions"),this,"noSetupCheckBox");
layout->addWidget(noSetupCheckBox,3,3);
// root checkbox
rootCheckBox=new QCheckBox(i18n("I have already set a MySQL root/admin account"),this,"rootCheckBox");
layout->addWidget(rootCheckBox,4,3);
QSpacerItem *rootInfoSpacer=new QSpacerItem(10,10,QSizePolicy::Minimum,QSizePolicy::Fixed);
layout->addItem(rootInfoSpacer,5,3);
// MySQL root/admin info
QVGroupBox *rootInfoVGBox=new QVGroupBox(this,"rootInfoVGBox"); rootInfoVGBox->setTitle(i18n("MySQL root info"));
rootInfoVGBox->setEnabled(false); // Disable by default
rootInfoVGBox->setInsideSpacing(10);
layout->addWidget(rootInfoVGBox,6,3);
// Input boxes (widgets inserted below)
QHBox *userBox=new QHBox(rootInfoVGBox); userBox->setSpacing(10);
QHBox *passBox=new QHBox(rootInfoVGBox); passBox->setSpacing(10);
// User Entry
QLabel *userLabel=new QLabel(userBox); userLabel->setText(i18n("Username:"));
userEdit=new KLineEdit(userBox);
// Password Entry
QLabel *passLabel=new QLabel(passBox); passLabel->setText(i18n("Password:"));
passEdit=new KLineEdit(passBox);
passEdit->setEchoMode(QLineEdit::Password);
// Connect Signals & slots
connect(rootCheckBox,SIGNAL(toggled(bool)),rootInfoVGBox,SLOT(setEnabled(bool)));
connect(rootCheckBox,SIGNAL(toggled(bool)),noSetupCheckBox,SLOT(rootCheckBoxChanged(bool)));
connect(noSetupCheckBox,SIGNAL(toggled(bool)),rootCheckBox,SLOT(noSetupCheckBoxChanged(bool)));
}
void PermissionsSetupPage::rootCheckBoxChanged(bool on)
{
if (on) noSetupCheckBox->setChecked(false); // exclude mutually the options (both can be unset)
}
void PermissionsSetupPage::noSetupCheckBoxChanged(bool on)
{
if (on) rootCheckBox->setChecked(false); // exclude mutually the options (both can be unset)
}
ServerSetupPage::ServerSetupPage(QWidget *parent):QWidget(parent)
{
QGridLayout *layout=new QGridLayout(this,1,1,0,0);
QSpacerItem *spacer_top=new QSpacerItem(10,10,QSizePolicy::Minimum, QSizePolicy::Fixed);
layout->addItem(spacer_top,0,1);
QSpacerItem *spacer_left=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(spacer_left,1,0);
QPixmap networkSetupPixmap (locate("data", "krecipes/pics/network.png"));
logo=new QLabel(this);
logo->setPixmap(networkSetupPixmap);
logo->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addMultiCellWidget(logo,1,8,1,1);
QSpacerItem *spacer_from_image=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(spacer_from_image,1,2);
QLabel* serverText=new QLabel(i18n("Server:"), this);
serverText->setFixedSize(QSize(100,20));
serverText->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(serverText,1,3);
serverEdit=new KLineEdit(this);
serverEdit->setFixedSize(QSize(120,20));
serverEdit->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
serverEdit->setText("localhost");
layout->addWidget(serverEdit,1,4);
QSpacerItem* spacerRow1 = new QSpacerItem( 10,10, QSizePolicy::Minimum, QSizePolicy::Fixed );
layout->addItem( spacerRow1,2,3 );
QLabel* usernameText=new QLabel(i18n("Username:"), this);
usernameText->setFixedSize(QSize(100,20));
usernameText->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(usernameText,3,3);
usernameEdit=new KLineEdit(this);
usernameEdit->setFixedSize(QSize(120,20));
usernameEdit->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
// get username
uid_t userID; QString username;struct passwd *user;
userID=getuid();user=getpwuid (userID); username=user->pw_name;
usernameEdit->setText(username);
layout->addWidget(usernameEdit,3,4);
QSpacerItem* spacerRow2 = new QSpacerItem( 10,10, QSizePolicy::Minimum, QSizePolicy::Fixed );
layout->addItem( spacerRow2,4,3 );
QLabel* passwordText=new QLabel(i18n("Password:"), this);
passwordText->setFixedSize(QSize(100,20));
passwordText->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(passwordText,5,3);
passwordEdit=new KLineEdit(this);
passwordEdit->setFixedSize(QSize(120,20));
passwordEdit->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(passwordEdit,5,4);
QSpacerItem* spacerRow3 = new QSpacerItem( 10,10, QSizePolicy::Minimum, QSizePolicy::Fixed );
layout->addItem( spacerRow3, 6,3 );
QLabel* dbNameText=new QLabel(i18n("Database Name:"), this);
dbNameText->setFixedSize(QSize(100,20));
dbNameText->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(dbNameText,7,3);
dbNameEdit=new KLineEdit(this);
dbNameEdit->setFixedSize(QSize(120,20));
dbNameEdit->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
dbNameEdit->setText("Krecipes");
layout->addWidget(dbNameEdit,7,4);
QSpacerItem* spacerRow4 = new QSpacerItem( 10,10, QSizePolicy::Minimum, QSizePolicy::MinimumExpanding);
layout->addItem( spacerRow4, 8,3 );
QSpacerItem* spacerRight = new QSpacerItem( 10,10, QSizePolicy::MinimumExpanding, QSizePolicy::Fixed );
layout->addItem( spacerRight, 1,5 );
}
QString ServerSetupPage::server(void)
{
return(this->serverEdit->text());
}
QString ServerSetupPage::user(void)
{
return(this->usernameEdit->text());
}
QString ServerSetupPage::password(void)
{
return(this->passwordEdit->text());
}
QString ServerSetupPage::dbName(void)
{
return(this->dbNameEdit->text());;
}
SavePage::SavePage(QWidget *parent):QWidget(parent)
{
QGridLayout *layout=new QGridLayout(this,1,1,0,0);
QSpacerItem *spacer_top=new QSpacerItem(10,10,QSizePolicy::Minimum, QSizePolicy::Fixed);
layout->addItem(spacer_top,0,1);
QSpacerItem *spacer_left=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(spacer_left,1,0);
QPixmap logoPixmap (locate("data", "krecipes/pics/save.png"));
logo=new QLabel(this);
logo->setPixmap(logoPixmap);
logo->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(logo,1,1);
QSpacerItem *spacer_from_image=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(spacer_left,1,2);
saveText=new QLabel(this);
saveText->setText(i18n("Congratulations! All the necessary configuration setup are done. Press 'Finish' to continue, and enjoy cooking!"));
saveText->setMinimumWidth(200);
saveText->setMaximumWidth(10000);
saveText->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum);
saveText->setAlignment( int( QLabel::WordBreak | QLabel::AlignVCenter | QLabel::AlignJustify) );
layout->addWidget(saveText,1,3);
}
void SetupWizard::save(void)
{
KConfig *config=kapp->config();
// Save the server data
config->setGroup("Server");
config->writeEntry("Host",serverSetupPage->server());
config->writeEntry("Username",serverSetupPage->user());
config->writeEntry("Password",serverSetupPage->password());
config->writeEntry("DBName",serverSetupPage->dbName());
// Indicate that settings were already made
config->setGroup("Wizard");
config->writeEntry( "SystemSetup",true);
}
<commit_msg>Fix excluding checkboxes<commit_after>/***************************************************************************
* Copyright (C) 2003 by Unai Garro *
* ugarro@users.sourceforge.net *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#include <unistd.h>
#include <pwd.h>
#include <iostream>
#include <qhbox.h>
#include <qvbox.h>
#include <qvgroupbox.h>
#include <qlayout.h>
#include <qpixmap.h>
#include <qpushbutton.h>
#include <kconfig.h>
#include <kapp.h>
#include <kstandarddirs.h>
#include <klocale.h>
#include "setupwizard.h"
SetupWizard::SetupWizard(QWidget *parent, const char *name, bool modal, WFlags f):KWizard(parent,name, modal,f)
{
welcomePage= new WelcomePage(this);
addPage(welcomePage,i18n("Welcome to Krecipes"));
permissionsSetupPage=new PermissionsSetupPage(this);
addPage(permissionsSetupPage,i18n("Database Permissions"));
serverSetupPage = new ServerSetupPage(this);
addPage(serverSetupPage,i18n("Server Settings"));
savePage = new SavePage(this);
addPage(savePage,i18n("Finish and Save Settings"));
setFinishEnabled(savePage,true); // Enable finish button
setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
connect(finishButton(),SIGNAL(clicked()),this,SLOT(save()));
}
SetupWizard::~SetupWizard()
{
}
WelcomePage::WelcomePage(QWidget *parent):QWidget(parent)
{
QGridLayout *layout=new QGridLayout(this,1,1,0,0);
QSpacerItem *spacer_top=new QSpacerItem(10,10,QSizePolicy::Minimum, QSizePolicy::Fixed);
layout->addItem(spacer_top,0,1);
QSpacerItem *spacer_left=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(spacer_left,1,0);
QPixmap logoPixmap (locate("data", "krecipes/pics/wizard.png"));
logo=new QLabel(this);
logo->setPixmap(logoPixmap);
logo->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(logo,1,1);
QSpacerItem *spacer_from_image=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(spacer_from_image,1,2);
welcomeText=new QLabel(this);
welcomeText->setText(i18n("Thank you very much for choosing Krecipes.\nIt looks like this is the first time you are using it. This wizard will help you with the initial setup so that you can start using it quickly.\n\nWelcome and enjoy cooking! ;-) "));
welcomeText->setMinimumWidth(200);
welcomeText->setMaximumWidth(10000);
welcomeText->setSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::Minimum);
welcomeText->setAlignment( int( QLabel::WordBreak | QLabel::AlignTop |QLabel::AlignJustify ) );
layout->addWidget(welcomeText,1,3);
}
PermissionsSetupPage::PermissionsSetupPage(QWidget *parent):QWidget(parent)
{
QGridLayout *layout=new QGridLayout(this,1,1,0,0);
QSpacerItem *spacer_top=new QSpacerItem(10,10,QSizePolicy::Minimum, QSizePolicy::Fixed);
layout->addItem(spacer_top,0,1);
QSpacerItem *spacer_left=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(spacer_left,1,0);
// Explanation Text
permissionsText=new QLabel(this);
permissionsText->setText(i18n("This dialog will allow you to specify a MySQL account that has the necessary permissions access the KRecipes MySQL database.<br><br><b>Most users that use Krecipes and MySQL for the first time can just leave the default parameters and press Next.</b> <br><br>If you set a MySQL root password before, or you have already permissions as normal user, click on the appropriate option. Otherwise the account 'root' will be used, with no password."));
permissionsText->setMinimumWidth(200);
permissionsText->setMaximumWidth(10000);
permissionsText->setSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::Minimum);
permissionsText->setAlignment( int( QLabel::WordBreak | QLabel::AlignTop |QLabel::AlignJustify ) );
layout->addWidget(permissionsText,1,3);
// Logo
QPixmap permissionsSetupPixmap (locate("data", "krecipes/pics/dbpermissions.png"));
logo=new QLabel(this);
logo->setPixmap(permissionsSetupPixmap);
logo->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addMultiCellWidget(logo,1,8,1,1);
// Spacer to separate the logo
QSpacerItem *logoSpacer=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(logoSpacer,1,2);
// "The user already has permissions" checkbox
noSetupCheckBox=new QCheckBox(i18n("I have already set the necessary permissions"),this,"noSetupCheckBox");
layout->addWidget(noSetupCheckBox,3,3);
// root checkbox
rootCheckBox=new QCheckBox(i18n("I have already set a MySQL root/admin account"),this,"rootCheckBox");
layout->addWidget(rootCheckBox,4,3);
QSpacerItem *rootInfoSpacer=new QSpacerItem(10,10,QSizePolicy::Minimum,QSizePolicy::Fixed);
layout->addItem(rootInfoSpacer,5,3);
// MySQL root/admin info
QVGroupBox *rootInfoVGBox=new QVGroupBox(this,"rootInfoVGBox"); rootInfoVGBox->setTitle(i18n("MySQL root info"));
rootInfoVGBox->setEnabled(false); // Disable by default
rootInfoVGBox->setInsideSpacing(10);
layout->addWidget(rootInfoVGBox,6,3);
// Input boxes (widgets inserted below)
QHBox *userBox=new QHBox(rootInfoVGBox); userBox->setSpacing(10);
QHBox *passBox=new QHBox(rootInfoVGBox); passBox->setSpacing(10);
// User Entry
QLabel *userLabel=new QLabel(userBox); userLabel->setText(i18n("Username:"));
userEdit=new KLineEdit(userBox);
// Password Entry
QLabel *passLabel=new QLabel(passBox); passLabel->setText(i18n("Password:"));
passEdit=new KLineEdit(passBox);
passEdit->setEchoMode(QLineEdit::Password);
// Connect Signals & slots
connect(rootCheckBox,SIGNAL(toggled(bool)),rootInfoVGBox,SLOT(setEnabled(bool)));
connect(rootCheckBox,SIGNAL(toggled(bool)),this,SLOT(rootCheckBoxChanged(bool)));
connect(noSetupCheckBox,SIGNAL(toggled(bool)),this,SLOT(noSetupCheckBoxChanged(bool)));
}
void PermissionsSetupPage::rootCheckBoxChanged(bool on)
{
if (on) noSetupCheckBox->setChecked(false); // exclude mutually the options (both can be unset)
}
void PermissionsSetupPage::noSetupCheckBoxChanged(bool on)
{
if (on) rootCheckBox->setChecked(false); // exclude mutually the options (both can be unset)
}
ServerSetupPage::ServerSetupPage(QWidget *parent):QWidget(parent)
{
QGridLayout *layout=new QGridLayout(this,1,1,0,0);
QSpacerItem *spacer_top=new QSpacerItem(10,10,QSizePolicy::Minimum, QSizePolicy::Fixed);
layout->addItem(spacer_top,0,1);
QSpacerItem *spacer_left=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(spacer_left,1,0);
QPixmap networkSetupPixmap (locate("data", "krecipes/pics/network.png"));
logo=new QLabel(this);
logo->setPixmap(networkSetupPixmap);
logo->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addMultiCellWidget(logo,1,8,1,1);
QSpacerItem *spacer_from_image=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(spacer_from_image,1,2);
QLabel* serverText=new QLabel(i18n("Server:"), this);
serverText->setFixedSize(QSize(100,20));
serverText->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(serverText,1,3);
serverEdit=new KLineEdit(this);
serverEdit->setFixedSize(QSize(120,20));
serverEdit->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
serverEdit->setText("localhost");
layout->addWidget(serverEdit,1,4);
QSpacerItem* spacerRow1 = new QSpacerItem( 10,10, QSizePolicy::Minimum, QSizePolicy::Fixed );
layout->addItem( spacerRow1,2,3 );
QLabel* usernameText=new QLabel(i18n("Username:"), this);
usernameText->setFixedSize(QSize(100,20));
usernameText->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(usernameText,3,3);
usernameEdit=new KLineEdit(this);
usernameEdit->setFixedSize(QSize(120,20));
usernameEdit->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
// get username
uid_t userID; QString username;struct passwd *user;
userID=getuid();user=getpwuid (userID); username=user->pw_name;
usernameEdit->setText(username);
layout->addWidget(usernameEdit,3,4);
QSpacerItem* spacerRow2 = new QSpacerItem( 10,10, QSizePolicy::Minimum, QSizePolicy::Fixed );
layout->addItem( spacerRow2,4,3 );
QLabel* passwordText=new QLabel(i18n("Password:"), this);
passwordText->setFixedSize(QSize(100,20));
passwordText->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(passwordText,5,3);
passwordEdit=new KLineEdit(this);
passwordEdit->setFixedSize(QSize(120,20));
passwordEdit->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(passwordEdit,5,4);
QSpacerItem* spacerRow3 = new QSpacerItem( 10,10, QSizePolicy::Minimum, QSizePolicy::Fixed );
layout->addItem( spacerRow3, 6,3 );
QLabel* dbNameText=new QLabel(i18n("Database Name:"), this);
dbNameText->setFixedSize(QSize(100,20));
dbNameText->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(dbNameText,7,3);
dbNameEdit=new KLineEdit(this);
dbNameEdit->setFixedSize(QSize(120,20));
dbNameEdit->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
dbNameEdit->setText("Krecipes");
layout->addWidget(dbNameEdit,7,4);
QSpacerItem* spacerRow4 = new QSpacerItem( 10,10, QSizePolicy::Minimum, QSizePolicy::MinimumExpanding);
layout->addItem( spacerRow4, 8,3 );
QSpacerItem* spacerRight = new QSpacerItem( 10,10, QSizePolicy::MinimumExpanding, QSizePolicy::Fixed );
layout->addItem( spacerRight, 1,5 );
}
QString ServerSetupPage::server(void)
{
return(this->serverEdit->text());
}
QString ServerSetupPage::user(void)
{
return(this->usernameEdit->text());
}
QString ServerSetupPage::password(void)
{
return(this->passwordEdit->text());
}
QString ServerSetupPage::dbName(void)
{
return(this->dbNameEdit->text());;
}
SavePage::SavePage(QWidget *parent):QWidget(parent)
{
QGridLayout *layout=new QGridLayout(this,1,1,0,0);
QSpacerItem *spacer_top=new QSpacerItem(10,10,QSizePolicy::Minimum, QSizePolicy::Fixed);
layout->addItem(spacer_top,0,1);
QSpacerItem *spacer_left=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(spacer_left,1,0);
QPixmap logoPixmap (locate("data", "krecipes/pics/save.png"));
logo=new QLabel(this);
logo->setPixmap(logoPixmap);
logo->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(logo,1,1);
QSpacerItem *spacer_from_image=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(spacer_left,1,2);
saveText=new QLabel(this);
saveText->setText(i18n("Congratulations! All the necessary configuration setup are done. Press 'Finish' to continue, and enjoy cooking!"));
saveText->setMinimumWidth(200);
saveText->setMaximumWidth(10000);
saveText->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum);
saveText->setAlignment( int( QLabel::WordBreak | QLabel::AlignVCenter | QLabel::AlignJustify) );
layout->addWidget(saveText,1,3);
}
void SetupWizard::save(void)
{
KConfig *config=kapp->config();
// Save the server data
config->setGroup("Server");
config->writeEntry("Host",serverSetupPage->server());
config->writeEntry("Username",serverSetupPage->user());
config->writeEntry("Password",serverSetupPage->password());
config->writeEntry("DBName",serverSetupPage->dbName());
// Indicate that settings were already made
config->setGroup("Wizard");
config->writeEntry( "SystemSetup",true);
}
<|endoftext|> |
<commit_before>#include "game.hpp"
#include "component_drawable.hpp"
#include "component_position.hpp"
#include "component_player.hpp"
#include "entityx/entityx.h"
#include <glm/vec2.hpp>
#include <glm/glm.hpp>
#include <glm/gtx/polar_coordinates.hpp>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <sstream>
#include "strapon/resource_manager/resource_manager.hpp"
#include "strapon/sdl_helpers/sdl_helpers.hpp"
class DrawSystem : public entityx::System<DrawSystem> {
public:
DrawSystem(Game *game) : m_game(game) {
int w, h;
SDL_RenderGetLogicalSize(game->renderer(), &w, &h);
m_camera = SDL_Rect{0, 0, w, h};
m_drawtex =
SDL_CreateTexture(game->renderer(), SDL_PIXELTYPE_UNKNOWN, SDL_TEXTUREACCESS_TARGET,
game->world_size().w, game->world_size().h);
}
~DrawSystem() {
SDL_DestroyTexture(m_drawtex);
}
glm::vec2 polar_to_euclid(glm::vec2 i) {
glm::vec2 cart;
cart.x = glm::cos(i[1]) * i[0];
cart.y = glm::sin(i[1]) * i[0];
return cart;
}
void update(entityx::EntityManager &es, entityx::EventManager &events,
entityx::TimeDelta dt) override {
// Change to render into rendertexture for now
SDL_SetRenderTarget(m_game->renderer(), m_drawtex);
SDL_SetRenderDrawColor(m_game->renderer(), 0, 100, 200, 255);
SDL_RenderClear(m_game->renderer());
entityx::ComponentHandle<Drawable> drawable;
entityx::ComponentHandle<Position> position;
entityx::ComponentHandle<Player> player;
glm::vec2 player_pos;
for (entityx::Entity entity : es.entities_with_components(player, position)) {
player_pos = polar_to_euclid(entity.component<Position>()->position());
}
std::set<int> layers;
for (entityx::Entity entity : es.entities_with_components(drawable)) {
(void)entity;
layers.insert(drawable->layer());
}
for (auto layer : layers) {
for (entityx::Entity entity : es.entities_with_components(drawable, position)) {
if (drawable->layer() == layer) {
auto coord_polar = entity.component<Position>();
SDL_Rect dest;
// now follow the player
glm::vec2 coord_euclid = polar_to_euclid(coord_polar->position());
// Converted position
dest.x = coord_euclid[0];
dest.y = coord_euclid[1];
// Center on entity
dest.x -= drawable->width() / 2;
dest.y -= drawable->height() / 2;
// Translate onto player. In fact will do this later. Too confusing w/o other
// entities
dest.x += m_camera.w / 2;
dest.y += m_camera.h / 2;
dest.x -= player_pos.x;
dest.y -= player_pos.y;
dest.w = drawable->width();
dest.h = drawable->height();
SDL_RenderCopyEx(m_game->renderer(),
m_game->res_manager().texture(drawable->texture_key()), NULL,
&dest, 0, NULL, SDL_FLIP_NONE);
}
}
}
std::ostringstream os;
os << "Score: " << (int)player->score;
SDL_Color c = { 200, 200, 200, 0 };
draw_text(m_game->renderer(), m_game->res_manager(), os.str(), "font20", 0, 0, c);
// Render to final window
SDL_SetRenderTarget(m_game->renderer(), nullptr);
SDL_RenderCopy(m_game->renderer(), m_drawtex, &m_camera, nullptr);
SDL_RenderPresent(m_game->renderer());
}
private:
Game *m_game;
SDL_Rect m_camera;
SDL_Texture *m_drawtex;
};
<commit_msg>fixed rotation of field, only minor fixes missing<commit_after>#include "game.hpp"
#include "component_drawable.hpp"
#include "component_position.hpp"
#include "component_player.hpp"
#include "entityx/entityx.h"
#include <glm/vec2.hpp>
#include <glm/glm.hpp>
#include <glm/gtx/polar_coordinates.hpp>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <sstream>
#include "strapon/resource_manager/resource_manager.hpp"
#include "strapon/sdl_helpers/sdl_helpers.hpp"
#include<iostream>
class DrawSystem : public entityx::System<DrawSystem> {
public:
DrawSystem(Game *game) : m_game(game) {
int w, h;
SDL_RenderGetLogicalSize(game->renderer(), &w, &h);
m_camera = SDL_Rect{0, 0, w, h};
m_drawtex =
SDL_CreateTexture(game->renderer(), SDL_PIXELTYPE_UNKNOWN, SDL_TEXTUREACCESS_TARGET,
game->world_size().w, game->world_size().h);
m_maptex =
SDL_CreateTexture(game->renderer(), SDL_PIXELTYPE_UNKNOWN, SDL_TEXTUREACCESS_TARGET,
game->world_size().w, game->world_size().h);
}
~DrawSystem() {
SDL_DestroyTexture(m_drawtex);
}
glm::vec2 polar_to_euclid(glm::vec2 i) {
glm::vec2 cart;
cart.x = glm::cos(i[1]) * i[0];
cart.y = glm::sin(i[1]) * i[0];
return cart;
}
inline double rad_to_deg(double f)
{
return f / (2.0*3.14159265)*360.0; //TODO 2 PI
}
void render_entity(entityx::Entity& e, int woff, int hoff) {
auto drawable = e.component<Drawable>();
auto position = e.component<Position>(); //bad name -> change to.. polarpos?
glm::vec2 coord_euclid = polar_to_euclid(position->position());
// Copy the coordinates to dest
// and offset them by half the image size
SDL_Rect dest;
dest.x = coord_euclid.x - drawable->width()/2 + woff;
dest.y = coord_euclid.y - drawable->height()/2 + hoff;
dest.w = drawable->width();
dest.h = drawable->height();
SDL_Texture* tex = m_game->res_manager().texture(drawable->texture_key());
SDL_RenderCopyEx(m_game->renderer(), tex, nullptr, &dest,
-rad_to_deg(position->position().y), nullptr, SDL_FLIP_NONE);
}
void update(entityx::EntityManager &es, entityx::EventManager &events,
entityx::TimeDelta dt) override {
// so that we have less unreadable text
SDL_Renderer* rendr = m_game->renderer();
//FIRST render everything which is NOT THE PLAYER to maptex
SDL_SetRenderTarget(rendr, m_maptex);
SDL_SetRenderDrawColor(rendr, 0, 100, 200, 255);
SDL_RenderClear(rendr);
// GET the size of the texture so that we can center all drawables
// btw the texture is 4 times as large as the viewport
int woff, hoff;
SDL_QueryTexture(m_maptex, nullptr, nullptr, &woff, &hoff);
woff /= 2;
hoff /= 2;
//Therefore we need these handlers
entityx::ComponentHandle<Drawable> drawable;
entityx::ComponentHandle<Position> position;
//and we need to sort all the drawables by layers
std::set<int> layers;
for (entityx::Entity entity : es.entities_with_components(drawable)) {
(void)entity;
layers.insert(drawable->layer());
}
entityx::Entity player_entity;
for (auto layer : layers) {
for (entityx::Entity entity : es.entities_with_components(drawable, position)) {
if (drawable->layer() == layer && !entity.component<Player>()) {
render_entity(entity, woff, hoff);
}
else if(entity.component<Player>())
player_entity = entity;
}
}
/*glm::vec2 player_pos;
for (entityx::Entity entity : es.entities_with_components(player, position)) {
player_pos = polar_to_euclid(entity.component<Position>()->position());
}*/
// change the rendertarget to the pre-backbuffer
SDL_SetRenderTarget(rendr, m_drawtex);
SDL_SetRenderDrawColor(rendr, 0, 100, 200, 255);
auto player_pos = player_entity.component<Position>();
drawable = player_entity.component<Drawable>();
// copy a rotated version of the maptexture.
SDL_RenderCopyEx(rendr, m_maptex, nullptr, nullptr, rad_to_deg(player_pos->position().y), nullptr, SDL_FLIP_NONE);
// Render Player (pretend he is at alpha=-PI/2)
glm::vec2 coord_polar = player_pos->position();
coord_polar.y = 3.14159265 / 2.0;
glm::vec2 coord_euclid = polar_to_euclid(coord_polar);
// Copy the coordinates to dest
// and offset them by half the image size
SDL_Rect dest;
dest.x = coord_euclid.x - drawable->width()/2 + woff;
dest.y = coord_euclid.y - drawable->height()/2 + hoff;
dest.w = drawable->width();
dest.h = drawable->height();
SDL_Texture* tex = m_game->res_manager().texture(drawable->texture_key());
SDL_RenderCopy(rendr, tex, nullptr, &dest);
// Print the score of the player
std::ostringstream os;
os << "Score: " << (int) 4;//player->score;
SDL_Color c = { 200, 200, 200, 0 };
draw_text(rendr, m_game->res_manager(), os.str(), "font20", 0, 0, c);
// Render to final window
SDL_SetRenderTarget(rendr, nullptr);
SDL_RenderCopy(rendr, m_drawtex, &m_camera, nullptr);
SDL_RenderPresent(rendr);
}
private:
Game *m_game;
SDL_Rect m_camera;
SDL_Texture *m_drawtex;
SDL_Texture *m_maptex;
};
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <memory>
#include <boost/variant.hpp>
#include "tac/Printer.hpp"
#include "tac/Program.hpp"
#include "VisitorUtils.hpp"
#include "Utils.hpp"
using namespace eddic;
namespace {
struct ArgumentToString : public boost::static_visitor<std::string> {
std::string operator()(std::shared_ptr<Variable>& variable) const {
return variable->name();
}
std::string operator()(int& integer) const {
return toString(integer);
}
std::string operator()(double& float_) const {
return toString(float_);
}
std::string operator()(std::string& str) const {
return str;
}
};
std::string printArgument(tac::Argument& arg){
return visit(ArgumentToString(), arg);
}
struct DebugVisitor : public boost::static_visitor<> {
void operator()(tac::Program& program){
std::cout << "TAC Program " << std::endl << std::endl;
visit_each_non_variant(*this, program.functions);
}
void operator()(std::shared_ptr<tac::Function> function){
std::cout << "Function " << function->getName() << std::endl;
visit_each(*this, function->getStatements());
visit_each_non_variant(*this, function->getBasicBlocks());
std::cout << std::endl;
}
void operator()(std::shared_ptr<tac::BasicBlock>& block){
std::cout << "B" << block->index << "->" << std::endl;
visit_each(*this, block->statements);
}
void operator()(tac::Statement& statement){
visit(*this, statement);
}
void operator()(std::shared_ptr<tac::Quadruple>& quadruple){
if(quadruple->op == tac::Operator::ASSIGN){
std::cout << "\t" << quadruple->result->name() << " = (normal) " << printArgument(*quadruple->arg1) << std::endl;
} else if(quadruple->op == tac::Operator::FASSIGN){
std::cout << "\t" << quadruple->result->name() << " = (float) " << printArgument(*quadruple->arg1) << std::endl;
} else {
tac::Operator op = quadruple->op;
if(op == tac::Operator::ADD){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " + " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::FADD){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " + (float) " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::SUB){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " - " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::FSUB){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " - (float) " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::MUL){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " * " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::FMUL){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " * (float) " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::DIV){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " / " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::FDIV){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " / (float) " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::MOD){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " % " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::EQUALS || op == tac::Operator::FE){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " == " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::NOT_EQUALS || op == tac::Operator::FNE){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " != " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::GREATER || op == tac::Operator::FG){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " > " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::GREATER_EQUALS || op == tac::Operator::FGE){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " >= " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::LESS || op == tac::Operator::FL){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " < " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::LESS_EQUALS || op == tac::Operator::FLE){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " <= " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::MINUS){
std::cout << "\t" << quadruple->result->name() << " = - " << printArgument(*quadruple->arg1) << std::endl;
} else if(op == tac::Operator::DOT){
std::cout << "\t" << quadruple->result->name() << " = (" << printArgument(*quadruple->arg1) << ")" << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::DOT_ASSIGN){
std::cout << "\t(" << quadruple->result->name() << ")" << printArgument(*quadruple->arg1) << " = " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::ARRAY){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " [" << printArgument(*quadruple->arg2) << "]" << std::endl;
} else if(op == tac::Operator::ARRAY_ASSIGN){
std::cout << "\t" << quadruple->result->name() << "[" << printArgument(*quadruple->arg1) << "] = " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::RETURN){
std::cout << "\treturn";
if(quadruple->arg1){
std::cout << " " << printArgument(*quadruple->arg1);
}
if(quadruple->arg2){
std::cout << ", " << printArgument(*quadruple->arg2);
}
std::cout << std::endl;
}
}
}
template<typename T>
std::string printTarget(std::shared_ptr<T>& ifFalse){
if(ifFalse->block){
return "B" + toString(ifFalse->block->index);
} else {
return ifFalse->label;
}
}
void operator()(std::shared_ptr<tac::IfFalse>& ifFalse){
if(ifFalse->op){
auto op = *ifFalse->op;
if(op == tac::BinaryOperator::EQUALS || op == tac::BinaryOperator::FE){
std::cout << "\tifFalse " << printArgument(ifFalse->arg1) << " == " << printArgument(*ifFalse->arg2) << " goto " << printTarget(ifFalse) << std::endl;
} else if(op == tac::BinaryOperator::NOT_EQUALS || op == tac::BinaryOperator::FNE){
std::cout << "\tifFalse " << printArgument(ifFalse->arg1) << " != " << printArgument(*ifFalse->arg2) << " goto " << printTarget(ifFalse) << std::endl;
} else if(op == tac::BinaryOperator::LESS || op == tac::BinaryOperator::FL){
std::cout << "\tifFalse " << printArgument(ifFalse->arg1) << " < " << printArgument(*ifFalse->arg2) << " goto " << printTarget(ifFalse) << std::endl;
} else if(op == tac::BinaryOperator::LESS_EQUALS || op == tac::BinaryOperator::FLE){
std::cout << "\tifFalse " << printArgument(ifFalse->arg1) << " <= " << printArgument(*ifFalse->arg2) << " goto " << printTarget(ifFalse) << std::endl;
} else if(op == tac::BinaryOperator::GREATER || op == tac::BinaryOperator::FG){
std::cout << "\tifFalse " << printArgument(ifFalse->arg1) << " > " << printArgument(*ifFalse->arg2) << " goto " << printTarget(ifFalse) << std::endl;
} else if(op == tac::BinaryOperator::GREATER_EQUALS || op == tac::BinaryOperator::FGE){
std::cout << "\tifFalse " << printArgument(ifFalse->arg1) << " >= " << printArgument(*ifFalse->arg2) << " goto " << printTarget(ifFalse) << std::endl;
}
} else {
std::cout << "\tifFalse " << printArgument(ifFalse->arg1) << " goto " << printTarget(ifFalse) << std::endl;
}
}
void operator()(std::shared_ptr<tac::If>& ifFalse){
if(ifFalse->op){
if(*ifFalse->op == tac::BinaryOperator::EQUALS){
std::cout << "\tif " << printArgument(ifFalse->arg1) << " == " << printArgument(*ifFalse->arg2) << " goto " << printTarget(ifFalse) << std::endl;
} else if(*ifFalse->op == tac::BinaryOperator::NOT_EQUALS){
std::cout << "\tif " << printArgument(ifFalse->arg1) << " != " << printArgument(*ifFalse->arg2) << " goto " << printTarget(ifFalse) << std::endl;
} else if(*ifFalse->op == tac::BinaryOperator::LESS){
std::cout << "\tif " << printArgument(ifFalse->arg1) << " < " << printArgument(*ifFalse->arg2) << " goto " << printTarget(ifFalse) << std::endl;
} else if(*ifFalse->op == tac::BinaryOperator::LESS_EQUALS){
std::cout << "\tif " << printArgument(ifFalse->arg1) << " <= " << printArgument(*ifFalse->arg2) << " goto " << printTarget(ifFalse) << std::endl;
} else if(*ifFalse->op == tac::BinaryOperator::GREATER){
std::cout << "\tif " << printArgument(ifFalse->arg1) << " > " << printArgument(*ifFalse->arg2) << " goto " << printTarget(ifFalse) << std::endl;
} else if(*ifFalse->op == tac::BinaryOperator::GREATER_EQUALS){
std::cout << "\tif " << printArgument(ifFalse->arg1) << " >= " << printArgument(*ifFalse->arg2) << " goto " << printTarget(ifFalse) << std::endl;
}
} else {
std::cout << "\tifFalse " << printArgument(ifFalse->arg1) << " goto " << printTarget(ifFalse) << std::endl;
}
}
void operator()(std::shared_ptr<tac::Param>& param){
if(param->param){
std::cout << "\tparam (" << param->param->name() << ")" << printArgument(param->arg) << std::endl;
} else {
std::cout << "\tparam " << printArgument(param->arg) << std::endl;
}
}
void operator()(std::shared_ptr<tac::Goto>& goto_){
std::cout << "\tgoto " << printTarget(goto_) << std::endl;
}
void operator()(tac::NoOp&){
std::cout << "\tno-op" << std::endl;
}
void operator()(std::shared_ptr<tac::Call>& call){
std::cout << "\t";
if(call->return_){
std::cout << call->return_->name();
}
if(call->return2_){
std::cout << ", " << call->return2_->name();
}
if(call->return_ || call->return2_){
std::cout << " = ";
}
std::cout << "call " << call->function << std::endl;
}
void operator()(std::string& label){
std::cout << "\t" << label << ":" << std::endl;
}
};
} //end of anonymous namespace
void tac::Printer::print(tac::Program& program) const {
DebugVisitor visitor;
visitor(program);
}
void tac::Printer::print(tac::Statement& statement) const {
DebugVisitor visitor;
visit(visitor, statement);
}
<commit_msg>Fix the output<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <memory>
#include <boost/variant.hpp>
#include "tac/Printer.hpp"
#include "tac/Program.hpp"
#include "VisitorUtils.hpp"
#include "Utils.hpp"
using namespace eddic;
namespace {
struct ArgumentToString : public boost::static_visitor<std::string> {
std::string operator()(std::shared_ptr<Variable>& variable) const {
return variable->name();
}
std::string operator()(int& integer) const {
return toString(integer);
}
std::string operator()(double& float_) const {
return toString(float_);
}
std::string operator()(std::string& str) const {
return str;
}
};
std::string printArgument(tac::Argument& arg){
return visit(ArgumentToString(), arg);
}
struct DebugVisitor : public boost::static_visitor<> {
void operator()(tac::Program& program){
std::cout << "TAC Program " << std::endl << std::endl;
visit_each_non_variant(*this, program.functions);
}
void operator()(std::shared_ptr<tac::Function> function){
std::cout << "Function " << function->getName() << std::endl;
visit_each(*this, function->getStatements());
visit_each_non_variant(*this, function->getBasicBlocks());
std::cout << std::endl;
}
void operator()(std::shared_ptr<tac::BasicBlock>& block){
std::cout << "B" << block->index << "->" << std::endl;
visit_each(*this, block->statements);
}
void operator()(tac::Statement& statement){
visit(*this, statement);
}
void operator()(std::shared_ptr<tac::Quadruple>& quadruple){
if(quadruple->op == tac::Operator::ASSIGN){
std::cout << "\t" << quadruple->result->name() << " = (normal) " << printArgument(*quadruple->arg1) << std::endl;
} else if(quadruple->op == tac::Operator::FASSIGN){
std::cout << "\t" << quadruple->result->name() << " = (float) " << printArgument(*quadruple->arg1) << std::endl;
} else {
tac::Operator op = quadruple->op;
if(op == tac::Operator::ADD){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " + " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::FADD){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " + (float) " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::SUB){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " - " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::FSUB){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " - (float) " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::MUL){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " * " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::FMUL){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " * (float) " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::DIV){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " / " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::FDIV){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " / (float) " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::MOD){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " % " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::EQUALS || op == tac::Operator::FE){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " == " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::NOT_EQUALS || op == tac::Operator::FNE){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " != " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::GREATER || op == tac::Operator::FG){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " > " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::GREATER_EQUALS || op == tac::Operator::FGE){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " >= " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::LESS || op == tac::Operator::FL){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " < " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::LESS_EQUALS || op == tac::Operator::FLE){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " <= " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::MINUS){
std::cout << "\t" << quadruple->result->name() << " = - " << printArgument(*quadruple->arg1) << std::endl;
} else if(op == tac::Operator::DOT){
std::cout << "\t" << quadruple->result->name() << " = (" << printArgument(*quadruple->arg1) << ")" << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::DOT_ASSIGN){
std::cout << "\t(" << quadruple->result->name() << ")" << printArgument(*quadruple->arg1) << " = " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::ARRAY){
std::cout << "\t" << quadruple->result->name() << " = " << printArgument(*quadruple->arg1) << " [" << printArgument(*quadruple->arg2) << "]" << std::endl;
} else if(op == tac::Operator::ARRAY_ASSIGN){
std::cout << "\t" << quadruple->result->name() << "[" << printArgument(*quadruple->arg1) << "] = " << printArgument(*quadruple->arg2) << std::endl;
} else if(op == tac::Operator::RETURN){
std::cout << "\treturn";
if(quadruple->arg1){
std::cout << " " << printArgument(*quadruple->arg1);
}
if(quadruple->arg2){
std::cout << ", " << printArgument(*quadruple->arg2);
}
std::cout << std::endl;
}
}
}
template<typename T>
std::string printTarget(std::shared_ptr<T>& ifFalse){
if(ifFalse->block){
return "B" + toString(ifFalse->block->index);
} else {
return ifFalse->label;
}
}
void operator()(std::shared_ptr<tac::IfFalse>& ifFalse){
if(ifFalse->op){
auto op = *ifFalse->op;
if(op == tac::BinaryOperator::EQUALS || op == tac::BinaryOperator::FE){
std::cout << "\tifFalse " << printArgument(ifFalse->arg1) << " == " << printArgument(*ifFalse->arg2) << " goto " << printTarget(ifFalse) << std::endl;
} else if(op == tac::BinaryOperator::NOT_EQUALS || op == tac::BinaryOperator::FNE){
std::cout << "\tifFalse " << printArgument(ifFalse->arg1) << " != " << printArgument(*ifFalse->arg2) << " goto " << printTarget(ifFalse) << std::endl;
} else if(op == tac::BinaryOperator::LESS || op == tac::BinaryOperator::FL){
std::cout << "\tifFalse " << printArgument(ifFalse->arg1) << " < " << printArgument(*ifFalse->arg2) << " goto " << printTarget(ifFalse) << std::endl;
} else if(op == tac::BinaryOperator::LESS_EQUALS || op == tac::BinaryOperator::FLE){
std::cout << "\tifFalse " << printArgument(ifFalse->arg1) << " <= " << printArgument(*ifFalse->arg2) << " goto " << printTarget(ifFalse) << std::endl;
} else if(op == tac::BinaryOperator::GREATER || op == tac::BinaryOperator::FG){
std::cout << "\tifFalse " << printArgument(ifFalse->arg1) << " > " << printArgument(*ifFalse->arg2) << " goto " << printTarget(ifFalse) << std::endl;
} else if(op == tac::BinaryOperator::GREATER_EQUALS || op == tac::BinaryOperator::FGE){
std::cout << "\tifFalse " << printArgument(ifFalse->arg1) << " >= " << printArgument(*ifFalse->arg2) << " goto " << printTarget(ifFalse) << std::endl;
}
} else {
std::cout << "\tifFalse " << printArgument(ifFalse->arg1) << " goto " << printTarget(ifFalse) << std::endl;
}
}
void operator()(std::shared_ptr<tac::If>& ifFalse){
if(ifFalse->op){
if(*ifFalse->op == tac::BinaryOperator::EQUALS){
std::cout << "\tif " << printArgument(ifFalse->arg1) << " == " << printArgument(*ifFalse->arg2) << " goto " << printTarget(ifFalse) << std::endl;
} else if(*ifFalse->op == tac::BinaryOperator::NOT_EQUALS){
std::cout << "\tif " << printArgument(ifFalse->arg1) << " != " << printArgument(*ifFalse->arg2) << " goto " << printTarget(ifFalse) << std::endl;
} else if(*ifFalse->op == tac::BinaryOperator::LESS){
std::cout << "\tif " << printArgument(ifFalse->arg1) << " < " << printArgument(*ifFalse->arg2) << " goto " << printTarget(ifFalse) << std::endl;
} else if(*ifFalse->op == tac::BinaryOperator::LESS_EQUALS){
std::cout << "\tif " << printArgument(ifFalse->arg1) << " <= " << printArgument(*ifFalse->arg2) << " goto " << printTarget(ifFalse) << std::endl;
} else if(*ifFalse->op == tac::BinaryOperator::GREATER){
std::cout << "\tif " << printArgument(ifFalse->arg1) << " > " << printArgument(*ifFalse->arg2) << " goto " << printTarget(ifFalse) << std::endl;
} else if(*ifFalse->op == tac::BinaryOperator::GREATER_EQUALS){
std::cout << "\tif " << printArgument(ifFalse->arg1) << " >= " << printArgument(*ifFalse->arg2) << " goto " << printTarget(ifFalse) << std::endl;
}
} else {
std::cout << "\tifFalse " << printArgument(ifFalse->arg1) << " goto " << printTarget(ifFalse) << std::endl;
}
}
void operator()(std::shared_ptr<tac::Param>& param){
if(param->param){
std::cout << "\tparam (" << param->param->name() << ") " << printArgument(param->arg) << std::endl;
} else {
std::cout << "\tparam " << printArgument(param->arg) << std::endl;
}
}
void operator()(std::shared_ptr<tac::Goto>& goto_){
std::cout << "\tgoto " << printTarget(goto_) << std::endl;
}
void operator()(tac::NoOp&){
std::cout << "\tno-op" << std::endl;
}
void operator()(std::shared_ptr<tac::Call>& call){
std::cout << "\t";
if(call->return_){
std::cout << call->return_->name();
}
if(call->return2_){
std::cout << ", " << call->return2_->name();
}
if(call->return_ || call->return2_){
std::cout << " = ";
}
std::cout << "call " << call->function << std::endl;
}
void operator()(std::string& label){
std::cout << "\t" << label << ":" << std::endl;
}
};
} //end of anonymous namespace
void tac::Printer::print(tac::Program& program) const {
DebugVisitor visitor;
visitor(program);
}
void tac::Printer::print(tac::Statement& statement) const {
DebugVisitor visitor;
visit(visitor, statement);
}
<|endoftext|> |
<commit_before>/*
*
* Copyright 2014 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Fermin Galan
*/
#include <string>
#include <sstream>
#include "mongoBackend/TriggeredSubscription.h"
/* ****************************************************************************
*
* TriggeredSubscription::TriggeredSubscription -
*/
TriggeredSubscription::TriggeredSubscription
(
long long _throttling,
long long _lastNotification,
Format _format,
const std::string& _reference,
AttributeList _attrL,
const std::string& _cacheSubId,
const char* _tenant
)
{
throttling = _throttling;
lastNotification = _lastNotification;
format = _format;
reference = _reference;
attrL = _attrL;
cacheSubId = _cacheSubId;
tenant = (_tenant == NULL)? "" : _tenant;
}
/* ****************************************************************************
*
* TriggeredSubscription::TriggeredSubscription -
*
* Constructor without throttling (for NGSI9 subscriptions)
*/
TriggeredSubscription::TriggeredSubscription
(
Format _format,
const std::string& _reference,
AttributeList _attrL
)
{
throttling = -1;
lastNotification = -1;
format = _format;
reference = _reference;
attrL = _attrL;
cacheSubId = "";
tenant = "";
}
/* ****************************************************************************
*
* TriggeredSubscription::toString -
*/
std::string TriggeredSubscription::toString(const std::string& delimiter)
{
std::stringstream ss;
ss << throttling << delimiter << lastNotification << delimiter << formatToString(format) << delimiter << reference;
return ss.str();
}
<commit_msg>use initiazation list in constructor<commit_after>/*
*
* Copyright 2014 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Fermin Galan
*/
#include <string>
#include <sstream>
#include "mongoBackend/TriggeredSubscription.h"
/* ****************************************************************************
*
* TriggeredSubscription::TriggeredSubscription -
*/
TriggeredSubscription::TriggeredSubscription
(
long long _throttling,
long long _lastNotification,
Format _format,
const std::string& _reference,
AttributeList _attrL,
const std::string& _cacheSubId,
const char* _tenant
):
throttling (_throttling),
lastNotification (_lastNotification),
format (_format),
reference (_reference),
attrL (_attrL),
cacheSubId (_cacheSubId),
tenant ((_tenant == NULL)? "" : _tenant)
{
}
/* ****************************************************************************
*
* TriggeredSubscription::TriggeredSubscription -
*
* Constructor without throttling (for NGSI9 subscriptions)
*/
TriggeredSubscription::TriggeredSubscription
(
Format _format,
const std::string& _reference,
AttributeList _attrL
):
throttling (-1),
lastNotification (-1),
format (_format),
reference (_reference),
attrL (_attrL),
cacheSubId (""),
tenant ("")
{
}
/* ****************************************************************************
*
* TriggeredSubscription::toString -
*/
std::string TriggeredSubscription::toString(const std::string& delimiter)
{
std::stringstream ss;
ss << throttling << delimiter << lastNotification << delimiter << formatToString(format) << delimiter << reference;
return ss.str();
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qgeotiledmappingmanagerengine.h"
#include "qgeotiledmappingmanagerengine_p.h"
#include "qgeotiledmapviewport.h"
#include "qgeotiledmaprequest.h"
#include "qgeotiledmappingmanagerthread.h"
#include <QPainter>
#include <QTimer>
#include <QNetworkAccessManager>
#include <QNetworkDiskCache>
#include <QDebug>
QTM_BEGIN_NAMESPACE
/*!
Constructs a QGeoTiledMappingManagerEngine object.
*/
QGeoTiledMappingManagerEngine::QGeoTiledMappingManagerEngine(const QMap<QString, QString> ¶meters, QObject *parent)
: QGeoMappingManagerEngine(new QGeoTiledMappingManagerEnginePrivate(parameters), parent)
{
setTileSize(QSize(128, 128));
QTimer::singleShot(0, this, SLOT(init()));
}
void QGeoTiledMappingManagerEngine::init()
{
Q_D(QGeoTiledMappingManagerEngine);
d->thread = createTileManagerThread();
d->thread->start();
}
/*!
Destroys this QGeoTiledMappingManagerEngine object.
*/
QGeoTiledMappingManagerEngine::~QGeoTiledMappingManagerEngine()
{
Q_D(QGeoTiledMappingManagerEngine);
d->thread->quit();
d->thread->wait();
}
QGeoMapViewport* QGeoTiledMappingManagerEngine::createViewport(QGeoMapWidget *widget)
{
return new QGeoTiledMapViewport(this, widget);
}
void QGeoTiledMappingManagerEngine::updateMapImage(QGeoMapViewport *viewport)
{
Q_D(QGeoTiledMappingManagerEngine);
if (!viewport)
return;
// deal with pole viewing later (needs more than two coords)
// determine tile indices to fetch
QPoint tileIndicesTopLeft = screenPositionToTilePosition(viewport, QPointF(0.0, 0.0));
QPoint tileIndicesBottomRight = screenPositionToTilePosition(viewport, QPointF(viewport->viewportSize().width(), viewport->viewportSize().height()));
int tileMinX = tileIndicesTopLeft.x();
int tileMaxX = tileIndicesBottomRight.x();
int tileMinY = tileIndicesTopLeft.y();
int tileMaxY = tileIndicesBottomRight.y();
int numTiles = 1 << qRound(viewport->zoomLevel());
//TODO: replace this QList-based implementation with a more mem-lightweight solution like a la TileIterator
QList<int> cols;
if (tileMinX <= tileMaxX) {
for (int i = tileMinX; i <= tileMaxX; ++i)
cols << i;
} else {
for (int i = tileMinX; i < numTiles; ++i)
cols << i;
for (int i = 0; i <= tileMaxX; ++i)
cols << i;
}
QList<int> rows;
if (tileMinY <= tileMaxY) {
for (int i = tileMinY; i <= tileMaxY; ++i)
rows << i;
} else {
for (int i = tileMinY; i < numTiles; ++i)
rows << i;
for (int i = 0; i <= tileMaxY; ++i)
rows << i;
}
int tileHeight = tileSize().height();
int tileWidth = tileSize().width();
//TODO: need to have some form of type checking in here
QGeoTiledMapViewport *tiledViewport = static_cast<QGeoTiledMapViewport*>(viewport);
QList<QGeoTiledMapRequest> requests;
QList<QPair<int, int> > tiles;
QRectF protectedRegion = tiledViewport->protectedRegion();
// TODO order in direction of travel if panning
// TODO request excess tiles around border
for (int x = 0; x < cols.size(); ++x) {
for (int y = 0; y < rows.size(); ++y) {
tiles.append(qMakePair(cols.at(x), rows.at(y)));
}
}
for (int i = 0; i < tiles.size(); ++i) {
int col = tiles.at(i).first;
int row = tiles.at(i).second;
int colOffset = 0;
if ((tileMinX > tileMaxX) && col <= tileMaxX)
colOffset = numTiles;
QRectF tileRect = QRectF((col + colOffset) * tileWidth, row * tileHeight, tileWidth, tileHeight);
// Protected region is the area that was on the screen before the
// start of a resize or pan.
// We shouldn't request tiles that are entirely contained in this
// region.
if (protectedRegion.isNull() || !protectedRegion.contains(tileRect))
requests.append(QGeoTiledMapRequest(tiledViewport, row, col, tileRect));
}
emit tileRequestsPrepared(tiledViewport, requests);
tiledViewport->clearProtectedRegion();
}
void QGeoTiledMappingManagerEngine::tileFinished(QGeoTiledMapReply *reply)
{
if (!reply)
return;
if (reply->error() != QGeoTiledMapReply::NoError) {
QTimer::singleShot(0, reply, SLOT(deleteLater()));
return;
}
QGeoTiledMapViewport *viewport = reply->request().viewport();
if ((viewport->zoomLevel() != reply->request().zoomLevel())
|| (viewport->mapType() != reply->request().mapType())) {
QTimer::singleShot(0, reply, SLOT(deleteLater()));
return;
}
QRectF screenRect = viewport->screenRect();
QRectF tileRect = reply->request().tileRect();
QRectF overlap = tileRect.intersected(screenRect);
if (overlap.isEmpty()) {
QTimer::singleShot(0, reply, SLOT(deleteLater()));
return;
}
QRectF source = overlap.translated(-1.0 * tileRect.x(), -1.0 * tileRect.y());
QRectF dest = overlap.translated(-1.0 * screenRect.x(), -1.0 * screenRect.y());
QPixmap pm = viewport->mapImage();
QPainter *painter = new QPainter(&pm);
painter->drawPixmap(dest, reply->mapImage(), source);
viewport->setMapImage(pm);
delete painter;
QTimer::singleShot(0, reply, SLOT(deleteLater()));
}
void QGeoTiledMappingManagerEngine::tileError(QGeoTiledMapReply *reply, QGeoTiledMapReply::Error error, QString errorString)
{
qWarning() << errorString;
}
QPoint QGeoTiledMappingManagerEngine::screenPositionToTilePosition(const QGeoMapViewport *viewport, const QPointF &screenPosition) const
{
// TODO checking mechanism for viewport type?
const QGeoTiledMapViewport *tiledViewport = static_cast<const QGeoTiledMapViewport*>(viewport);
return tiledViewport->screenPositionToTileIndices(screenPosition);
}
/*!
Returns a list of the image formats supported by this QGeoTiledMappingManagerEngine
instance.
\sa QGeoTiledMappingManagerEngine::setSupportedImageFormats()
*/
QList<QString> QGeoTiledMappingManagerEngine::supportedImageFormats() const
{
Q_D(const QGeoTiledMappingManagerEngine);
return d->supportedImageFormats;
}
QSize QGeoTiledMappingManagerEngine::tileSize() const
{
Q_D(const QGeoTiledMappingManagerEngine);
return d->tileSize;
}
/*!
Sets the list of image formats supported by this QGeoTiledMappingManagerEngine
instance to \a imageFormats.
Subclasses of QGeoCodingService should use this function to ensure that
supportedImageFormats() provides accurate information.
\sa QGeoTiledMappingManagerEngine::supportedImageFormats()
*/
void QGeoTiledMappingManagerEngine::setSupportedImageFormats(const QList<QString> &imageFormats)
{
Q_D(QGeoTiledMappingManagerEngine);
d->supportedImageFormats = imageFormats;
}
void QGeoTiledMappingManagerEngine::setTileSize(const QSize &tileSize)
{
Q_D(QGeoTiledMappingManagerEngine);
d->tileSize = tileSize;
}
/*!
\fn void QGeoTiledMappingManagerEngine::replyFinished(QGeoMapReply *reply)
Indicates that a request handled by this QGeoTiledMappingManagerEngine object has
finished successfully. The result of the request will be in \a reply.
Note that \a reply will be the same object returned by this
QGeoTiledMappingManagerEngine instance when the request was issued, and that the
QGeoMapReply::finished() signal can be used instead of this signal if it
is more convinient to do so.
Do not delete the QGeoMapReply object in a slot connected to this signal
- use deleteLater() if it is necessary to do so.
\sa QGeoMapReply::finished()
*/
/*!
\fn void QGeoTiledMappingManagerEngine::replyError(QGeoMapReply *reply,
QGeoTiledMappingManagerEngine::ErrorCode errorCode,
QString errorString);
Indicates that a request handled by this QGeoTiledMappingManagerEngine object has
failed. The error is described by \a errorCode and \a errorString, and \a
reply is the QGeoMapReply object which was managing the result of the
corresponding service request.
Note that \a reply will be the same object returned by this
QGeoTiledMappingManagerEngine instance when the request was issued, and that the
QGeoMapReply::error() signal can be used instead of this signal if it is
more convinient to do so.
Do not delete the QGeoMapReply object in a slot connected to this signal
- use deleteLater() if it is necessary to do so.
\sa QGeoMapReply::error()
*/
/*******************************************************************************
*******************************************************************************/
QGeoTiledMappingManagerEnginePrivate::QGeoTiledMappingManagerEnginePrivate(const QMap<QString, QString> ¶meters)
: QGeoMappingManagerEnginePrivate(parameters) {}
QGeoTiledMappingManagerEnginePrivate::QGeoTiledMappingManagerEnginePrivate(const QGeoTiledMappingManagerEnginePrivate &other)
: QGeoMappingManagerEnginePrivate(other),
supportedImageFormats(other.supportedImageFormats),
tileSize(other.tileSize),
thread(other.thread) {}
QGeoTiledMappingManagerEnginePrivate::~QGeoTiledMappingManagerEnginePrivate() {}
QGeoTiledMappingManagerEnginePrivate& QGeoTiledMappingManagerEnginePrivate::operator= (const QGeoTiledMappingManagerEnginePrivate & other)
{
QGeoMappingManagerEnginePrivate::operator =(other);
supportedImageFormats = other.supportedImageFormats;
tileSize = other.tileSize;
thread = other.thread;
return *this;
}
///*******************************************************************************
//*******************************************************************************/
#include "moc_qgeotiledmappingmanagerengine.cpp"
QTM_END_NAMESPACE
<commit_msg>Fix QGeoTiledMappingManagerEngine destructor when init is not called<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qgeotiledmappingmanagerengine.h"
#include "qgeotiledmappingmanagerengine_p.h"
#include "qgeotiledmapviewport.h"
#include "qgeotiledmaprequest.h"
#include "qgeotiledmappingmanagerthread.h"
#include <QPainter>
#include <QTimer>
#include <QNetworkAccessManager>
#include <QNetworkDiskCache>
#include <QDebug>
QTM_BEGIN_NAMESPACE
/*!
Constructs a QGeoTiledMappingManagerEngine object.
*/
QGeoTiledMappingManagerEngine::QGeoTiledMappingManagerEngine(const QMap<QString, QString> ¶meters, QObject *parent)
: QGeoMappingManagerEngine(new QGeoTiledMappingManagerEnginePrivate(parameters), parent)
{
setTileSize(QSize(128, 128));
QTimer::singleShot(0, this, SLOT(init()));
}
void QGeoTiledMappingManagerEngine::init()
{
Q_D(QGeoTiledMappingManagerEngine);
d->thread = createTileManagerThread();
d->thread->start();
}
/*!
Destroys this QGeoTiledMappingManagerEngine object.
*/
QGeoTiledMappingManagerEngine::~QGeoTiledMappingManagerEngine()
{
Q_D(QGeoTiledMappingManagerEngine);
if(d->thread) {
d->thread->quit();
d->thread->wait();
}
}
QGeoMapViewport* QGeoTiledMappingManagerEngine::createViewport(QGeoMapWidget *widget)
{
return new QGeoTiledMapViewport(this, widget);
}
void QGeoTiledMappingManagerEngine::updateMapImage(QGeoMapViewport *viewport)
{
Q_D(QGeoTiledMappingManagerEngine);
if (!viewport)
return;
// deal with pole viewing later (needs more than two coords)
// determine tile indices to fetch
QPoint tileIndicesTopLeft = screenPositionToTilePosition(viewport, QPointF(0.0, 0.0));
QPoint tileIndicesBottomRight = screenPositionToTilePosition(viewport, QPointF(viewport->viewportSize().width(), viewport->viewportSize().height()));
int tileMinX = tileIndicesTopLeft.x();
int tileMaxX = tileIndicesBottomRight.x();
int tileMinY = tileIndicesTopLeft.y();
int tileMaxY = tileIndicesBottomRight.y();
int numTiles = 1 << qRound(viewport->zoomLevel());
//TODO: replace this QList-based implementation with a more mem-lightweight solution like a la TileIterator
QList<int> cols;
if (tileMinX <= tileMaxX) {
for (int i = tileMinX; i <= tileMaxX; ++i)
cols << i;
} else {
for (int i = tileMinX; i < numTiles; ++i)
cols << i;
for (int i = 0; i <= tileMaxX; ++i)
cols << i;
}
QList<int> rows;
if (tileMinY <= tileMaxY) {
for (int i = tileMinY; i <= tileMaxY; ++i)
rows << i;
} else {
for (int i = tileMinY; i < numTiles; ++i)
rows << i;
for (int i = 0; i <= tileMaxY; ++i)
rows << i;
}
int tileHeight = tileSize().height();
int tileWidth = tileSize().width();
//TODO: need to have some form of type checking in here
QGeoTiledMapViewport *tiledViewport = static_cast<QGeoTiledMapViewport*>(viewport);
QList<QGeoTiledMapRequest> requests;
QList<QPair<int, int> > tiles;
QRectF protectedRegion = tiledViewport->protectedRegion();
// TODO order in direction of travel if panning
// TODO request excess tiles around border
for (int x = 0; x < cols.size(); ++x) {
for (int y = 0; y < rows.size(); ++y) {
tiles.append(qMakePair(cols.at(x), rows.at(y)));
}
}
for (int i = 0; i < tiles.size(); ++i) {
int col = tiles.at(i).first;
int row = tiles.at(i).second;
int colOffset = 0;
if ((tileMinX > tileMaxX) && col <= tileMaxX)
colOffset = numTiles;
QRectF tileRect = QRectF((col + colOffset) * tileWidth, row * tileHeight, tileWidth, tileHeight);
// Protected region is the area that was on the screen before the
// start of a resize or pan.
// We shouldn't request tiles that are entirely contained in this
// region.
if (protectedRegion.isNull() || !protectedRegion.contains(tileRect))
requests.append(QGeoTiledMapRequest(tiledViewport, row, col, tileRect));
}
emit tileRequestsPrepared(tiledViewport, requests);
tiledViewport->clearProtectedRegion();
}
void QGeoTiledMappingManagerEngine::tileFinished(QGeoTiledMapReply *reply)
{
if (!reply)
return;
if (reply->error() != QGeoTiledMapReply::NoError) {
QTimer::singleShot(0, reply, SLOT(deleteLater()));
return;
}
QGeoTiledMapViewport *viewport = reply->request().viewport();
if ((viewport->zoomLevel() != reply->request().zoomLevel())
|| (viewport->mapType() != reply->request().mapType())) {
QTimer::singleShot(0, reply, SLOT(deleteLater()));
return;
}
QRectF screenRect = viewport->screenRect();
QRectF tileRect = reply->request().tileRect();
QRectF overlap = tileRect.intersected(screenRect);
if (overlap.isEmpty()) {
QTimer::singleShot(0, reply, SLOT(deleteLater()));
return;
}
QRectF source = overlap.translated(-1.0 * tileRect.x(), -1.0 * tileRect.y());
QRectF dest = overlap.translated(-1.0 * screenRect.x(), -1.0 * screenRect.y());
QPixmap pm = viewport->mapImage();
QPainter *painter = new QPainter(&pm);
painter->drawPixmap(dest, reply->mapImage(), source);
viewport->setMapImage(pm);
delete painter;
QTimer::singleShot(0, reply, SLOT(deleteLater()));
}
void QGeoTiledMappingManagerEngine::tileError(QGeoTiledMapReply *reply, QGeoTiledMapReply::Error error, QString errorString)
{
qWarning() << errorString;
}
QPoint QGeoTiledMappingManagerEngine::screenPositionToTilePosition(const QGeoMapViewport *viewport, const QPointF &screenPosition) const
{
// TODO checking mechanism for viewport type?
const QGeoTiledMapViewport *tiledViewport = static_cast<const QGeoTiledMapViewport*>(viewport);
return tiledViewport->screenPositionToTileIndices(screenPosition);
}
/*!
Returns a list of the image formats supported by this QGeoTiledMappingManagerEngine
instance.
\sa QGeoTiledMappingManagerEngine::setSupportedImageFormats()
*/
QList<QString> QGeoTiledMappingManagerEngine::supportedImageFormats() const
{
Q_D(const QGeoTiledMappingManagerEngine);
return d->supportedImageFormats;
}
QSize QGeoTiledMappingManagerEngine::tileSize() const
{
Q_D(const QGeoTiledMappingManagerEngine);
return d->tileSize;
}
/*!
Sets the list of image formats supported by this QGeoTiledMappingManagerEngine
instance to \a imageFormats.
Subclasses of QGeoCodingService should use this function to ensure that
supportedImageFormats() provides accurate information.
\sa QGeoTiledMappingManagerEngine::supportedImageFormats()
*/
void QGeoTiledMappingManagerEngine::setSupportedImageFormats(const QList<QString> &imageFormats)
{
Q_D(QGeoTiledMappingManagerEngine);
d->supportedImageFormats = imageFormats;
}
void QGeoTiledMappingManagerEngine::setTileSize(const QSize &tileSize)
{
Q_D(QGeoTiledMappingManagerEngine);
d->tileSize = tileSize;
}
/*!
\fn void QGeoTiledMappingManagerEngine::replyFinished(QGeoMapReply *reply)
Indicates that a request handled by this QGeoTiledMappingManagerEngine object has
finished successfully. The result of the request will be in \a reply.
Note that \a reply will be the same object returned by this
QGeoTiledMappingManagerEngine instance when the request was issued, and that the
QGeoMapReply::finished() signal can be used instead of this signal if it
is more convinient to do so.
Do not delete the QGeoMapReply object in a slot connected to this signal
- use deleteLater() if it is necessary to do so.
\sa QGeoMapReply::finished()
*/
/*!
\fn void QGeoTiledMappingManagerEngine::replyError(QGeoMapReply *reply,
QGeoTiledMappingManagerEngine::ErrorCode errorCode,
QString errorString);
Indicates that a request handled by this QGeoTiledMappingManagerEngine object has
failed. The error is described by \a errorCode and \a errorString, and \a
reply is the QGeoMapReply object which was managing the result of the
corresponding service request.
Note that \a reply will be the same object returned by this
QGeoTiledMappingManagerEngine instance when the request was issued, and that the
QGeoMapReply::error() signal can be used instead of this signal if it is
more convinient to do so.
Do not delete the QGeoMapReply object in a slot connected to this signal
- use deleteLater() if it is necessary to do so.
\sa QGeoMapReply::error()
*/
/*******************************************************************************
*******************************************************************************/
QGeoTiledMappingManagerEnginePrivate::QGeoTiledMappingManagerEnginePrivate(const QMap<QString, QString> ¶meters)
: QGeoMappingManagerEnginePrivate(parameters), thread(NULL) {}
QGeoTiledMappingManagerEnginePrivate::QGeoTiledMappingManagerEnginePrivate(const QGeoTiledMappingManagerEnginePrivate &other)
: QGeoMappingManagerEnginePrivate(other),
supportedImageFormats(other.supportedImageFormats),
tileSize(other.tileSize),
thread(other.thread) {}
QGeoTiledMappingManagerEnginePrivate::~QGeoTiledMappingManagerEnginePrivate() {}
QGeoTiledMappingManagerEnginePrivate& QGeoTiledMappingManagerEnginePrivate::operator= (const QGeoTiledMappingManagerEnginePrivate & other)
{
QGeoMappingManagerEnginePrivate::operator =(other);
supportedImageFormats = other.supportedImageFormats;
tileSize = other.tileSize;
thread = other.thread;
return *this;
}
///*******************************************************************************
//*******************************************************************************/
#include "moc_qgeotiledmappingmanagerengine.cpp"
QTM_END_NAMESPACE
<|endoftext|> |
<commit_before>#include "tests.h"
#include <QVector>
#include <iostream>
#include "callout_test.h"
#include "clonecopy_test.h"
#include "readwrite_test.h"
#include "reverse_test.h"
#include "changerandomoperation_test.h"
#include "swaprandomvertexins_test.h"
#include "random_remove_vertex_test.h"
#include "random_add_vertex_test.h"
bool runtests(){
QVector<IReverseHashTest *> tests;
// tests.push_back(new CallOut_Test());
// tests.push_back(new ReadWrite_Test());
// tests.push_back(new ChangeRandomOperation_Test());
// tests.push_back(new SwapRandomVertexIns_Test());
// tests.push_back(new Reverse_Test());
tests.push_back(new CloneCopy_Test());
// tests.push_back(new RandomRemoveVertex_Test());
// tests.push_back(new RandomAddVertex_Test());
bool bResult = true;
for(int i = 0; i < tests.size(); i++){
std::cout << " Run " << tests[i]->name().toStdString() << " ... \n";
if(!tests[i]->run()){
bResult = false;
std::cout << " -> [FAIL] \n";
}else{
std::cout << " -> [OK] \n";
}
}
return bResult;
}
<commit_msg>Enabled all tests<commit_after>#include "tests.h"
#include <QVector>
#include <iostream>
#include "callout_test.h"
#include "clonecopy_test.h"
#include "readwrite_test.h"
#include "reverse_test.h"
#include "changerandomoperation_test.h"
#include "swaprandomvertexins_test.h"
#include "random_remove_vertex_test.h"
#include "random_add_vertex_test.h"
bool runtests(){
QVector<IReverseHashTest *> tests;
tests.push_back(new CallOut_Test());
tests.push_back(new ReadWrite_Test());
tests.push_back(new ChangeRandomOperation_Test());
tests.push_back(new SwapRandomVertexIns_Test());
tests.push_back(new Reverse_Test());
tests.push_back(new CloneCopy_Test());
tests.push_back(new RandomRemoveVertex_Test());
tests.push_back(new RandomAddVertex_Test());
bool bResult = true;
for(int i = 0; i < tests.size(); i++){
std::cout << " Run " << tests[i]->name().toStdString() << " ... \n";
if(!tests[i]->run()){
bResult = false;
std::cout << " -> [FAIL] \n";
}else{
std::cout << " -> [OK] \n";
}
}
return bResult;
}
<|endoftext|> |
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __URI_FETCHER_HPP__
#define __URI_FETCHER_HPP__
#include <process/owned.hpp>
#include <stout/none.hpp>
#include <stout/option.hpp>
#include <stout/try.hpp>
#include <mesos/uri/fetcher.hpp>
#include "uri/fetchers/copy.hpp"
#include "uri/fetchers/curl.hpp"
#include "uri/fetchers/docker.hpp"
#include "uri/fetchers/hadoop.hpp"
namespace mesos {
namespace uri {
namespace fetcher {
/**
* The combined flags for all built-in plugins.
*/
class Flags :
public virtual CopyFetcherPlugin::Flags,
#ifdef __WINDOWS__
// TODO(dpravat): Add support for Hadoop and Docker plugins. See MESOS-5473.
public virtual CurlFetcherPlugin::Flags {};
#else
public virtual CurlFetcherPlugin::Flags,
public virtual HadoopFetcherPlugin::Flags,
public virtual DockerFetcherPlugin::Flags {};
#endif // __WINDOWS__
/**
* Factory method for creating a Fetcher instance.
*/
Try<process::Owned<Fetcher>> create(const Option<Flags>& flags = None());
} // namespace fetcher {
} // namespace uri {
} // namespace mesos {
#endif // __URI_FETCHER_HPP__
<commit_msg>Fixed parameter name in uri/fetcher.hpp.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __URI_FETCHER_HPP__
#define __URI_FETCHER_HPP__
#include <process/owned.hpp>
#include <stout/none.hpp>
#include <stout/option.hpp>
#include <stout/try.hpp>
#include <mesos/uri/fetcher.hpp>
#include "uri/fetchers/copy.hpp"
#include "uri/fetchers/curl.hpp"
#include "uri/fetchers/docker.hpp"
#include "uri/fetchers/hadoop.hpp"
namespace mesos {
namespace uri {
namespace fetcher {
/**
* The combined flags for all built-in plugins.
*/
class Flags :
public virtual CopyFetcherPlugin::Flags,
#ifdef __WINDOWS__
// TODO(dpravat): Add support for Hadoop and Docker plugins. See MESOS-5473.
public virtual CurlFetcherPlugin::Flags {};
#else
public virtual CurlFetcherPlugin::Flags,
public virtual HadoopFetcherPlugin::Flags,
public virtual DockerFetcherPlugin::Flags {};
#endif // __WINDOWS__
/**
* Factory method for creating a Fetcher instance.
*/
Try<process::Owned<Fetcher>> create(const Option<Flags>& _flags = None());
} // namespace fetcher {
} // namespace uri {
} // namespace mesos {
#endif // __URI_FETCHER_HPP__
<|endoftext|> |
<commit_before>#ifndef PVLOG_HPP_
#define PVLOG_HPP_
#include <cstdarg>
#include <iostream>
#include <libgen.h>
#include <string>
#include <type_traits>
#ifdef NDEBUG
// Not DEBUG build
#ifdef PV_DEBUG_OUTPUT
// Release build, but logDebug output was requested
#define _PV_DEBUG_OUTPUT 1
#else
// Release build, no debug output
#undef _PV_DEBUG_OUTPUT
#endif // PV_DEBUG_OUTPUT
#else
// Debug build, logDebug output needed
#define _PV_DEBUG_OUTPUT 1
#endif // NDEBUG
#if defined(_PV_DEBUG_OUTPUT)
#define DEBUG_LOG_TEST_CONDITION true
#else
#define DEBUG_LOG_TEST_CONDITION false
#endif // defined(_PV_DEBUG_OUTPUT)
//
// Logging with the C++ builder pattern.
//
// After PV_Init::initialize has been called, use the following macros instead
// of writing to stdout, stderr, std::cout, std::cerr, etc.
// This way, the file will go to stdout or stderr if the -l option is not used,
// but will go to the log file if it is.
//
// InfoLog() << "Some info" << std::endl;
// WarnLog() << "Print a warning" << std::endl;
// Fatal() << "Print an error" << std::endl;
// ErrorLog() << "Print an error" << std::endl;
// DebugLog() << "Some" << "stuff" << "to log" << std::endl;
//
// FatalIf uses printf style formatting:
// FatalIf(condition == true, "Condition %s was true. Exiting.\n", conditionName);
//
// These macros create objets that send to the stream returned one of by
// PV::getOutputStream() or PV::getErrorStream().
// InfoLog() sends its output to the output stream.
// WarnLog() prepends its output with "WARN " and sends to the error stream.
// Fatal() prepends its output to the error stream with "ERROR <file,line>: ", then exits.
// ErrorLog() prepends its output to the error stream with "ERROR <file,line>: "
// DebugLog() prepends its output with "DEBUG <file,line>: " and sends to the output stream.
// In release versions, DebugLog() does not print any output,
// unless PetaVision was built using cmake -DPV_LOG_DEBUG:Bool=ON.
//
// The <file,line> returned by several of these macros gives the basename of the file where
// the macro was invoked, and the line number within that file.
// Because __LINE__ and __FILE__ evaluate to *this* file, not
// the file where the inline function is called. This is different
// from Clang, which puts in the __FILE__ and __LINE__ of the caller
#ifdef __GNUC__
#define InfoLog(...) PV::_Info __VA_ARGS__(__FILE__, __LINE__)
#define WarnLog(...) PV::_Warn __VA_ARGS__(__FILE__, __LINE__)
#define Fatal(...) PV::_Error __VA_ARGS__(__FILE__, __LINE__)
#define ErrorLog(...) PV::_ErrorNoExit __VA_ARGS__(__FILE__, __LINE__)
#define DebugLog(...) PV::_Debug __VA_ARGS__(__FILE__, __LINE__)
#define StackTrace(...) PV::_StackTrace __VA_ARGS__(__FILE__, __LINE__)
#define FatalIf(x, ...) \
if (x) { \
Fatal().printf(__VA_ARGS__); \
}
#endif // __GNUC__
namespace PV {
enum LogTypeEnum { _LogInfo, _LogWarn, _LogError, _LogErrorNoExit, _LogDebug, _LogStackTrace };
/**
* Returns the stream used by InfoLog and, DebugLog
* Typically, if a log file is set, the file is opened with write access and
* getOutputStream() returns the resulting fstream.
* If a log file is not set, this function returns std::cout.
*/
std::ostream &getOutputStream();
/**
* Returns the stream used by WarnLog, Fatal, and ErrorLog.
* Typically, if a log file is set, this returns the same ostream as getOutputStream(),
* and if a log file is not set, this returns std::cerr.
*/
std::ostream &getErrorStream();
/**
* A wide-character analog of getOutputStream().
*/
std::wostream &getWOutputStream();
/**
* A wide-character analog of getOutputStream().
*/
std::wostream &getWErrorStream();
/**
* LogType traits class. This is the protocol for defining traits
* for various log types, like LogInfoType, etc.
*/
template <int T>
struct LogType {
static std::string prefix();
// Should this log type generate output? This is used
// for suppressing debug output in release builds
static bool output();
// Should this log type flush the output stream before printing its
// message? If output and error streams are going to a terminal,
// error messages can get lost if output is buffered and error
// is unbuffered.
static bool flushOutputStream();
// Append prefix, file and line number? Used for suppressing
// this information for LogInfoType
static bool prependPrefix();
// Should this log type print the file and line information?
static bool outputFileLine();
// Should this log type exit once the message is printed?
static void exit();
};
typedef LogType<_LogInfo> LogInfoType;
typedef LogType<_LogWarn> LogWarnType;
typedef LogType<_LogError> LogErrorType;
typedef LogType<_LogErrorNoExit> LogErrorNoExitType;
typedef LogType<_LogDebug> LogDebugType;
typedef LogType<_LogStackTrace> LogStackTraceType;
// LogType traits
template <>
inline std::string LogInfoType::prefix() {
return std::string("INFO");
}
template <>
inline std::string LogWarnType::prefix() {
return std::string("WARN");
}
template <>
inline std::string LogErrorType::prefix() {
return std::string("ERROR");
}
template <>
inline std::string LogErrorNoExitType::prefix() {
return std::string("ERROR");
}
template <>
inline std::string LogDebugType::prefix() {
return std::string("DEBUG");
}
template <>
inline std::string LogStackTraceType::prefix() {
return std::string("");
}
template <>
inline bool LogInfoType::output() {
return true;
}
template <>
inline bool LogWarnType::output() {
return true;
}
template <>
inline bool LogErrorType::output() {
return true;
}
template <>
inline bool LogErrorNoExitType::output() {
return true;
}
template <>
inline bool LogStackTraceType::output() {
return true;
}
template <>
inline bool LogDebugType::output() {
return DEBUG_LOG_TEST_CONDITION;
}
template <>
inline bool LogInfoType::flushOutputStream() {
return false;
}
template <>
inline bool LogWarnType::flushOutputStream() {
return false;
}
template <>
inline bool LogErrorType::flushOutputStream() {
return true;
}
template <>
inline bool LogErrorNoExitType::flushOutputStream() {
return true;
}
template <>
inline bool LogStackTraceType::flushOutputStream() {
return true;
}
template <>
inline bool LogDebugType::flushOutputStream() {
return true;
}
template <>
inline bool LogInfoType::prependPrefix() {
return false;
}
template <>
inline bool LogWarnType::prependPrefix() {
return true;
}
template <>
inline bool LogErrorType::prependPrefix() {
return true;
}
template <>
inline bool LogErrorNoExitType::prependPrefix() {
return true;
}
template <>
inline bool LogStackTraceType::prependPrefix() {
return false;
}
template <>
inline bool LogDebugType::prependPrefix() {
return true;
}
template <>
inline bool LogInfoType::outputFileLine() {
return false;
}
template <>
inline bool LogWarnType::outputFileLine() {
return false;
}
template <>
inline bool LogErrorType::outputFileLine() {
return true;
}
template <>
inline bool LogErrorNoExitType::outputFileLine() {
return true;
}
template <>
inline bool LogStackTraceType::outputFileLine() {
return false;
}
template <>
inline bool LogDebugType::outputFileLine() {
return true;
}
template <>
inline void LogInfoType::exit() {}
template <>
inline void LogWarnType::exit() {}
template <>
inline void LogErrorType::exit() {
::exit(EXIT_FAILURE);
}
template <>
inline void LogErrorNoExitType::exit() {}
template <>
inline void LogStackTraceType::exit() {}
template <>
inline void LogDebugType::exit() {}
// Log traits, for definining the stream to be used by the logger
template <typename C, typename LT, typename T = std::char_traits<C>>
struct LogStreamTraits {
typedef T char_traits;
typedef LT LogType;
typedef std::basic_ostream<C, T> &(*StrFunc)(std::basic_ostream<C, T> &);
static std::basic_ostream<C, T> &stream();
};
template <>
inline std::ostream &LogStreamTraits<char, LogInfoType>::stream() {
return getOutputStream();
}
template <>
inline std::wostream &LogStreamTraits<wchar_t, LogInfoType>::stream() {
return getWOutputStream();
}
template <>
inline std::ostream &LogStreamTraits<char, LogWarnType>::stream() {
return getErrorStream();
}
template <>
inline std::wostream &LogStreamTraits<wchar_t, LogWarnType>::stream() {
return getWErrorStream();
}
template <>
inline std::ostream &LogStreamTraits<char, LogErrorType>::stream() {
return getErrorStream();
}
template <>
inline std::wostream &LogStreamTraits<wchar_t, LogErrorNoExitType>::stream() {
return getWErrorStream();
}
template <>
inline std::ostream &LogStreamTraits<char, LogErrorNoExitType>::stream() {
return getErrorStream();
}
template <>
inline std::wostream &LogStreamTraits<wchar_t, LogErrorType>::stream() {
return getWErrorStream();
}
template <>
inline std::ostream &LogStreamTraits<char, LogDebugType>::stream() {
return getOutputStream();
}
template <>
inline std::wostream &LogStreamTraits<wchar_t, LogDebugType>::stream() {
return getWOutputStream();
}
template <>
inline std::ostream &LogStreamTraits<char, LogStackTraceType>::stream() {
return getErrorStream();
}
template <>
inline std::wostream &LogStreamTraits<wchar_t, LogStackTraceType>::stream() {
return getWErrorStream();
}
template <typename C, typename LT, typename T = std::char_traits<C>>
struct Log {
typedef std::basic_ostream<C, T> basic_ostream;
typedef LogStreamTraits<C, LT, T> LogStreamType;
typedef LT LogType;
Log(const char *file = __FILE__, int line = __LINE__) : _stream(LogStreamType::stream()) {
outputPrefix(file, line);
}
Log(basic_ostream &s, const char *file = __FILE__, int line = __LINE__)
: _stream(LogStreamType::stream()) {
outputPrefix(file, line);
}
~Log() { LogType::exit(); }
void outputPrefix(const char *file, int line) {
// In release this is optimised away if log type is debug
if (LogType::output()) {
if (LogType::flushOutputStream()) {
getOutputStream().flush();
}
if (LogType::prependPrefix()) {
_stream << LogType::prefix() << " ";
}
if (LogType::outputFileLine()) {
_stream << "<" << basename((char *)file) << ":" << line << ">: ";
}
}
}
template <typename V>
Log &operator<<(V const &value) {
if (LogType::output()) {
_stream << value;
}
return *this;
}
Log &operator<<(typename LogStreamType::StrFunc func) {
if (LogType::output()) {
func(_stream);
}
return *this;
}
Log &flush() {
if (LogType::output()) {
_stream.flush();
}
return *this;
}
/**
* A method intended to make it easy to convert printf(format,...) and fprintf(stderr,format,...)
* statements
* to versions that use the PVLog facilities.
* To have output recorded in the logfile, replace printf(format,...) with
* InfoLog().printf(format,...)
* and fprintf(stderr,format,...) with pvXXXX().printf(format,...), with pvXXXX replaced by
* WarnLog, Fatal, or ErrorLog depending on the desired behavior.
*/
int printf(char const *fmt, ...) {
int chars_printed;
if (LogType::output()) {
va_list args1, args2;
va_start(args1, fmt);
va_copy(args2, args1);
char c;
int chars_needed = vsnprintf(&c, 1, fmt, args1);
chars_needed++;
char output_string[chars_needed];
chars_printed = vsnprintf(output_string, chars_needed, fmt, args2);
_stream << output_string;
va_end(args1);
va_end(args2);
return chars_needed;
}
else {
chars_printed = 0;
}
return chars_printed;
}
private:
std::basic_ostream<C, T> &_stream;
};
#ifdef __GNUC__
// Macros that call these functions defined outside of namespace
typedef Log<char, LogDebugType> _Debug;
typedef Log<char, LogInfoType> _Info;
typedef Log<char, LogWarnType> _Warn;
typedef Log<char, LogErrorType> _Error;
typedef Log<char, LogErrorNoExitType> _ErrorNoExit;
typedef Log<char, LogStackTraceType> _StackTrace;
typedef Log<wchar_t, LogDebugType> _WDebug;
typedef Log<wchar_t, LogInfoType> _WInfo;
typedef Log<wchar_t, LogWarnType> _WWarn;
typedef Log<wchar_t, LogErrorType> _WError;
typedef Log<char, LogErrorNoExitType> _WErrorNoExit;
typedef Log<wchar_t, LogStackTraceType> _WStackTrace;
#else
// Clang __FILE__ and __LINE__ evalaute to the caller of the function
// thus the macros aren't needed
typedef Log<char, LogDebugType> Debug;
typedef Log<char, LogInfoType> Info;
typedef Log<char, LogWarnType> Warn;
typedef Log<char, LogErrorType> Error;
typedef Log<char, LogErrorNoExitType> ErrorNoExit;
typedef Log<char, LogStackTraceType> StackTrace;
typedef Log<wchar_t, LogDebugType> WDebug;
typedef Log<wchar_t, LogInfoType> WInfo;
typedef Log<wchar_t, LogWarnType> WWarn;
typedef Log<wchar_t, LogErrorType> WError;
typedef Log<wchar_t, LogErrorNoExitType> WErrorNoExit;
typedef Log<wchar_t, LogStackTraceType> WStackTrace;
#endif // __GNUC__
// setLogFile sets the file that the DebugLog, InfoLog, WarnLog, and Fatal streams write to.
void setLogFile(char const *logFile, std::ios_base::openmode mode = std::ios_base::out);
void setWLogFile(char const *logFile, std::ios_base::openmode mode = std::ios_base::out);
} // end namespace PV
#endif // PVLOG_HPP_
<commit_msg>Fixed some renaming that I missed in PVLog.hpp<commit_after>#ifndef PVLOG_HPP_
#define PVLOG_HPP_
#include <cstdarg>
#include <iostream>
#include <libgen.h>
#include <string>
#include <type_traits>
#ifdef NDEBUG
// Not DEBUG build
#ifdef PV_DEBUG_OUTPUT
// Release build, but logDebug output was requested
#define _PV_DEBUG_OUTPUT 1
#else
// Release build, no debug output
#undef _PV_DEBUG_OUTPUT
#endif // PV_DEBUG_OUTPUT
#else
// Debug build, logDebug output needed
#define _PV_DEBUG_OUTPUT 1
#endif // NDEBUG
#if defined(_PV_DEBUG_OUTPUT)
#define DEBUG_LOG_TEST_CONDITION true
#else
#define DEBUG_LOG_TEST_CONDITION false
#endif // defined(_PV_DEBUG_OUTPUT)
//
// Logging with the C++ builder pattern.
//
// After PV_Init::initialize has been called, use the following macros instead
// of writing to stdout, stderr, std::cout, std::cerr, etc.
// This way, the file will go to stdout or stderr if the -l option is not used,
// but will go to the log file if it is.
//
// InfoLog() << "Some info" << std::endl;
// WarnLog() << "Print a warning" << std::endl;
// Fatal() << "Print an error" << std::endl;
// ErrorLog() << "Print an error" << std::endl;
// DebugLog() << "Some" << "stuff" << "to log" << std::endl;
//
// FatalIf uses printf style formatting:
// FatalIf(condition == true, "Condition %s was true. Exiting.\n", conditionName);
//
// These macros create objets that send to the stream returned one of by
// PV::getOutputStream() or PV::getErrorStream().
// InfoLog() sends its output to the output stream.
// WarnLog() prepends its output with "WARN " and sends to the error stream.
// Fatal() prepends its output to the error stream with "ERROR <file,line>: ", then exits.
// ErrorLog() prepends its output to the error stream with "ERROR <file,line>: "
// DebugLog() prepends its output with "DEBUG <file,line>: " and sends to the output stream.
// In release versions, DebugLog() does not print any output,
// unless PetaVision was built using cmake -DPV_LOG_DEBUG:Bool=ON.
//
// The <file,line> returned by several of these macros gives the basename of the file where
// the macro was invoked, and the line number within that file.
// Because __LINE__ and __FILE__ evaluate to *this* file, not
// the file where the inline function is called. This is different
// from Clang, which puts in the __FILE__ and __LINE__ of the caller
#ifdef __GNUC__
#define InfoLog(...) PV::InfoLog __VA_ARGS__(__FILE__, __LINE__)
#define WarnLog(...) PV::WarnLog __VA_ARGS__(__FILE__, __LINE__)
#define Fatal(...) PV::Fatal __VA_ARGS__(__FILE__, __LINE__)
#define ErrorLog(...) PV::ErrorLog __VA_ARGS__(__FILE__, __LINE__)
#define DebugLog(...) PV::DebugLog __VA_ARGS__(__FILE__, __LINE__)
#define StackTrace(...) PV::StackTrace __VA_ARGS__(__FILE__, __LINE__)
#define FatalIf(x, ...) \
if (x) { \
Fatal().printf(__VA_ARGS__); \
}
#endif // __GNUC__
namespace PV {
enum LogTypeEnum { _LogInfo, _LogWarn, _LogError, _LogErrorNoExit, _LogDebug, _LogStackTrace };
/**
* Returns the stream used by InfoLog and, DebugLog
* Typically, if a log file is set, the file is opened with write access and
* getOutputStream() returns the resulting fstream.
* If a log file is not set, this function returns std::cout.
*/
std::ostream &getOutputStream();
/**
* Returns the stream used by WarnLog, Fatal, and ErrorLog.
* Typically, if a log file is set, this returns the same ostream as getOutputStream(),
* and if a log file is not set, this returns std::cerr.
*/
std::ostream &getErrorStream();
/**
* A wide-character analog of getOutputStream().
*/
std::wostream &getWOutputStream();
/**
* A wide-character analog of getOutputStream().
*/
std::wostream &getWErrorStream();
/**
* LogType traits class. This is the protocol for defining traits
* for various log types, like InfoLogType, etc.
*/
template <int T>
struct LogType {
static std::string prefix();
// Should this log type generate output? This is used
// for suppressing debug output in release builds
static bool output();
// Should this log type flush the output stream before printing its
// message? If output and error streams are going to a terminal,
// error messages can get lost if output is buffered and error
// is unbuffered.
static bool flushOutputStream();
// Append prefix, file and line number? Used for suppressing
// this information for InfoLogType
static bool prependPrefix();
// Should this log type print the file and line information?
static bool outputFileLine();
// Should this log type exit once the message is printed?
static void exit();
};
typedef LogType<_LogInfo> InfoLogType;
typedef LogType<_LogWarn> WarnLogType;
typedef LogType<_LogError> FatalType;
typedef LogType<_LogErrorNoExit> ErrorLogType;
typedef LogType<_LogDebug> DebugLogType;
typedef LogType<_LogStackTrace> StackTraceType;
// LogType traits
template <>
inline std::string InfoLogType::prefix() {
return std::string("INFO");
}
template <>
inline std::string WarnLogType::prefix() {
return std::string("WARN");
}
template <>
inline std::string FatalType::prefix() {
return std::string("ERROR");
}
template <>
inline std::string ErrorLogType::prefix() {
return std::string("ERROR");
}
template <>
inline std::string DebugLogType::prefix() {
return std::string("DEBUG");
}
template <>
inline std::string StackTraceType::prefix() {
return std::string("");
}
template <>
inline bool InfoLogType::output() {
return true;
}
template <>
inline bool WarnLogType::output() {
return true;
}
template <>
inline bool FatalType::output() {
return true;
}
template <>
inline bool ErrorLogType::output() {
return true;
}
template <>
inline bool StackTraceType::output() {
return true;
}
template <>
inline bool DebugLogType::output() {
return DEBUG_LOG_TEST_CONDITION;
}
template <>
inline bool InfoLogType::flushOutputStream() {
return false;
}
template <>
inline bool WarnLogType::flushOutputStream() {
return false;
}
template <>
inline bool FatalType::flushOutputStream() {
return true;
}
template <>
inline bool ErrorLogType::flushOutputStream() {
return true;
}
template <>
inline bool StackTraceType::flushOutputStream() {
return true;
}
template <>
inline bool DebugLogType::flushOutputStream() {
return true;
}
template <>
inline bool InfoLogType::prependPrefix() {
return false;
}
template <>
inline bool WarnLogType::prependPrefix() {
return true;
}
template <>
inline bool FatalType::prependPrefix() {
return true;
}
template <>
inline bool ErrorLogType::prependPrefix() {
return true;
}
template <>
inline bool StackTraceType::prependPrefix() {
return false;
}
template <>
inline bool DebugLogType::prependPrefix() {
return true;
}
template <>
inline bool InfoLogType::outputFileLine() {
return false;
}
template <>
inline bool WarnLogType::outputFileLine() {
return false;
}
template <>
inline bool FatalType::outputFileLine() {
return true;
}
template <>
inline bool ErrorLogType::outputFileLine() {
return true;
}
template <>
inline bool StackTraceType::outputFileLine() {
return false;
}
template <>
inline bool DebugLogType::outputFileLine() {
return true;
}
template <>
inline void InfoLogType::exit() {}
template <>
inline void WarnLogType::exit() {}
template <>
inline void FatalType::exit() {
::exit(EXIT_FAILURE);
}
template <>
inline void ErrorLogType::exit() {}
template <>
inline void StackTraceType::exit() {}
template <>
inline void DebugLogType::exit() {}
// Log traits, for definining the stream to be used by the logger
template <typename C, typename LT, typename T = std::char_traits<C>>
struct LogStreamTraits {
typedef T char_traits;
typedef LT LogType;
typedef std::basic_ostream<C, T> &(*StrFunc)(std::basic_ostream<C, T> &);
static std::basic_ostream<C, T> &stream();
};
template <>
inline std::ostream &LogStreamTraits<char, InfoLogType>::stream() {
return getOutputStream();
}
template <>
inline std::wostream &LogStreamTraits<wchar_t, InfoLogType>::stream() {
return getWOutputStream();
}
template <>
inline std::ostream &LogStreamTraits<char, WarnLogType>::stream() {
return getErrorStream();
}
template <>
inline std::wostream &LogStreamTraits<wchar_t, WarnLogType>::stream() {
return getWErrorStream();
}
template <>
inline std::ostream &LogStreamTraits<char, FatalType>::stream() {
return getErrorStream();
}
template <>
inline std::wostream &LogStreamTraits<wchar_t, ErrorLogType>::stream() {
return getWErrorStream();
}
template <>
inline std::ostream &LogStreamTraits<char, ErrorLogType>::stream() {
return getErrorStream();
}
template <>
inline std::wostream &LogStreamTraits<wchar_t, FatalType>::stream() {
return getWErrorStream();
}
template <>
inline std::ostream &LogStreamTraits<char, DebugLogType>::stream() {
return getOutputStream();
}
template <>
inline std::wostream &LogStreamTraits<wchar_t, DebugLogType>::stream() {
return getWOutputStream();
}
template <>
inline std::ostream &LogStreamTraits<char, StackTraceType>::stream() {
return getErrorStream();
}
template <>
inline std::wostream &LogStreamTraits<wchar_t, StackTraceType>::stream() {
return getWErrorStream();
}
template <typename C, typename LT, typename T = std::char_traits<C>>
struct Log {
typedef std::basic_ostream<C, T> basic_ostream;
typedef LogStreamTraits<C, LT, T> LogStreamType;
typedef LT LogType;
Log(const char *file = __FILE__, int line = __LINE__) : _stream(LogStreamType::stream()) {
outputPrefix(file, line);
}
Log(basic_ostream &s, const char *file = __FILE__, int line = __LINE__)
: _stream(LogStreamType::stream()) {
outputPrefix(file, line);
}
~Log() { LogType::exit(); }
void outputPrefix(const char *file, int line) {
// In release this is optimised away if log type is debug
if (LogType::output()) {
if (LogType::flushOutputStream()) {
getOutputStream().flush();
}
if (LogType::prependPrefix()) {
_stream << LogType::prefix() << " ";
}
if (LogType::outputFileLine()) {
_stream << "<" << basename((char *)file) << ":" << line << ">: ";
}
}
}
template <typename V>
Log &operator<<(V const &value) {
if (LogType::output()) {
_stream << value;
}
return *this;
}
Log &operator<<(typename LogStreamType::StrFunc func) {
if (LogType::output()) {
func(_stream);
}
return *this;
}
Log &flush() {
if (LogType::output()) {
_stream.flush();
}
return *this;
}
/**
* A method intended to make it easy to convert printf(format,...) and fprintf(stderr,format,...)
* statements
* to versions that use the PVLog facilities.
* To have output recorded in the logfile, replace printf(format,...) with
* InfoLog().printf(format,...)
* and fprintf(stderr,format,...) with pvXXXX().printf(format,...), with pvXXXX replaced by
* WarnLog, Fatal, or ErrorLog depending on the desired behavior.
*/
int printf(char const *fmt, ...) {
int chars_printed;
if (LogType::output()) {
va_list args1, args2;
va_start(args1, fmt);
va_copy(args2, args1);
char c;
int chars_needed = vsnprintf(&c, 1, fmt, args1);
chars_needed++;
char output_string[chars_needed];
chars_printed = vsnprintf(output_string, chars_needed, fmt, args2);
_stream << output_string;
va_end(args1);
va_end(args2);
return chars_needed;
}
else {
chars_printed = 0;
}
return chars_printed;
}
private:
std::basic_ostream<C, T> &_stream;
};
#ifdef __GNUC__
// Macros that call these functions defined outside of namespace
typedef Log<char, DebugLogType> DebugLog;
typedef Log<char, InfoLogType> InfoLog;
typedef Log<char, WarnLogType> WarnLog;
typedef Log<char, FatalType> Fatal;
typedef Log<char, ErrorLogType> ErrorLog;
typedef Log<char, StackTraceType> StackTrace;
typedef Log<wchar_t, DebugLogType> WDebug;
typedef Log<wchar_t, InfoLogType> WInfo;
typedef Log<wchar_t, WarnLogType> WWarn;
typedef Log<wchar_t, FatalType> WFatal;
typedef Log<char, ErrorLogType> WError;
typedef Log<wchar_t, StackTraceType> WStackTrace;
#else
// Clang __FILE__ and __LINE__ evalaute to the caller of the function
// thus the macros aren't needed
typedef Log<char, DebugLogType> Debug;
typedef Log<char, InfoLogType> Info;
typedef Log<char, WarnLogType> Warn;
typedef Log<char, FatalType> Error;
typedef Log<char, ErrorLogType> ErrorNoExit;
typedef Log<char, StackTraceType> StackTrace;
typedef Log<wchar_t, DebugLogType> WDebug;
typedef Log<wchar_t, InfoLogType> WInfo;
typedef Log<wchar_t, WarnLogType> WWarn;
typedef Log<wchar_t, FatalType> WFatal;
typedef Log<wchar_t, ErrorLogType> WError;
typedef Log<wchar_t, StackTraceType> WStackTrace;
#endif // __GNUC__
// setLogFile sets the file that the DebugLog, InfoLog, WarnLog, and Fatal streams write to.
void setLogFile(char const *logFile, std::ios_base::openmode mode = std::ios_base::out);
void setWLogFile(char const *logFile, std::ios_base::openmode mode = std::ios_base::out);
} // end namespace PV
#endif // PVLOG_HPP_
<|endoftext|> |
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage 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 "hokuyo.h"
#include <stdio.h>
#include <ros/console.h>
using namespace std;
int
main(int argc, char** argv)
{
if (argc < 2 || argc > 3)
{
fprintf(stderr, "usage: getID /dev/ttyACM? [quiet]\nOutputs the device ID of a hokuyo at /dev/ttyACM?. Add a second argument for script friendly output.\n");
return 1;
}
hokuyo::Laser laser;
for (int retries = 10; retries; retries--)
{
try
{
laser.open(argv[1]);
std::string device_id = laser.getID();
if (argc == 2)
printf("Device at %s has ID ", argv[1]);
printf("%s\n", device_id.c_str());
laser.close();
return 0;
}
catch (hokuyo::Exception &e)
{
ROS_WARN("getID failed: %s", e.what());
laser.close();
}
sleep(1);
}
ROS_ERROR("getID failed for 10 seconds. Giving up.");
return 1;
}
<commit_msg>Got rid of all output to stderr when getID is in quiet mode.<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage 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 "hokuyo.h"
#include <stdio.h>
#include <ros/console.h>
using namespace std;
int
main(int argc, char** argv)
{
if (argc < 2 || argc > 3)
{
fprintf(stderr, "usage: getID /dev/ttyACM? [quiet]\nOutputs the device ID of a hokuyo at /dev/ttyACM?. Add a second argument for script friendly output.\n");
return 1;
}
bool verbose = (argc == 2);
if (!verbose)
{
// In quiet mode we want to turn off logging levels that go to stdout.
log4cxx::LoggerPtr my_logger = log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME);
my_logger->setLevel(ros::console::g_level_lookup[ros::console::levels::Error]);
}
hokuyo::Laser laser;
for (int retries = 10; retries; retries--)
{
try
{
laser.open(argv[1]);
std::string device_id = laser.getID();
if (verbose)
printf("Device at %s has ID ", argv[1]);
printf("%s\n", device_id.c_str());
laser.close();
return 0;
}
catch (hokuyo::Exception &e)
{
if (verbose)
ROS_WARN("getID failed: %s", e.what());
laser.close();
}
sleep(1);
}
if (verbose)
ROS_ERROR("getID failed for 10 seconds. Giving up.");
return 1;
}
<|endoftext|> |
<commit_before>#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/select.h>
#include <linux/limits.h>
#include <linux/types.h> /* for videodev2.h */
#include <linux/videodev2.h>
#include <iostream>
#include <string>
#include <cstring>
#include <vector>
#include <utility>
#include <memory>
#include <cerrno>
#include "cxxopts/cxxopts.hpp"
#include "easylogging++/easylogging++.h"
using OptionsPtr = std::shared_ptr<cxxopts::Options>;
INITIALIZE_EASYLOGGINGPP
class V4L2Device {
public:
V4L2Device() = delete;
V4L2Device(OptionsPtr opts):
options(opts)
{
}
~V4L2Device()
{
if (fd != -1) {
close(fd);
}
}
bool initialize()
{
auto initialized = open_device() and check_capabilities() and set_format() and init_buffers();
return initialized;
}
void capture()
{
struct v4l2_buffer bufferinfo;
std::memset(&bufferinfo, 0, sizeof(bufferinfo));
bufferinfo.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
bufferinfo.memory = V4L2_MEMORY_MMAP;
bufferinfo.index = 0; /* Queueing buffer index 0. */
// Put the buffer in the incoming queue.
if (ioctl(fd, VIDIOC_QBUF, &bufferinfo) < 0) {
LOG(ERROR) << "VIDIOC_QBUF failed: " << strerror(errno);
return;
}
// Activate streaming
int type = bufferinfo.type;
if (ioctl(fd, VIDIOC_STREAMON, &type) < 0){
LOG(ERROR) << "VIDIOC_STREAMON failed: " << strerror(errno);
return;
}
int frames_taken = 0;
int frames_skipped = 0;
auto loop = (*options)["loop"].as<bool>();
int frames_count = options->count("count") ? (*options)["count"].as<int>() : 1;
int frames_to_skip = options->count("skip") ? (*options)["skip"].as<int>() : 0;
useconds_t pause = std::lround((options->count("pause") ? (*options)["pause"].as<double>() : 0) * 1e6);
char fname[PATH_MAX];
auto dir = (*options)["dir"].as<std::string>();
while ((frames_taken < frames_count) or loop) {
// Dequeue the buffer.
if (ioctl(fd, VIDIOC_DQBUF, &bufferinfo) < 0) {
LOG(ERROR) << "VIDIOC_QBUF failed: " << strerror(errno);
break;
}
bool skip_frame = frames_to_skip > 0 and frames_skipped < frames_to_skip;
if (not skip_frame) {
snprintf(fname, sizeof(fname) - 1, "%s/image_%i.jpeg", dir.c_str(), frames_taken);
int jpgfile;
if ((jpgfile = open(fname, O_WRONLY | O_CREAT, 0660)) < 0) {
LOG(ERROR) << "open file failed: " << strerror(errno);
break;
}
auto rc = write(jpgfile, buffer.start, bufferinfo.length);
if (rc < 0) {
LOG(ERROR) << "write file failed: " << strerror(errno);
break;
}
close(jpgfile);
frames_taken++;
} else {
frames_skipped++;
}
bufferinfo.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
bufferinfo.memory = V4L2_MEMORY_MMAP;
/* Set the index if using several buffers */
// Queue the next one.
if (ioctl(fd, VIDIOC_QBUF, &bufferinfo) < 0) {
LOG(ERROR) << "VIDIOC_QBUF failed: " << strerror(errno);
break;
}
if (pause > 0) {
usleep(pause);
}
}
// Deactivate streaming
if (ioctl(fd, VIDIOC_STREAMOFF, &type) < 0) {
LOG(ERROR) << "VIDIOC_STREAMOFF failed: " << strerror(errno);
}
}
private:
class IOBuffer
{
public:
IOBuffer(const IOBuffer&) = delete;
IOBuffer() = default;
~IOBuffer()
{
if (start != nullptr and size > 0) {
auto rc = munmap(start, size);
if (rc < 0) {
LOG(ERROR) << "munmap() failed: " << strerror(errno);
}
}
}
void *start = nullptr;
size_t size = 0;
};
int fd = -1;
IOBuffer buffer;
OptionsPtr options;
bool open_device()
{
if (fd == -1) {
auto device = (*options)["device"].as<std::string>().c_str();
fd = open(device, O_RDWR);
if (fd < 0) {
LOG(ERROR) << "Couldn't open '" << device << "' :" << strerror(errno) << std::endl;
return false;
}
} else {
LOG(WARNING) << "Is device already initialized?";
return false;
}
return true;
}
bool check_capabilities()
{
struct v4l2_capability cap;
std::memset(&cap, 0, sizeof(cap));
if (ioctl(fd, VIDIOC_QUERYCAP, &cap) < 0) {
LOG(ERROR) << "VIDIOC_QUERYCAP failed: " << strerror(errno);
return false;
}
if ((cap.capabilities & V4L2_CAP_VIDEO_CAPTURE) == 0) {
LOG(ERROR) << "the device does not handle single-planar video capture";
return false;
}
if ((cap.capabilities & V4L2_CAP_STREAMING) == 0) {
LOG(ERROR) << "the device does not handle frame streaming";
return false;
}
return true;
}
bool set_format()
{
struct v4l2_format format;
std::memset(&format, 0, sizeof(format));
format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
format.fmt.pix.pixelformat = V4L2_PIX_FMT_MJPEG;
// FIXME: set format specified in cmd. line
format.fmt.pix.width = 800;
format.fmt.pix.height = 600;
if (ioctl(fd, VIDIOC_S_FMT, &format) < 0) {
LOG(ERROR) << "VIDIOC_S_FMT failed: " << strerror(errno);
return false;
}
return true;
}
bool init_buffers()
{
struct v4l2_requestbuffers bufrequest;
std::memset(&bufrequest, 0, sizeof(bufrequest));
bufrequest.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
bufrequest.memory = V4L2_MEMORY_MMAP;
bufrequest.count = 1;
if (ioctl(fd, VIDIOC_REQBUFS, &bufrequest) < 0) {
LOG(ERROR) << "VIDIOC_REQBUFS failed: " << strerror(errno);
return false;
}
struct v4l2_buffer bufferinfo;
std::memset(&bufferinfo, 0, sizeof(bufferinfo));
bufferinfo.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
bufferinfo.memory = V4L2_MEMORY_MMAP;
bufferinfo.index = 0;
if (ioctl(fd, VIDIOC_QUERYBUF, &bufferinfo) < 0) {
LOG(ERROR) << "VIDIOC_QUERYBUF failed: " << strerror(errno);
return false;
}
buffer.start = mmap(
NULL,
bufferinfo.length,
PROT_READ | PROT_WRITE,
MAP_SHARED,
fd,
bufferinfo.m.offset
);
if (buffer.start == MAP_FAILED) {
LOG(ERROR) << "mmaping buffer failed: " << strerror(errno);
return false;
}
buffer.size = bufferinfo.length;
memset(buffer.start, 0, bufferinfo.length);
return true;
}
};
int
main(int argc, char** argv)
{
auto options = std::make_shared<cxxopts::Options>("uvccapture2", "Capture images from an USB camera on Linux");
// clang-format off
options->add_options()
("h,help", "show this help")
("debug", "enable debugging")
("dir", "name of an images directory", cxxopts::value<std::string>())
("device", "camera's device ti use", cxxopts::value<std::string>()->default_value("/dev/video0"))
("count", "number of images to capture", cxxopts::value<int>())
("pause", "pause between subsequent captures in seconds", cxxopts::value<double>())
("loop", "run in loop mode, overrides --count", cxxopts::value<bool>())
("skip", "skip specified number of frames before first capture", cxxopts::value<int>())
("resolution", "image's resolution", cxxopts::value<std::string>()->default_value("640x480"))
;
// clang-format on
options->parse(argc, argv);
if (options->count("help")) {
std::cout << options->help() << std::endl;
return 0;
}
if (options->count("dir") == 0) {
std::cout << "Mandatory parameter '--dir' was not specified." << std::endl;
return 0;
}
el::Configurations defaultConf;
defaultConf.setToDefault();
// Values are always std::string
defaultConf.set(el::Level::Info, el::ConfigurationType::Format, "%datetime %level %loc %msg");
defaultConf.set(el::Level::Error, el::ConfigurationType::Format, "%datetime %level %loc %msg");
// default logger uses default configurations
el::Loggers::reconfigureLogger("default", defaultConf);
std::cout << "images' directory: " << (*options)["dir"].as<std::string>() << std::endl;
std::cout << "device: " << (*options)["device"].as<std::string>() << std::endl;
std::cout << "loop: " << (*options)["loop"].as<bool>() << std::endl;
V4L2Device dev(options);
if (dev.initialize()) {
dev.capture();
}
return 0;
}
<commit_msg>renamings<commit_after>#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/select.h>
#include <linux/limits.h>
#include <linux/types.h> /* for videodev2.h */
#include <linux/videodev2.h>
#include <iostream>
#include <string>
#include <cstring>
#include <vector>
#include <utility>
#include <memory>
#include <cerrno>
#include "cxxopts/cxxopts.hpp"
#include "easylogging++/easylogging++.h"
using OptionsPtr = std::shared_ptr<cxxopts::Options>;
INITIALIZE_EASYLOGGINGPP
class V4L2Device {
public:
V4L2Device() = delete;
V4L2Device(OptionsPtr opts):
options(opts)
{
}
~V4L2Device()
{
if (fd != -1) {
close(fd);
}
}
bool initialize()
{
auto initialized = open_device() and check_capabilities() and set_format() and init_buffers();
return initialized;
}
void capture()
{
struct v4l2_buffer bufferinfo;
std::memset(&bufferinfo, 0, sizeof(bufferinfo));
bufferinfo.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
bufferinfo.memory = V4L2_MEMORY_MMAP;
bufferinfo.index = 0; /* Queueing buffer index 0. */
// Put the buffer in the incoming queue.
if (ioctl(fd, VIDIOC_QBUF, &bufferinfo) < 0) {
LOG(ERROR) << "VIDIOC_QBUF failed: " << strerror(errno);
return;
}
// Activate streaming
int type = bufferinfo.type;
if (ioctl(fd, VIDIOC_STREAMON, &type) < 0){
LOG(ERROR) << "VIDIOC_STREAMON failed: " << strerror(errno);
return;
}
int frames_taken = 0;
int frames_skipped = 0;
auto loop = (*options)["loop"].as<bool>();
int frames_count = options->count("count") ? (*options)["count"].as<int>() : 1;
int frames_to_skip = options->count("skip") ? (*options)["skip"].as<int>() : 0;
useconds_t pause = std::lround((options->count("pause") ? (*options)["pause"].as<double>() : 0) * 1e6);
char jpeg_file_name[PATH_MAX];
auto dir = (*options)["dir"].as<std::string>();
while ((frames_taken < frames_count) or loop) {
// Dequeue the buffer.
if (ioctl(fd, VIDIOC_DQBUF, &bufferinfo) < 0) {
LOG(ERROR) << "VIDIOC_QBUF failed: " << strerror(errno);
break;
}
bool skip_frame = frames_to_skip > 0 and frames_skipped < frames_to_skip;
if (not skip_frame) {
snprintf(jpeg_file_name, sizeof(jpeg_file_name) - 1, "%s/image_%i.jpeg", dir.c_str(), frames_taken);
auto jpeg_file_fd = open(jpeg_file_name, O_WRONLY | O_CREAT, 0660);
if (jpeg_file_fd < 0) {
LOG(ERROR) << "open file failed: " << strerror(errno);
break;
}
auto rc = write(jpeg_file_fd, buffer.start, bufferinfo.length);
if (rc < 0) {
LOG(ERROR) << "write file failed: " << strerror(errno);
break;
}
close(jpeg_file_fd);
frames_taken++;
} else {
frames_skipped++;
}
bufferinfo.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
bufferinfo.memory = V4L2_MEMORY_MMAP;
/* Set the index if using several buffers */
// Queue the next one.
if (ioctl(fd, VIDIOC_QBUF, &bufferinfo) < 0) {
LOG(ERROR) << "VIDIOC_QBUF failed: " << strerror(errno);
break;
}
if (pause > 0) {
usleep(pause);
}
}
// Deactivate streaming
if (ioctl(fd, VIDIOC_STREAMOFF, &type) < 0) {
LOG(ERROR) << "VIDIOC_STREAMOFF failed: " << strerror(errno);
}
}
private:
class IOBuffer
{
public:
IOBuffer(const IOBuffer&) = delete;
IOBuffer() = default;
~IOBuffer()
{
if (start != nullptr and size > 0) {
auto rc = munmap(start, size);
if (rc < 0) {
LOG(ERROR) << "munmap() failed: " << strerror(errno);
}
}
}
void *start = nullptr;
size_t size = 0;
};
int fd = -1;
IOBuffer buffer;
OptionsPtr options;
bool open_device()
{
if (fd == -1) {
auto device = (*options)["device"].as<std::string>().c_str();
fd = open(device, O_RDWR);
if (fd < 0) {
LOG(ERROR) << "Couldn't open '" << device << "' :" << strerror(errno) << std::endl;
return false;
}
} else {
LOG(WARNING) << "Is device already initialized?";
return false;
}
return true;
}
bool check_capabilities()
{
struct v4l2_capability cap;
std::memset(&cap, 0, sizeof(cap));
if (ioctl(fd, VIDIOC_QUERYCAP, &cap) < 0) {
LOG(ERROR) << "VIDIOC_QUERYCAP failed: " << strerror(errno);
return false;
}
if ((cap.capabilities & V4L2_CAP_VIDEO_CAPTURE) == 0) {
LOG(ERROR) << "the device does not handle single-planar video capture";
return false;
}
if ((cap.capabilities & V4L2_CAP_STREAMING) == 0) {
LOG(ERROR) << "the device does not handle frame streaming";
return false;
}
return true;
}
bool set_format()
{
struct v4l2_format format;
std::memset(&format, 0, sizeof(format));
format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
format.fmt.pix.pixelformat = V4L2_PIX_FMT_MJPEG;
// FIXME: set format specified in cmd. line
format.fmt.pix.width = 800;
format.fmt.pix.height = 600;
if (ioctl(fd, VIDIOC_S_FMT, &format) < 0) {
LOG(ERROR) << "VIDIOC_S_FMT failed: " << strerror(errno);
return false;
}
return true;
}
bool init_buffers()
{
struct v4l2_requestbuffers bufrequest;
std::memset(&bufrequest, 0, sizeof(bufrequest));
bufrequest.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
bufrequest.memory = V4L2_MEMORY_MMAP;
bufrequest.count = 1;
if (ioctl(fd, VIDIOC_REQBUFS, &bufrequest) < 0) {
LOG(ERROR) << "VIDIOC_REQBUFS failed: " << strerror(errno);
return false;
}
struct v4l2_buffer bufferinfo;
std::memset(&bufferinfo, 0, sizeof(bufferinfo));
bufferinfo.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
bufferinfo.memory = V4L2_MEMORY_MMAP;
bufferinfo.index = 0;
if (ioctl(fd, VIDIOC_QUERYBUF, &bufferinfo) < 0) {
LOG(ERROR) << "VIDIOC_QUERYBUF failed: " << strerror(errno);
return false;
}
buffer.start = mmap(
NULL,
bufferinfo.length,
PROT_READ | PROT_WRITE,
MAP_SHARED,
fd,
bufferinfo.m.offset
);
if (buffer.start == MAP_FAILED) {
LOG(ERROR) << "mmaping buffer failed: " << strerror(errno);
return false;
}
buffer.size = bufferinfo.length;
memset(buffer.start, 0, bufferinfo.length);
return true;
}
};
int
main(int argc, char** argv)
{
auto options = std::make_shared<cxxopts::Options>("uvccapture2", "Capture images from an USB camera on Linux");
// clang-format off
options->add_options()
("h,help", "show this help")
("debug", "enable debugging")
("dir", "name of an images directory", cxxopts::value<std::string>())
("device", "camera's device ti use", cxxopts::value<std::string>()->default_value("/dev/video0"))
("resolution", "image's resolution", cxxopts::value<std::string>()->default_value("640x480"))
("skip", "skip specified number of frames before first capture", cxxopts::value<int>())
("count", "number of images to capture", cxxopts::value<int>())
("pause", "pause between subsequent captures in seconds", cxxopts::value<double>())
("loop", "run in loop mode, overrides --count", cxxopts::value<bool>())
;
// clang-format on
options->parse(argc, argv);
if (options->count("help")) {
std::cout << options->help() << std::endl;
return 0;
}
if (options->count("dir") == 0) {
std::cout << "Mandatory parameter '--dir' was not specified." << std::endl;
return 0;
}
el::Configurations defaultConf;
defaultConf.setToDefault();
// Values are always std::string
defaultConf.set(el::Level::Info, el::ConfigurationType::Format, "%datetime %level %loc %msg");
defaultConf.set(el::Level::Error, el::ConfigurationType::Format, "%datetime %level %loc %msg");
// default logger uses default configurations
el::Loggers::reconfigureLogger("default", defaultConf);
std::cout << "images' directory: " << (*options)["dir"].as<std::string>() << std::endl;
std::cout << "device: " << (*options)["device"].as<std::string>() << std::endl;
std::cout << "loop: " << (*options)["loop"].as<bool>() << std::endl;
V4L2Device dev(options);
if (dev.initialize()) {
dev.capture();
}
return 0;
}
<|endoftext|> |
<commit_before>///////////////
// Compilers //
///////////////
#if defined(_MSC_VER)
#define COMPILER_MSVC 1
#endif
#if defined(__GNUC__)
#define COMPILER_GCC 1
#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#endif
#if defined(__clang__)
#define COMPILER_CLANG 1
#endif
///////////////
// Platforms //
///////////////
#if defined(WIN32) || defined(_WIN32)
#define PLATFORM_WINDOWS 1
#endif
#ifdef __APPLE__
#define PLATFORM_OSX 1
#endif
#if defined(__linux__)
#define PLATFORM_LINUX 1
#endif
#include <thread>
#include <chrono>
#include <vector>
#include <stdint.h>
#include <mutex>
#include <iostream>
#include "librealsense/rs.hpp"
#include "GfxUtil.h"
#if defined(PLATFORM_WINDOWS)
#include <GL\glew.h>
#include <GLFW\glfw3.h>
#elif defined(PLATFORM_OSX)
#include "glfw3.h"
#define GLFW_EXPOSE_NATIVE_COCOA
#define GLFW_EXPOSE_NATIVE_NSGL
#include "glfw3native.h"
#include <OpenGL/gl3.h>
#elif defined(PLATFORM_LINUX)
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#endif
GLFWwindow * window;
std::string vertShader = R"(#version 330 core
layout(location = 0) in vec3 position;
out vec2 texCoord;
void main()
{
gl_Position = vec4(position, 1);
texCoord = (position.xy + vec2(1,1)) / 2.0;
}
)";
std::string fragShader = R"(#version 330 core
uniform sampler2D u_image;
in vec2 texCoord;
out vec3 color;
void main()
{
color = texture(u_image, texCoord.st * vec2(1.0, -1.0)).rgb;
}
)";
static const GLfloat g_quad_vertex_buffer_data[] =
{
1.0f, 1.0f, 0.0f,
-1.0f, 1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
-1.0f, 1.0f, 0.0f,
-1.0f, -1.0f, 0.0f,
};
GLuint rgbTextureHandle;
GLuint depthTextureHandle;
GLuint imageUniformHandle;
// Compute field of view angles in degrees from rectified intrinsics
inline float GetAsymmetricFieldOfView(int imageSize, float focalLength, float principalPoint)
{
return (atan2f(principalPoint + 0.5f, focalLength) + atan2f(imageSize - principalPoint - 0.5f, focalLength)) * 180.0f / (float)M_PI;
}
int main(int argc, const char * argv[]) try
{
uint64_t frameCount = 0;
if (!glfwInit())
{
fprintf( stderr, "Failed to initialize GLFW\n" );
return -1;
}
//#if defined(PLATFORM_OSX)
glfwWindowHint(GLFW_SAMPLES, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
//#endif
window = glfwCreateWindow(1280, 480, "R200 Pointcloud", NULL, NULL);
if (!window)
{
std::cout << "Failed to open GLFW window\n" << std::endl;
glfwTerminate();
std::exit( EXIT_FAILURE );
}
glfwMakeContextCurrent(window);
std::cout << "GL_VERSION = " << glGetString(GL_VERSION) << std::endl;
std::cout << "GL_VENDOR = " << glGetString(GL_VENDOR) << std::endl;
std::cout << "GL_RENDERER = " << glGetString(GL_RENDERER) << std::endl;
#if defined(PLATFORM_WINDOWS) || defined(PLATFORM_LINUX)
glewExperimental = GL_TRUE;
if(glewInit() != GLEW_OK) throw std::runtime_error("Failed to initialize GLEW");
#endif
glfwSetWindowSizeCallback(window,
[](GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
});
glfwSetKeyCallback (window,
[](GLFWwindow * window, int key, int, int action, int mods)
{
if (action == GLFW_PRESS)
{
if (key == GLFW_KEY_ESCAPE)
{
glfwSetWindowShouldClose(window, 1);
}
}
});
rs::context realsenseContext;
rs::camera camera;
// Init RealSense R200 Camera -------------------------------------------
if (realsenseContext.get_camera_count() == 0)
{
std::cout << "Error: no cameras detected. Is it plugged in?" << std::endl;
return EXIT_FAILURE;
}
for (int i = 0; i < realsenseContext.get_camera_count(); ++i)
{
std::cout << "Found Camera At Index: " << i << std::endl;
camera = realsenseContext.get_camera(i);
camera.enable_stream(RS_STREAM_DEPTH);
//camera.enable_stream(RS_STREAM_RGB);
camera.configure_streams();
float hFov = GetAsymmetricFieldOfView(
camera.get_stream_property_i(RS_STREAM_DEPTH, RS_IMAGE_SIZE_X),
camera.get_stream_property_f(RS_STREAM_DEPTH, RS_FOCAL_LENGTH_X),
camera.get_stream_property_f(RS_STREAM_DEPTH, RS_PRINCIPAL_POINT_X));
float vFov = GetAsymmetricFieldOfView(
camera.get_stream_property_i(RS_STREAM_DEPTH, RS_IMAGE_SIZE_Y),
camera.get_stream_property_f(RS_STREAM_DEPTH, RS_FOCAL_LENGTH_Y),
camera.get_stream_property_f(RS_STREAM_DEPTH, RS_PRINCIPAL_POINT_Y));
std::cout << "Computed FoV: " << hFov << " x " << vFov << std::endl;
// R200 / DS4
//camera.start_stream(RS_STREAM_DEPTH, 628, 469, 0, RS_FRAME_FORMAT_Z16);
//camera.start_stream(RS_STREAM_RGB, 640, 480, 30, RS_FRAME_FORMAT_YUYV);
// F200 / IVCAM
camera.start_stream(RS_STREAM_DEPTH, 640, 480, 60, RS_FRAME_FORMAT_INVZ);
// camera.start_stream(RS_STREAM_RGB, 640, 480, 30, RS_FRAME_FORMAT_YUYV);
}
// ----------------------------------------------------------------
// Remapped colors...
rgbTextureHandle = CreateTexture(640, 480, GL_RGB); // Normal RGB
depthTextureHandle = CreateTexture(628, 468, GL_RGB); // Depth to RGB remap
GLuint quad_VertexArrayID;
glGenVertexArrays(1, &quad_VertexArrayID);
glBindVertexArray(quad_VertexArrayID);
GLuint quadVBO;
glGenBuffers(1, &quadVBO);
glBindBuffer(GL_ARRAY_BUFFER, quadVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(g_quad_vertex_buffer_data), g_quad_vertex_buffer_data, GL_STATIC_DRAW);
// Create and compile our GLSL program from the shaders
GLuint fullscreenTextureProg = CreateGLProgram(vertShader, fragShader);
imageUniformHandle = glGetUniformLocation(fullscreenTextureProg, "u_image");
while(!glfwWindowShouldClose(window))
{
glfwPollEvents();
glClearColor(0.15f, 0.15f, 0.15f, 1);
glClear(GL_COLOR_BUFFER_BIT);
glfwMakeContextCurrent(window);
int width, height;
glfwGetWindowSize(window, &width, &height);
if (camera && camera.is_streaming())
{
glViewport(0, 0, width, height);
auto depthImage = camera.get_depth_image();
static uint8_t depthColoredHistogram[628 * 468 * 3];
ConvertDepthToRGBUsingHistogram(depthColoredHistogram, depthImage, 628, 468, 0.1f, 0.625f);
drawTexture(fullscreenTextureProg, quadVBO, imageUniformHandle, depthTextureHandle, depthColoredHistogram, 628, 468, GL_RGB, GL_UNSIGNED_BYTE);
//glViewport(width / 2, 0, width, height);
//auto colorImage = camera.get_color_image();
//drawTexture(fullscreenTextureProg, quadVBO, imageUniformHandle, rgbTextureHandle, colorImage, 640, 480, GL_RGB, GL_UNSIGNED_BYTE);
}
frameCount++;
glfwSwapBuffers(window);
CHECK_GL_ERROR();
std::this_thread::sleep_for(std::chrono::milliseconds(16)); // 16 fps
}
glfwTerminate();
return 0;
}
catch (const std::exception & e)
{
std::cerr << "Caught exception: " << e.what() << std::endl;
return EXIT_FAILURE;
}
<commit_msg>add comment about ds5<commit_after>///////////////
// Compilers //
///////////////
#if defined(_MSC_VER)
#define COMPILER_MSVC 1
#endif
#if defined(__GNUC__)
#define COMPILER_GCC 1
#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#endif
#if defined(__clang__)
#define COMPILER_CLANG 1
#endif
///////////////
// Platforms //
///////////////
#if defined(WIN32) || defined(_WIN32)
#define PLATFORM_WINDOWS 1
#endif
#ifdef __APPLE__
#define PLATFORM_OSX 1
#endif
#if defined(__linux__)
#define PLATFORM_LINUX 1
#endif
#include <thread>
#include <chrono>
#include <vector>
#include <stdint.h>
#include <mutex>
#include <iostream>
#include "librealsense/rs.hpp"
#include "GfxUtil.h"
#if defined(PLATFORM_WINDOWS)
#include <GL\glew.h>
#include <GLFW\glfw3.h>
#elif defined(PLATFORM_OSX)
#include "glfw3.h"
#define GLFW_EXPOSE_NATIVE_COCOA
#define GLFW_EXPOSE_NATIVE_NSGL
#include "glfw3native.h"
#include <OpenGL/gl3.h>
#elif defined(PLATFORM_LINUX)
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#endif
GLFWwindow * window;
std::string vertShader = R"(#version 330 core
layout(location = 0) in vec3 position;
out vec2 texCoord;
void main()
{
gl_Position = vec4(position, 1);
texCoord = (position.xy + vec2(1,1)) / 2.0;
}
)";
std::string fragShader = R"(#version 330 core
uniform sampler2D u_image;
in vec2 texCoord;
out vec3 color;
void main()
{
color = texture(u_image, texCoord.st * vec2(1.0, -1.0)).rgb;
}
)";
static const GLfloat g_quad_vertex_buffer_data[] =
{
1.0f, 1.0f, 0.0f,
-1.0f, 1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
-1.0f, 1.0f, 0.0f,
-1.0f, -1.0f, 0.0f,
};
GLuint rgbTextureHandle;
GLuint depthTextureHandle;
GLuint imageUniformHandle;
// Compute field of view angles in degrees from rectified intrinsics
inline float GetAsymmetricFieldOfView(int imageSize, float focalLength, float principalPoint)
{
return (atan2f(principalPoint + 0.5f, focalLength) + atan2f(imageSize - principalPoint - 0.5f, focalLength)) * 180.0f / (float)M_PI;
}
int main(int argc, const char * argv[]) try
{
uint64_t frameCount = 0;
if (!glfwInit())
{
fprintf( stderr, "Failed to initialize GLFW\n" );
return -1;
}
//#if defined(PLATFORM_OSX)
glfwWindowHint(GLFW_SAMPLES, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
//#endif
window = glfwCreateWindow(1280, 480, "R200 Pointcloud", NULL, NULL);
if (!window)
{
std::cout << "Failed to open GLFW window\n" << std::endl;
glfwTerminate();
std::exit( EXIT_FAILURE );
}
glfwMakeContextCurrent(window);
std::cout << "GL_VERSION = " << glGetString(GL_VERSION) << std::endl;
std::cout << "GL_VENDOR = " << glGetString(GL_VENDOR) << std::endl;
std::cout << "GL_RENDERER = " << glGetString(GL_RENDERER) << std::endl;
#if defined(PLATFORM_WINDOWS) || defined(PLATFORM_LINUX)
glewExperimental = GL_TRUE;
if(glewInit() != GLEW_OK) throw std::runtime_error("Failed to initialize GLEW");
#endif
glfwSetWindowSizeCallback(window,
[](GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
});
glfwSetKeyCallback (window,
[](GLFWwindow * window, int key, int, int action, int mods)
{
if (action == GLFW_PRESS)
{
if (key == GLFW_KEY_ESCAPE)
{
glfwSetWindowShouldClose(window, 1);
}
}
});
rs::context realsenseContext;
rs::camera camera;
// Init RealSense R200 Camera -------------------------------------------
if (realsenseContext.get_camera_count() == 0)
{
std::cout << "Error: no cameras detected. Is it plugged in?" << std::endl;
return EXIT_FAILURE;
}
for (int i = 0; i < realsenseContext.get_camera_count(); ++i)
{
std::cout << "Found Camera At Index: " << i << std::endl;
camera = realsenseContext.get_camera(i);
camera.enable_stream(RS_STREAM_DEPTH);
//camera.enable_stream(RS_STREAM_RGB);
camera.configure_streams();
float hFov = GetAsymmetricFieldOfView(
camera.get_stream_property_i(RS_STREAM_DEPTH, RS_IMAGE_SIZE_X),
camera.get_stream_property_f(RS_STREAM_DEPTH, RS_FOCAL_LENGTH_X),
camera.get_stream_property_f(RS_STREAM_DEPTH, RS_PRINCIPAL_POINT_X));
float vFov = GetAsymmetricFieldOfView(
camera.get_stream_property_i(RS_STREAM_DEPTH, RS_IMAGE_SIZE_Y),
camera.get_stream_property_f(RS_STREAM_DEPTH, RS_FOCAL_LENGTH_Y),
camera.get_stream_property_f(RS_STREAM_DEPTH, RS_PRINCIPAL_POINT_Y));
std::cout << "Computed FoV: " << hFov << " x " << vFov << std::endl;
// R300 / DS5
//camera.start_stream(RS_STREAM_DEPTH, 1280, 721, 30, RS_FRAME_FORMAT_Z16);
// R200 / DS4
//camera.start_stream(RS_STREAM_DEPTH, 628, 469, 0, RS_FRAME_FORMAT_Z16);
//camera.start_stream(RS_STREAM_RGB, 640, 480, 30, RS_FRAME_FORMAT_YUYV);
// F200 / IVCAM
camera.start_stream(RS_STREAM_DEPTH, 640, 480, 60, RS_FRAME_FORMAT_INVZ);
// camera.start_stream(RS_STREAM_RGB, 640, 480, 30, RS_FRAME_FORMAT_YUYV);
}
// ----------------------------------------------------------------
// Remapped colors...
rgbTextureHandle = CreateTexture(640, 480, GL_RGB); // Normal RGB
depthTextureHandle = CreateTexture(628, 468, GL_RGB); // Depth to RGB remap
GLuint quad_VertexArrayID;
glGenVertexArrays(1, &quad_VertexArrayID);
glBindVertexArray(quad_VertexArrayID);
GLuint quadVBO;
glGenBuffers(1, &quadVBO);
glBindBuffer(GL_ARRAY_BUFFER, quadVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(g_quad_vertex_buffer_data), g_quad_vertex_buffer_data, GL_STATIC_DRAW);
// Create and compile our GLSL program from the shaders
GLuint fullscreenTextureProg = CreateGLProgram(vertShader, fragShader);
imageUniformHandle = glGetUniformLocation(fullscreenTextureProg, "u_image");
while(!glfwWindowShouldClose(window))
{
glfwPollEvents();
glClearColor(0.15f, 0.15f, 0.15f, 1);
glClear(GL_COLOR_BUFFER_BIT);
glfwMakeContextCurrent(window);
int width, height;
glfwGetWindowSize(window, &width, &height);
if (camera && camera.is_streaming())
{
glViewport(0, 0, width, height);
auto depthImage = camera.get_depth_image();
static uint8_t depthColoredHistogram[628 * 468 * 3];
ConvertDepthToRGBUsingHistogram(depthColoredHistogram, depthImage, 628, 468, 0.1f, 0.625f);
drawTexture(fullscreenTextureProg, quadVBO, imageUniformHandle, depthTextureHandle, depthColoredHistogram, 628, 468, GL_RGB, GL_UNSIGNED_BYTE);
//glViewport(width / 2, 0, width, height);
//auto colorImage = camera.get_color_image();
//drawTexture(fullscreenTextureProg, quadVBO, imageUniformHandle, rgbTextureHandle, colorImage, 640, 480, GL_RGB, GL_UNSIGNED_BYTE);
}
frameCount++;
glfwSwapBuffers(window);
CHECK_GL_ERROR();
std::this_thread::sleep_for(std::chrono::milliseconds(16)); // 16 fps
}
glfwTerminate();
return 0;
}
catch (const std::exception & e)
{
std::cerr << "Caught exception: " << e.what() << std::endl;
return EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <init.h>
#include <interfaces/chain.h>
#include <net.h>
#include <node/context.h>
#include <outputtype.h>
#include <ui_interface.h>
#include <util/moneystr.h>
#include <util/system.h>
#include <util/translation.h>
#include <wallet/coincontrol.h>
#include <wallet/wallet.h>
#include <walletinitinterface.h>
class WalletInit : public WalletInitInterface {
public:
//! Was the wallet component compiled in.
bool HasWalletSupport() const override {return true;}
//! Return the wallets help message.
void AddWalletOptions() const override;
//! Wallets parameter interaction
bool ParameterInteraction() const override;
//! Add wallets that should be opened to list of chain clients.
void Construct(NodeContext& node) const override;
// SYSCOIN
void AutoLockMasternodeCollaterals() const override;
};
const WalletInitInterface& g_wallet_init_interface = WalletInit();
void WalletInit::AddWalletOptions() const
{
gArgs.AddArg("-addresstype", strprintf("What type of addresses to use (\"legacy\", \"p2sh-segwit\", or \"bech32\", default: \"%s\")", FormatOutputType(DEFAULT_ADDRESS_TYPE)), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-avoidpartialspends", strprintf("Group outputs by address, selecting all or none, instead of selecting on a per-output basis. Privacy is improved as an address is only used once (unless someone sends to it after spending from it), but may result in slightly higher fees as suboptimal coin selection may result due to the added limitation (default: %u (always enabled for wallets with \"avoid_reuse\" enabled))", DEFAULT_AVOIDPARTIALSPENDS), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-changetype", "What type of change to use (\"legacy\", \"p2sh-segwit\", or \"bech32\"). Default is same as -addresstype, except when -addresstype=p2sh-segwit a native segwit output is used when sending to a native segwit address)", ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-disablewallet", "Do not load the wallet and disable wallet RPC calls", ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-discardfee=<amt>", strprintf("The fee rate (in %s/kB) that indicates your tolerance for discarding change by adding it to the fee (default: %s). "
"Note: An output is discarded if it is dust at this rate, but we will always discard up to the dust relay fee and a discard fee above that is limited by the fee estimate for the longest target",
CURRENCY_UNIT, FormatMoney(DEFAULT_DISCARD_FEE)), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-fallbackfee=<amt>", strprintf("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data. 0 to entirely disable the fallbackfee feature. (default: %s)",
CURRENCY_UNIT, FormatMoney(DEFAULT_FALLBACK_FEE)), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-keypool=<n>", strprintf("Set key pool size to <n> (default: %u). Warning: Smaller sizes may increase the risk of losing funds when restoring from an old backup, if none of the addresses in the original keypool have been used.", DEFAULT_KEYPOOL_SIZE), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-maxtxfee=<amt>", strprintf("Maximum total fees (in %s) to use in a single wallet transaction; setting this too low may abort large transactions (default: %s)",
CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MAXFEE)), ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-mintxfee=<amt>", strprintf("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)",
CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MINFEE)), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-paytxfee=<amt>", strprintf("Fee (in %s/kB) to add to transactions you send (default: %s)",
CURRENCY_UNIT, FormatMoney(CFeeRate{DEFAULT_PAY_TX_FEE}.GetFeePerK())), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-rescan", "Rescan the block chain for missing wallet transactions on startup", ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-spendzeroconfchange", strprintf("Spend unconfirmed change when sending transactions (default: %u)", DEFAULT_SPEND_ZEROCONF_CHANGE), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-txconfirmtarget=<n>", strprintf("If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)", DEFAULT_TX_CONFIRM_TARGET), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-wallet=<path>", "Specify wallet database path. Can be specified multiple times to load multiple wallets. Path is interpreted relative to <walletdir> if it is not absolute, and will be created if it does not exist (as a directory containing a wallet.dat file and log files). For backwards compatibility this will also accept names of existing data files in <walletdir>.)", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::WALLET);
gArgs.AddArg("-walletbroadcast", strprintf("Make the wallet broadcast transactions (default: %u)", DEFAULT_WALLETBROADCAST), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-walletdir=<dir>", "Specify directory to hold wallets (default: <datadir>/wallets if it exists, otherwise <datadir>)", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::WALLET);
#if HAVE_SYSTEM
gArgs.AddArg("-walletnotify=<cmd>", "Execute command when a wallet transaction changes. %s in cmd is replaced by TxID and %w is replaced by wallet name. %w is not currently implemented on windows. On systems where %w is supported, it should NOT be quoted because this would break shell escaping used to invoke the command.", ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
#endif
gArgs.AddArg("-walletrbf", strprintf("Send transactions with full-RBF opt-in enabled (RPC only, default: %u)", DEFAULT_WALLET_RBF), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-zapwallettxes=<mode>", "Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup"
" (1 = keep tx meta data e.g. payment request information, 2 = drop tx meta data)", ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::WALLET_DEBUG_TEST);
gArgs.AddArg("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::WALLET_DEBUG_TEST);
gArgs.AddArg("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::WALLET_DEBUG_TEST);
gArgs.AddArg("-walletrejectlongchains", strprintf("Wallet will not create transactions that violate mempool chain limits (default: %u)", DEFAULT_WALLET_REJECT_LONG_CHAINS), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::WALLET_DEBUG_TEST);
}
bool WalletInit::ParameterInteraction() const
{
// SYSCOIN
if (gArgs.IsArgSet("-masternodeblsprivkey") && gArgs.SoftSetBoolArg("-disablewallet", true)) {
LogPrintf("%s: parameter interaction: -masternodeblsprivkey set -> setting -disablewallet=1\n", __func__);
}
if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) {
for (const std::string& wallet : gArgs.GetArgs("-wallet")) {
LogPrintf("%s: parameter interaction: -disablewallet -> ignoring -wallet=%s\n", __func__, wallet);
}
return true;
} else if (gArgs.IsArgSet("-masternodeblsprivkey")) {
return InitError(_("You can not start a masternode with wallet enabled."));
}
const bool is_multiwallet = gArgs.GetArgs("-wallet").size() > 1;
if (gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) && gArgs.SoftSetBoolArg("-walletbroadcast", false)) {
LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__);
}
bool zapwallettxes = gArgs.GetBoolArg("-zapwallettxes", false);
// -zapwallettxes implies dropping the mempool on startup
if (zapwallettxes && gArgs.SoftSetBoolArg("-persistmempool", false)) {
LogPrintf("%s: parameter interaction: -zapwallettxes enabled -> setting -persistmempool=0\n", __func__);
}
// -zapwallettxes implies a rescan
if (zapwallettxes) {
if (is_multiwallet) {
return InitError(strprintf(Untranslated("%s is only allowed with a single wallet file"), "-zapwallettxes"));
}
if (gArgs.SoftSetBoolArg("-rescan", true)) {
LogPrintf("%s: parameter interaction: -zapwallettxes enabled -> setting -rescan=1\n", __func__);
}
}
if (gArgs.GetBoolArg("-sysperms", false))
return InitError(Untranslated("-sysperms is not allowed in combination with enabled wallet functionality"));
return true;
}
void WalletInit::Construct(NodeContext& node) const
{
if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) {
LogPrintf("Wallet disabled!\n");
return;
}
gArgs.SoftSetArg("-wallet", "");
node.chain_clients.emplace_back(interfaces::MakeWalletClient(*node.chain, gArgs.GetArgs("-wallet")));
}
// SYSCOIN
void WalletInit::AutoLockMasternodeCollaterals() const
{
for (const std::shared_ptr<CWallet>& pwallet : GetWallets()) {
pwallet->AutoLockMasternodeCollaterals();
}
}
<commit_msg>remove else check already force setting disable wallet<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <init.h>
#include <interfaces/chain.h>
#include <net.h>
#include <node/context.h>
#include <outputtype.h>
#include <ui_interface.h>
#include <util/moneystr.h>
#include <util/system.h>
#include <util/translation.h>
#include <wallet/coincontrol.h>
#include <wallet/wallet.h>
#include <walletinitinterface.h>
class WalletInit : public WalletInitInterface {
public:
//! Was the wallet component compiled in.
bool HasWalletSupport() const override {return true;}
//! Return the wallets help message.
void AddWalletOptions() const override;
//! Wallets parameter interaction
bool ParameterInteraction() const override;
//! Add wallets that should be opened to list of chain clients.
void Construct(NodeContext& node) const override;
// SYSCOIN
void AutoLockMasternodeCollaterals() const override;
};
const WalletInitInterface& g_wallet_init_interface = WalletInit();
void WalletInit::AddWalletOptions() const
{
gArgs.AddArg("-addresstype", strprintf("What type of addresses to use (\"legacy\", \"p2sh-segwit\", or \"bech32\", default: \"%s\")", FormatOutputType(DEFAULT_ADDRESS_TYPE)), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-avoidpartialspends", strprintf("Group outputs by address, selecting all or none, instead of selecting on a per-output basis. Privacy is improved as an address is only used once (unless someone sends to it after spending from it), but may result in slightly higher fees as suboptimal coin selection may result due to the added limitation (default: %u (always enabled for wallets with \"avoid_reuse\" enabled))", DEFAULT_AVOIDPARTIALSPENDS), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-changetype", "What type of change to use (\"legacy\", \"p2sh-segwit\", or \"bech32\"). Default is same as -addresstype, except when -addresstype=p2sh-segwit a native segwit output is used when sending to a native segwit address)", ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-disablewallet", "Do not load the wallet and disable wallet RPC calls", ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-discardfee=<amt>", strprintf("The fee rate (in %s/kB) that indicates your tolerance for discarding change by adding it to the fee (default: %s). "
"Note: An output is discarded if it is dust at this rate, but we will always discard up to the dust relay fee and a discard fee above that is limited by the fee estimate for the longest target",
CURRENCY_UNIT, FormatMoney(DEFAULT_DISCARD_FEE)), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-fallbackfee=<amt>", strprintf("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data. 0 to entirely disable the fallbackfee feature. (default: %s)",
CURRENCY_UNIT, FormatMoney(DEFAULT_FALLBACK_FEE)), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-keypool=<n>", strprintf("Set key pool size to <n> (default: %u). Warning: Smaller sizes may increase the risk of losing funds when restoring from an old backup, if none of the addresses in the original keypool have been used.", DEFAULT_KEYPOOL_SIZE), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-maxtxfee=<amt>", strprintf("Maximum total fees (in %s) to use in a single wallet transaction; setting this too low may abort large transactions (default: %s)",
CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MAXFEE)), ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-mintxfee=<amt>", strprintf("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)",
CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MINFEE)), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-paytxfee=<amt>", strprintf("Fee (in %s/kB) to add to transactions you send (default: %s)",
CURRENCY_UNIT, FormatMoney(CFeeRate{DEFAULT_PAY_TX_FEE}.GetFeePerK())), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-rescan", "Rescan the block chain for missing wallet transactions on startup", ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-spendzeroconfchange", strprintf("Spend unconfirmed change when sending transactions (default: %u)", DEFAULT_SPEND_ZEROCONF_CHANGE), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-txconfirmtarget=<n>", strprintf("If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)", DEFAULT_TX_CONFIRM_TARGET), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-wallet=<path>", "Specify wallet database path. Can be specified multiple times to load multiple wallets. Path is interpreted relative to <walletdir> if it is not absolute, and will be created if it does not exist (as a directory containing a wallet.dat file and log files). For backwards compatibility this will also accept names of existing data files in <walletdir>.)", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::WALLET);
gArgs.AddArg("-walletbroadcast", strprintf("Make the wallet broadcast transactions (default: %u)", DEFAULT_WALLETBROADCAST), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-walletdir=<dir>", "Specify directory to hold wallets (default: <datadir>/wallets if it exists, otherwise <datadir>)", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::WALLET);
#if HAVE_SYSTEM
gArgs.AddArg("-walletnotify=<cmd>", "Execute command when a wallet transaction changes. %s in cmd is replaced by TxID and %w is replaced by wallet name. %w is not currently implemented on windows. On systems where %w is supported, it should NOT be quoted because this would break shell escaping used to invoke the command.", ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
#endif
gArgs.AddArg("-walletrbf", strprintf("Send transactions with full-RBF opt-in enabled (RPC only, default: %u)", DEFAULT_WALLET_RBF), ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-zapwallettxes=<mode>", "Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup"
" (1 = keep tx meta data e.g. payment request information, 2 = drop tx meta data)", ArgsManager::ALLOW_ANY, OptionsCategory::WALLET);
gArgs.AddArg("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::WALLET_DEBUG_TEST);
gArgs.AddArg("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::WALLET_DEBUG_TEST);
gArgs.AddArg("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::WALLET_DEBUG_TEST);
gArgs.AddArg("-walletrejectlongchains", strprintf("Wallet will not create transactions that violate mempool chain limits (default: %u)", DEFAULT_WALLET_REJECT_LONG_CHAINS), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::WALLET_DEBUG_TEST);
}
bool WalletInit::ParameterInteraction() const
{
// SYSCOIN
if (gArgs.IsArgSet("-masternodeblsprivkey") && gArgs.SoftSetBoolArg("-disablewallet", true)) {
LogPrintf("%s: parameter interaction: -masternodeblsprivkey set -> setting -disablewallet=1\n", __func__);
}
if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) {
for (const std::string& wallet : gArgs.GetArgs("-wallet")) {
LogPrintf("%s: parameter interaction: -disablewallet -> ignoring -wallet=%s\n", __func__, wallet);
}
return true;
}
const bool is_multiwallet = gArgs.GetArgs("-wallet").size() > 1;
if (gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) && gArgs.SoftSetBoolArg("-walletbroadcast", false)) {
LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__);
}
bool zapwallettxes = gArgs.GetBoolArg("-zapwallettxes", false);
// -zapwallettxes implies dropping the mempool on startup
if (zapwallettxes && gArgs.SoftSetBoolArg("-persistmempool", false)) {
LogPrintf("%s: parameter interaction: -zapwallettxes enabled -> setting -persistmempool=0\n", __func__);
}
// -zapwallettxes implies a rescan
if (zapwallettxes) {
if (is_multiwallet) {
return InitError(strprintf(Untranslated("%s is only allowed with a single wallet file"), "-zapwallettxes"));
}
if (gArgs.SoftSetBoolArg("-rescan", true)) {
LogPrintf("%s: parameter interaction: -zapwallettxes enabled -> setting -rescan=1\n", __func__);
}
}
if (gArgs.GetBoolArg("-sysperms", false))
return InitError(Untranslated("-sysperms is not allowed in combination with enabled wallet functionality"));
return true;
}
void WalletInit::Construct(NodeContext& node) const
{
if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) {
LogPrintf("Wallet disabled!\n");
return;
}
gArgs.SoftSetArg("-wallet", "");
node.chain_clients.emplace_back(interfaces::MakeWalletClient(*node.chain, gArgs.GetArgs("-wallet")));
}
// SYSCOIN
void WalletInit::AutoLockMasternodeCollaterals() const
{
for (const std::shared_ptr<CWallet>& pwallet : GetWallets()) {
pwallet->AutoLockMasternodeCollaterals();
}
}
<|endoftext|> |
<commit_before>/**
* @file typedef.hpp
* @author Ryan Curtin
*
* Simple typedefs describing template instantiations of the NeighborSearch
* class which are commonly used. This is meant to be included by
* neighbor_search.h but is a separate file for simplicity.
*/
#ifndef __MLPACK_NEIGHBOR_SEARCH_TYPEDEF_H
#define __MLPACK_NEIGHBOR_SEARCH_TYPEDEF_H
// In case someone included this directly.
#include "neighbor_search.hpp"
#include <mlpack/core/metrics/lmetric.hpp>
#include "sort_policies/nearest_neighbor_sort.hpp"
#include "sort_policies/furthest_neighbor_sort.hpp"
namespace mlpack {
namespace neighbor {
/**
* The AllkNN class is the all-k-nearest-neighbors method. It returns squared
* L2 distances (squared Euclidean distances) for each of the k nearest
* neighbors. Squared distances are used because they are slightly faster than
* non-squared distances (they have one fewer call to sqrt()).
*/
typedef NeighborSearch<NearestNeighborSort, metric::SquaredEuclideanDistance>
AllkNN;
/**
* The AllkFN class is the all-k-furthest-neighbors method. It returns squared
* L2 distances (squared Euclidean distances) for each of the k furthest
* neighbors. Squared distances are used because they are slightly faster than
* non-squared distances (they have one fewer call to sqrt()).
*/
typedef NeighborSearch<FurthestNeighborSort, metric::SquaredEuclideanDistance>
AllkFN;
}; // namespace neighbor
}; // namespace mlpack
#endif
<commit_msg>Don't use L2-squared distance by default.<commit_after>/**
* @file typedef.hpp
* @author Ryan Curtin
*
* Simple typedefs describing template instantiations of the NeighborSearch
* class which are commonly used. This is meant to be included by
* neighbor_search.h but is a separate file for simplicity.
*/
#ifndef __MLPACK_NEIGHBOR_SEARCH_TYPEDEF_H
#define __MLPACK_NEIGHBOR_SEARCH_TYPEDEF_H
// In case someone included this directly.
#include "neighbor_search.hpp"
#include <mlpack/core/metrics/lmetric.hpp>
#include "sort_policies/nearest_neighbor_sort.hpp"
#include "sort_policies/furthest_neighbor_sort.hpp"
namespace mlpack {
namespace neighbor {
/**
* The AllkNN class is the all-k-nearest-neighbors method. It returns L2
* distances (Euclidean distances) for each of the k nearest neighbors.
*/
typedef NeighborSearch<NearestNeighborSort, metric::EuclideanDistance> AllkNN;
/**
* The AllkFN class is the all-k-furthest-neighbors method. It returns L2
* distances (Euclidean distances) for each of the k furthest neighbors.
*/
typedef NeighborSearch<FurthestNeighborSort, metric::EuclideanDistance> AllkFN;
}; // namespace neighbor
}; // namespace mlpack
#endif
<|endoftext|> |
<commit_before>//*****************************************************************************
// Copyright 2017-2018 Intel Corporation
//
// 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 "ngraph/runtime/interpreter/int_backend.hpp"
#include "ngraph/descriptor/layout/dense_tensor_layout.hpp"
#include "ngraph/except.hpp"
#include "ngraph/op/convert.hpp"
#include "ngraph/op/select.hpp"
#include "ngraph/op/util/binary_elementwise_comparison.hpp"
#include "ngraph/pass/assign_layout.hpp"
#include "ngraph/pass/like_replacement.hpp"
#include "ngraph/pass/liveness.hpp"
#include "ngraph/pass/manager.hpp"
#include "ngraph/util.hpp"
using namespace std;
using namespace ngraph;
using descriptor::layout::DenseTensorLayout;
extern "C" const char* get_ngraph_version_string()
{
return NGRAPH_VERSION;
}
extern "C" runtime::Backend* new_backend(const char* configuration_string)
{
return new runtime::interpreter::INTBackend();
}
extern "C" void delete_backend(runtime::Backend* backend)
{
delete backend;
}
shared_ptr<runtime::Tensor>
runtime::interpreter::INTBackend::create_tensor(const element::Type& type, const Shape& shape)
{
return make_shared<runtime::HostTensor>(type, shape, "external");
}
shared_ptr<runtime::Tensor> runtime::interpreter::INTBackend::create_tensor(
const element::Type& type, const Shape& shape, void* memory_pointer)
{
return make_shared<runtime::HostTensor>(type, shape, memory_pointer, "external");
}
bool runtime::interpreter::INTBackend::compile(shared_ptr<Function> function)
{
FunctionInstance& instance = m_function_map[function];
if (!instance.m_is_compiled)
{
instance.m_is_compiled = true;
pass::Manager pass_manager;
pass_manager.register_pass<pass::LikeReplacement>();
pass_manager.register_pass<pass::AssignLayout<DenseTensorLayout>>();
pass_manager.register_pass<pass::Liveness>();
pass_manager.run_passes(function);
for (const shared_ptr<Node>& node : function->get_ordered_ops())
{
instance.m_wrapped_nodes.emplace_back(node);
}
}
return true;
}
bool runtime::interpreter::INTBackend::call(shared_ptr<Function> function,
const vector<shared_ptr<runtime::Tensor>>& outputs,
const vector<shared_ptr<runtime::Tensor>>& inputs)
{
validate_call(function, outputs, inputs);
compile(function);
FunctionInstance& instance = m_function_map[function];
// convert inputs to HostTensor
vector<shared_ptr<runtime::HostTensor>> func_inputs;
for (auto tv : inputs)
{
func_inputs.push_back(static_pointer_cast<runtime::HostTensor>(tv));
}
if (instance.m_nan_check_enabled)
{
perform_nan_check(func_inputs);
}
// convert outputs to HostTensor
vector<shared_ptr<runtime::HostTensor>> func_outputs;
for (auto tv : outputs)
{
func_outputs.push_back(static_pointer_cast<runtime::HostTensor>(tv));
}
// map function params -> HostTensor
unordered_map<descriptor::Tensor*, shared_ptr<runtime::HostTensor>> tensor_map;
size_t input_count = 0;
for (auto param : function->get_parameters())
{
for (size_t i = 0; i < param->get_output_size(); ++i)
{
descriptor::Tensor* tv = param->get_output_tensor_ptr(i).get();
tensor_map.insert({tv, func_inputs[input_count++]});
}
}
// map function outputs -> HostTensor
for (size_t output_count = 0; output_count < function->get_output_size(); ++output_count)
{
auto output = function->get_output_op(output_count);
if (!dynamic_pointer_cast<op::Result>(output))
{
throw ngraph_error("One of function's outputs isn't op::Result");
}
descriptor::Tensor* tv = output->get_output_tensor_ptr(0).get();
tensor_map.insert({tv, func_outputs[output_count]});
}
// for each ordered op in the graph
for (const NodeWrapper& wrapped : instance.m_wrapped_nodes)
{
const Node* op = &wrapped.get_node();
auto type_id = wrapped.get_typeid();
if (type_id == OP_TYPEID::Parameter)
{
continue;
}
// get op inputs from map
vector<shared_ptr<runtime::HostTensor>> op_inputs;
for (const descriptor::Input& input : op->get_inputs())
{
descriptor::Tensor* tv = input.get_output().get_tensor_ptr().get();
op_inputs.push_back(tensor_map.at(tv));
}
// get op outputs from map or create
vector<shared_ptr<runtime::HostTensor>> op_outputs;
for (size_t i = 0; i < op->get_output_size(); ++i)
{
descriptor::Tensor* tv = op->get_output_tensor_ptr(i).get();
shared_ptr<runtime::HostTensor> htv;
auto it = tensor_map.find(tv);
if (it == tensor_map.end())
{
// the output tensor is not in the tensor map so create a new tensor
const Shape& shape = op->get_output_shape(i);
const element::Type& type = op->get_output_element_type(i);
string name = op->get_output_tensor(i).get_name();
htv = make_shared<runtime::HostTensor>(type, shape, name);
tensor_map.insert({tv, htv});
}
else
{
htv = it->second;
}
op_outputs.push_back(htv);
}
// get op type
element::Type type;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wswitch-enum"
switch (type_id)
{
case OP_TYPEID::Convert:
case OP_TYPEID::Quantize:
case OP_TYPEID::Dequantize: type = op->get_input_element_type(0); break;
case OP_TYPEID::Equal:
case OP_TYPEID::Greater:
case OP_TYPEID::GreaterEq:
case OP_TYPEID::Less:
case OP_TYPEID::LessEq:
case OP_TYPEID::NotEqual:
// Get the type of the second input, not the first
// All BinaryElementwiseComparision ops have the same type for inputs
// Select has bool for first input and the type we are interested in for the second
type = op->get_input_element_type(1);
break;
default: type = op->get_outputs().at(0).get_element_type(); break;
}
#pragma GCC diagnostic pop
if (instance.m_performance_counters_enabled)
{
instance.m_timer_map[op].start();
}
generate_calls(type, wrapped, op_outputs, op_inputs);
if (instance.m_performance_counters_enabled)
{
instance.m_timer_map[op].stop();
}
if (instance.m_nan_check_enabled)
{
perform_nan_check(op_outputs, op);
}
// delete any obsolete tensors
for (const descriptor::Tensor* t : op->liveness_free_list)
{
for (auto it = tensor_map.begin(); it != tensor_map.end(); ++it)
{
if (it->second->get_name() == t->get_name())
{
tensor_map.erase(it);
break;
}
}
}
}
return true;
}
void runtime::interpreter::INTBackend::generate_calls(const element::Type& type,
const NodeWrapper& op,
const vector<shared_ptr<HostTensor>>& outputs,
const vector<shared_ptr<HostTensor>>& inputs)
{
if (type == element::boolean)
{
op_engine<char>(op, outputs, inputs);
}
else if (type == element::f32)
{
op_engine<float>(op, outputs, inputs);
}
else if (type == element::f64)
{
op_engine<double>(op, outputs, inputs);
}
else if (type == element::i8)
{
op_engine<int8_t>(op, outputs, inputs);
}
else if (type == element::i16)
{
op_engine<int16_t>(op, outputs, inputs);
}
else if (type == element::i32)
{
op_engine<int32_t>(op, outputs, inputs);
}
else if (type == element::i64)
{
op_engine<int64_t>(op, outputs, inputs);
}
else if (type == element::u8)
{
op_engine<uint8_t>(op, outputs, inputs);
}
else if (type == element::u16)
{
op_engine<uint16_t>(op, outputs, inputs);
}
else if (type == element::u32)
{
op_engine<uint32_t>(op, outputs, inputs);
}
else if (type == element::u64)
{
op_engine<uint64_t>(op, outputs, inputs);
}
else
{
stringstream ss;
ss << "unsupported element type " << type << " op " << op.get_node().get_name();
throw ngraph_error(ss.str());
}
}
void runtime::interpreter::INTBackend::set_nan_check(shared_ptr<Function> func, bool enable)
{
FunctionInstance& instance = m_function_map[func];
instance.m_nan_check_enabled = enable;
}
void runtime::interpreter::INTBackend::enable_performance_data(shared_ptr<Function> func,
bool enable)
{
FunctionInstance& instance = m_function_map[func];
instance.m_performance_counters_enabled = enable;
}
vector<runtime::PerformanceCounter>
runtime::interpreter::INTBackend::get_performance_data(shared_ptr<Function> func) const
{
vector<runtime::PerformanceCounter> rc;
const FunctionInstance& instance = m_function_map.at(func);
for (const pair<const Node*, stopwatch> p : instance.m_timer_map)
{
rc.emplace_back(p.first->get_name().c_str(),
p.second.get_total_microseconds(),
p.second.get_call_count());
}
return rc;
}
void runtime::interpreter::INTBackend::perform_nan_check(const vector<shared_ptr<HostTensor>>& tvs,
const Node* op)
{
size_t arg_number = 1;
for (shared_ptr<HostTensor> tv : tvs)
{
const element::Type& type = tv->get_element_type();
if (type == element::f32)
{
const float* data = tv->get_data_ptr<float>();
for (size_t i = 0; i < tv->get_element_count(); i++)
{
if (std::isnan(data[i]))
{
if (op)
{
throw runtime_error("nan found in op '" + op->get_name() + "' output");
}
else
{
throw runtime_error("nan found in function's input tensor number " +
to_string(arg_number));
}
}
}
}
else if (type == element::f64)
{
const double* data = tv->get_data_ptr<double>();
for (size_t i = 0; i < tv->get_element_count(); i++)
{
if (std::isnan(data[i]))
{
if (op)
{
throw runtime_error("nan found in op '" + op->get_name() + "' output");
}
else
{
throw runtime_error("nan found in function's input tensor number " +
to_string(arg_number));
}
}
}
}
arg_number++;
}
}
<commit_msg>argmin/max fix (#1922)<commit_after>//*****************************************************************************
// Copyright 2017-2018 Intel Corporation
//
// 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 "ngraph/runtime/interpreter/int_backend.hpp"
#include "ngraph/descriptor/layout/dense_tensor_layout.hpp"
#include "ngraph/except.hpp"
#include "ngraph/op/convert.hpp"
#include "ngraph/op/select.hpp"
#include "ngraph/op/util/binary_elementwise_comparison.hpp"
#include "ngraph/pass/assign_layout.hpp"
#include "ngraph/pass/like_replacement.hpp"
#include "ngraph/pass/liveness.hpp"
#include "ngraph/pass/manager.hpp"
#include "ngraph/util.hpp"
using namespace std;
using namespace ngraph;
using descriptor::layout::DenseTensorLayout;
extern "C" const char* get_ngraph_version_string()
{
return NGRAPH_VERSION;
}
extern "C" runtime::Backend* new_backend(const char* configuration_string)
{
return new runtime::interpreter::INTBackend();
}
extern "C" void delete_backend(runtime::Backend* backend)
{
delete backend;
}
shared_ptr<runtime::Tensor>
runtime::interpreter::INTBackend::create_tensor(const element::Type& type, const Shape& shape)
{
return make_shared<runtime::HostTensor>(type, shape, "external");
}
shared_ptr<runtime::Tensor> runtime::interpreter::INTBackend::create_tensor(
const element::Type& type, const Shape& shape, void* memory_pointer)
{
return make_shared<runtime::HostTensor>(type, shape, memory_pointer, "external");
}
bool runtime::interpreter::INTBackend::compile(shared_ptr<Function> function)
{
FunctionInstance& instance = m_function_map[function];
if (!instance.m_is_compiled)
{
instance.m_is_compiled = true;
pass::Manager pass_manager;
pass_manager.register_pass<pass::LikeReplacement>();
pass_manager.register_pass<pass::AssignLayout<DenseTensorLayout>>();
pass_manager.register_pass<pass::Liveness>();
pass_manager.run_passes(function);
for (const shared_ptr<Node>& node : function->get_ordered_ops())
{
instance.m_wrapped_nodes.emplace_back(node);
}
}
return true;
}
bool runtime::interpreter::INTBackend::call(shared_ptr<Function> function,
const vector<shared_ptr<runtime::Tensor>>& outputs,
const vector<shared_ptr<runtime::Tensor>>& inputs)
{
validate_call(function, outputs, inputs);
compile(function);
FunctionInstance& instance = m_function_map[function];
// convert inputs to HostTensor
vector<shared_ptr<runtime::HostTensor>> func_inputs;
for (auto tv : inputs)
{
func_inputs.push_back(static_pointer_cast<runtime::HostTensor>(tv));
}
if (instance.m_nan_check_enabled)
{
perform_nan_check(func_inputs);
}
// convert outputs to HostTensor
vector<shared_ptr<runtime::HostTensor>> func_outputs;
for (auto tv : outputs)
{
func_outputs.push_back(static_pointer_cast<runtime::HostTensor>(tv));
}
// map function params -> HostTensor
unordered_map<descriptor::Tensor*, shared_ptr<runtime::HostTensor>> tensor_map;
size_t input_count = 0;
for (auto param : function->get_parameters())
{
for (size_t i = 0; i < param->get_output_size(); ++i)
{
descriptor::Tensor* tv = param->get_output_tensor_ptr(i).get();
tensor_map.insert({tv, func_inputs[input_count++]});
}
}
// map function outputs -> HostTensor
for (size_t output_count = 0; output_count < function->get_output_size(); ++output_count)
{
auto output = function->get_output_op(output_count);
if (!dynamic_pointer_cast<op::Result>(output))
{
throw ngraph_error("One of function's outputs isn't op::Result");
}
descriptor::Tensor* tv = output->get_output_tensor_ptr(0).get();
tensor_map.insert({tv, func_outputs[output_count]});
}
// for each ordered op in the graph
for (const NodeWrapper& wrapped : instance.m_wrapped_nodes)
{
const Node* op = &wrapped.get_node();
auto type_id = wrapped.get_typeid();
if (type_id == OP_TYPEID::Parameter)
{
continue;
}
// get op inputs from map
vector<shared_ptr<runtime::HostTensor>> op_inputs;
for (const descriptor::Input& input : op->get_inputs())
{
descriptor::Tensor* tv = input.get_output().get_tensor_ptr().get();
op_inputs.push_back(tensor_map.at(tv));
}
// get op outputs from map or create
vector<shared_ptr<runtime::HostTensor>> op_outputs;
for (size_t i = 0; i < op->get_output_size(); ++i)
{
descriptor::Tensor* tv = op->get_output_tensor_ptr(i).get();
shared_ptr<runtime::HostTensor> htv;
auto it = tensor_map.find(tv);
if (it == tensor_map.end())
{
// the output tensor is not in the tensor map so create a new tensor
const Shape& shape = op->get_output_shape(i);
const element::Type& type = op->get_output_element_type(i);
string name = op->get_output_tensor(i).get_name();
htv = make_shared<runtime::HostTensor>(type, shape, name);
tensor_map.insert({tv, htv});
}
else
{
htv = it->second;
}
op_outputs.push_back(htv);
}
// get op type
element::Type type;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wswitch-enum"
switch (type_id)
{
case OP_TYPEID::Convert:
case OP_TYPEID::Quantize:
case OP_TYPEID::Dequantize:
case OP_TYPEID::ArgMin:
case OP_TYPEID::ArgMax: type = op->get_input_element_type(0); break;
case OP_TYPEID::Equal:
case OP_TYPEID::Greater:
case OP_TYPEID::GreaterEq:
case OP_TYPEID::Less:
case OP_TYPEID::LessEq:
case OP_TYPEID::NotEqual:
// Get the type of the second input, not the first
// All BinaryElementwiseComparision ops have the same type for inputs
// Select has bool for first input and the type we are interested in for the second
type = op->get_input_element_type(1);
break;
default: type = op->get_outputs().at(0).get_element_type(); break;
}
#pragma GCC diagnostic pop
if (instance.m_performance_counters_enabled)
{
instance.m_timer_map[op].start();
}
generate_calls(type, wrapped, op_outputs, op_inputs);
if (instance.m_performance_counters_enabled)
{
instance.m_timer_map[op].stop();
}
if (instance.m_nan_check_enabled)
{
perform_nan_check(op_outputs, op);
}
// delete any obsolete tensors
for (const descriptor::Tensor* t : op->liveness_free_list)
{
for (auto it = tensor_map.begin(); it != tensor_map.end(); ++it)
{
if (it->second->get_name() == t->get_name())
{
tensor_map.erase(it);
break;
}
}
}
}
return true;
}
void runtime::interpreter::INTBackend::generate_calls(const element::Type& type,
const NodeWrapper& op,
const vector<shared_ptr<HostTensor>>& outputs,
const vector<shared_ptr<HostTensor>>& inputs)
{
if (type == element::boolean)
{
op_engine<char>(op, outputs, inputs);
}
else if (type == element::f32)
{
op_engine<float>(op, outputs, inputs);
}
else if (type == element::f64)
{
op_engine<double>(op, outputs, inputs);
}
else if (type == element::i8)
{
op_engine<int8_t>(op, outputs, inputs);
}
else if (type == element::i16)
{
op_engine<int16_t>(op, outputs, inputs);
}
else if (type == element::i32)
{
op_engine<int32_t>(op, outputs, inputs);
}
else if (type == element::i64)
{
op_engine<int64_t>(op, outputs, inputs);
}
else if (type == element::u8)
{
op_engine<uint8_t>(op, outputs, inputs);
}
else if (type == element::u16)
{
op_engine<uint16_t>(op, outputs, inputs);
}
else if (type == element::u32)
{
op_engine<uint32_t>(op, outputs, inputs);
}
else if (type == element::u64)
{
op_engine<uint64_t>(op, outputs, inputs);
}
else
{
stringstream ss;
ss << "unsupported element type " << type << " op " << op.get_node().get_name();
throw ngraph_error(ss.str());
}
}
void runtime::interpreter::INTBackend::set_nan_check(shared_ptr<Function> func, bool enable)
{
FunctionInstance& instance = m_function_map[func];
instance.m_nan_check_enabled = enable;
}
void runtime::interpreter::INTBackend::enable_performance_data(shared_ptr<Function> func,
bool enable)
{
FunctionInstance& instance = m_function_map[func];
instance.m_performance_counters_enabled = enable;
}
vector<runtime::PerformanceCounter>
runtime::interpreter::INTBackend::get_performance_data(shared_ptr<Function> func) const
{
vector<runtime::PerformanceCounter> rc;
const FunctionInstance& instance = m_function_map.at(func);
for (const pair<const Node*, stopwatch> p : instance.m_timer_map)
{
rc.emplace_back(p.first->get_name().c_str(),
p.second.get_total_microseconds(),
p.second.get_call_count());
}
return rc;
}
void runtime::interpreter::INTBackend::perform_nan_check(const vector<shared_ptr<HostTensor>>& tvs,
const Node* op)
{
size_t arg_number = 1;
for (shared_ptr<HostTensor> tv : tvs)
{
const element::Type& type = tv->get_element_type();
if (type == element::f32)
{
const float* data = tv->get_data_ptr<float>();
for (size_t i = 0; i < tv->get_element_count(); i++)
{
if (std::isnan(data[i]))
{
if (op)
{
throw runtime_error("nan found in op '" + op->get_name() + "' output");
}
else
{
throw runtime_error("nan found in function's input tensor number " +
to_string(arg_number));
}
}
}
}
else if (type == element::f64)
{
const double* data = tv->get_data_ptr<double>();
for (size_t i = 0; i < tv->get_element_count(); i++)
{
if (std::isnan(data[i]))
{
if (op)
{
throw runtime_error("nan found in op '" + op->get_name() + "' output");
}
else
{
throw runtime_error("nan found in function's input tensor number " +
to_string(arg_number));
}
}
}
}
arg_number++;
}
}
<|endoftext|> |
<commit_before>#include "bochs.h"
#include "cpu/extdb.h"
#ifdef WIN32
# include <windows.h>
#else
//# error "extdb.cc only supported in win32 environment"
#endif
TRegs regs;
char debug_loaded = 0;
void (*call_debugger)(TRegs *,Bit8u *, Bit32u);
void bx_external_debugger(BX_CPU_C *cpu)
{
#if 0
//printf("Calling debugger state=%d\n",regs.debug_state);
switch (regs.debug_state) {
case debug_run:
return;
case debug_count:
if (--regs.debug_counter) return;
regs.debug_state = debug_step;
break;
case debug_skip:
if (cpu->dword.eip != regs.debug_eip ||
cpu->sregs[1].selector.value != regs.debug_cs) return;
regs.debug_state = debug_step;
break;
}
regs.rax = cpu->gen_reg[0].rrx;
regs.rcx = cpu->gen_reg[1].rrx;
regs.rdx = cpu->gen_reg[2].rrx;
regs.rbx = cpu->gen_reg[3].rrx;
regs.rsp = cpu->gen_reg[4].rrx;
regs.rbp = cpu->gen_reg[5].rrx;
regs.rsi = cpu->gen_reg[6].rrx;
regs.rdi = cpu->gen_reg[7].rrx;
regs.r8 = cpu->gen_reg[8].rrx;
regs.r9 = cpu->gen_reg[9].rrx;
regs.r10 = cpu->gen_reg[10].rrx;
regs.r11 = cpu->gen_reg[11].rrx;
regs.r12 = cpu->gen_reg[12].rrx;
regs.r13 = cpu->gen_reg[13].rrx;
regs.r14 = cpu->gen_reg[14].rrx;
regs.r15 = cpu->gen_reg[15].rrx;
regs.rip = cpu->rip;
regs.rflags = cpu->read_eflags();
regs.es = cpu->sregs[0].selector.value;
regs.cs = cpu->sregs[1].selector.value;
regs.ss = cpu->sregs[2].selector.value;
regs.ds = cpu->sregs[3].selector.value;
regs.fs = cpu->sregs[4].selector.value;
regs.gs = cpu->sregs[5].selector.value;
regs.gdt.base = cpu->gdtr.base;
regs.gdt.limit = cpu->gdtr.limit;
regs.idt.base = cpu->idtr.base;
regs.idt.limit = cpu->idtr.limit;
regs.ldt = cpu->ldtr.selector.value;
regs.cr0 = cpu->cr0.val32;
regs.cr1 = cpu->cr1;
regs.cr2 = cpu->cr2;
regs.cr3 = cpu->cr3;
regs.cr4 = cpu->cr4.getRegister();
//regs.cr5 = cpu->cr5;
//regs.cr6 = cpu->cr6;
//regs.cr7 = cpu->cr7;
regs.efer = (BX_CPU_THIS_PTR msr.sce << 0)
| (BX_CPU_THIS_PTR msr.lme << 8)
| (BX_CPU_THIS_PTR msr.lma << 10);
if (debug_loaded == 0) {
HINSTANCE hdbg;
debug_loaded = 1;
hdbg = LoadLibrary("debug.dll");
call_debugger = (void (*)(TRegs *,Bit8u *, Bit32u)) GetProcAddress(hdbg,"call_debugger");
if (call_debugger != NULL) debug_loaded = 2;
}
if (debug_loaded == 2) {
bx_vga.timer();
call_debugger(®s,cpu->mem->vector,cpu->mem->len);
}
#endif
}
<commit_msg>Oops, I had #ifdef 0'd the code in here to do a test compile, and forgot to put it back.<commit_after>#include "bochs.h"
#include "cpu/extdb.h"
#ifdef WIN32
# include <windows.h>
#else
//# error "extdb.cc only supported in win32 environment"
#endif
TRegs regs;
char debug_loaded = 0;
void (*call_debugger)(TRegs *,Bit8u *, Bit32u);
void bx_external_debugger(BX_CPU_C *cpu)
{
//printf("Calling debugger state=%d\n",regs.debug_state);
switch (regs.debug_state) {
case debug_run:
return;
case debug_count:
if (--regs.debug_counter) return;
regs.debug_state = debug_step;
break;
case debug_skip:
if (cpu->dword.eip != regs.debug_eip ||
cpu->sregs[1].selector.value != regs.debug_cs) return;
regs.debug_state = debug_step;
break;
}
regs.rax = cpu->gen_reg[0].rrx;
regs.rcx = cpu->gen_reg[1].rrx;
regs.rdx = cpu->gen_reg[2].rrx;
regs.rbx = cpu->gen_reg[3].rrx;
regs.rsp = cpu->gen_reg[4].rrx;
regs.rbp = cpu->gen_reg[5].rrx;
regs.rsi = cpu->gen_reg[6].rrx;
regs.rdi = cpu->gen_reg[7].rrx;
regs.r8 = cpu->gen_reg[8].rrx;
regs.r9 = cpu->gen_reg[9].rrx;
regs.r10 = cpu->gen_reg[10].rrx;
regs.r11 = cpu->gen_reg[11].rrx;
regs.r12 = cpu->gen_reg[12].rrx;
regs.r13 = cpu->gen_reg[13].rrx;
regs.r14 = cpu->gen_reg[14].rrx;
regs.r15 = cpu->gen_reg[15].rrx;
regs.rip = cpu->rip;
regs.rflags = cpu->read_eflags();
regs.es = cpu->sregs[0].selector.value;
regs.cs = cpu->sregs[1].selector.value;
regs.ss = cpu->sregs[2].selector.value;
regs.ds = cpu->sregs[3].selector.value;
regs.fs = cpu->sregs[4].selector.value;
regs.gs = cpu->sregs[5].selector.value;
regs.gdt.base = cpu->gdtr.base;
regs.gdt.limit = cpu->gdtr.limit;
regs.idt.base = cpu->idtr.base;
regs.idt.limit = cpu->idtr.limit;
regs.ldt = cpu->ldtr.selector.value;
regs.cr0 = cpu->cr0.val32;
regs.cr1 = cpu->cr1;
regs.cr2 = cpu->cr2;
regs.cr3 = cpu->cr3;
regs.cr4 = cpu->cr4.getRegister();
//regs.cr5 = cpu->cr5;
//regs.cr6 = cpu->cr6;
//regs.cr7 = cpu->cr7;
regs.efer = (BX_CPU_THIS_PTR msr.sce << 0)
| (BX_CPU_THIS_PTR msr.lme << 8)
| (BX_CPU_THIS_PTR msr.lma << 10);
if (debug_loaded == 0) {
HINSTANCE hdbg;
debug_loaded = 1;
hdbg = LoadLibrary("debug.dll");
call_debugger = (void (*)(TRegs *,Bit8u *, Bit32u)) GetProcAddress(hdbg,"call_debugger");
if (call_debugger != NULL) debug_loaded = 2;
}
if (debug_loaded == 2) {
bx_vga.timer();
call_debugger(®s,cpu->mem->vector,cpu->mem->len);
}
}
<|endoftext|> |
<commit_before>#ifndef UTIL_RECT_H__
#define UTIL_RECT_H__
#include <sstream>
#include <iostream>
#include "point.hpp"
namespace util {
template <typename T>
struct rect {
/**
* Default constructor.
*/
rect() {};
template <typename S>
rect(const rect<S>& other) :
minX(other.minX),
minY(other.minY),
maxX(other.maxX),
maxY(other.maxY) {};
rect(const T& minX_, const T& minY_, const T& maxX_, const T& maxY_) :
minX(minX_),
minY(minY_),
maxX(maxX_),
maxY(maxY_) {};
T minX;
T minY;
T maxX;
T maxY;
T width() const {
return maxX - minX;
}
T height() const {
return maxY - minY;
}
point<T> upperLeft() const {
return point<T>(minX, minY);
}
point<T> lowerRight() const {
return point<T>(maxX, maxY);
}
point<T> upperRight() const {
return point<T>(maxX, minY);
}
point<T> lowerLeft() const {
return point<T>(minX, maxY);
}
point<T> center() const {
return point<T>((minX + maxX)/2, (minY + maxY)/2);
}
bool intersects(const rect<T>& other) const {
// empty rectangles do not intersect
if (area()*other.area() == 0)
return false;
// two non-intersecting rectanlges are separated by a line parallel to
// either x or y
// separated by x-line
if (maxX <= other.minX || minX >= other.maxX)
return false;
// separated by y-line
if (maxY <= other.minY || minY >= other.maxY)
return false;
return true;
}
rect<T> intersection(const rect<T>& other) const {
rect<T> result(0, 0, 0, 0);
if (!intersects(other))
return result;
result.minX = std::max(minX, other.minX);
result.minY = std::max(minY, other.minY);
result.maxX = std::min(maxX, other.maxX);
result.maxY = std::min(maxY, other.maxY);
return result;
}
bool contains(const point<T>& point) const {
return minX <= point.x && minY <= point.y && maxX > point.x && maxY > point.y;
}
bool contains(const rect<T>& other) const {
return minX <= other.minX && minY <= other.minY && maxX >= other.maxX && maxY >= other.maxY;
}
/**
* Extend this rect, such that it fits the given point.
*/
void fit(const point<T>& point) {
minX = std::min(point.x, minX);
minY = std::min(point.y, minY);
maxX = std::max(point.x, maxX);
maxY = std::max(point.y, maxY);
}
T area() const {
return width()*height();
}
bool isZero() const {
return minX == 0 && minY == 0 && maxX == 0 && maxY == 0;
}
template <typename S>
rect<T>& operator+=(const point<S>& other) {
minX += other.x;
maxX += other.x;
minY += other.y;
maxY += other.y;
return *this;
}
template <typename S>
rect<T>& operator-=(const point<S>& other) {
minX -= other.x;
maxX -= other.x;
minY -= other.y;
maxY -= other.y;
return *this;
}
template <typename S>
rect<T>& operator*=(const S& s) {
minX *= s;
maxX *= s;
minY *= s;
maxY *= s;
return *this;
}
template <typename S>
rect<T>& operator/=(const S& s) {
minX /= s;
maxX /= s;
minY /= s;
maxY /= s;
return *this;
}
template <typename S>
rect<T>& operator*=(const point<S>& p) {
minX *= p.x;
maxX *= p.x;
minY *= p.y;
maxY *= p.y;
return *this;
}
template <typename S>
rect<T>& operator/=(const point<S>& p) {
minX /= p.x;
maxX /= p.x;
minY /= p.y;
maxY /= p.y;
return *this;
}
template <typename S>
bool operator==(const rect<S>& other) const {
return minX == other.minX &&
minY == other.minY &&
maxX == other.maxX &&
maxY == other.maxY;
}
template <typename S>
bool operator!=(const rect<S>& other) const {
return !(*this == other);
}
};
} // namespace util
template <typename T, typename S>
util::rect<T> operator+(const util::rect<T>& p, const util::point<S>& o) {
util::rect<T> result(p);
return result += o;
}
template <typename T, typename S>
util::rect<T> operator-(const util::rect<T>& p, const util::point<S>& o) {
util::rect<T> result(p);
return result -= o;
}
template <typename T, typename S>
util::rect<T> operator*(const util::rect<T>& p, const S& s) {
util::rect<T> result(p);
return result *= s;
}
template <typename T, typename S>
util::rect<S> operator*(const S& s, const util::rect<T>& p) {
util::rect<S> result(p);
return result *= s;
}
template <typename T, typename S>
util::rect<T> operator/(const util::rect<T>& p, const S& s) {
util::rect<T> result(p);
return result /= s;
}
template <typename T>
std::ostream& operator<<(std::ostream& os, const util::rect<T>& rect) {
os << "[" << rect.minX << ", " << rect.minY
<< ", " << rect.maxX << ", " << rect.maxY << "]";
return os;
}
#endif // UTIL_RECT_H__
<commit_msg>added fit for rectangles with rectangles<commit_after>#ifndef UTIL_RECT_H__
#define UTIL_RECT_H__
#include <sstream>
#include <iostream>
#include "point.hpp"
namespace util {
template <typename T>
struct rect {
/**
* Default constructor.
*/
rect() {};
template <typename S>
rect(const rect<S>& other) :
minX(other.minX),
minY(other.minY),
maxX(other.maxX),
maxY(other.maxY) {};
rect(const T& minX_, const T& minY_, const T& maxX_, const T& maxY_) :
minX(minX_),
minY(minY_),
maxX(maxX_),
maxY(maxY_) {};
T minX;
T minY;
T maxX;
T maxY;
T width() const {
return maxX - minX;
}
T height() const {
return maxY - minY;
}
point<T> upperLeft() const {
return point<T>(minX, minY);
}
point<T> lowerRight() const {
return point<T>(maxX, maxY);
}
point<T> upperRight() const {
return point<T>(maxX, minY);
}
point<T> lowerLeft() const {
return point<T>(minX, maxY);
}
point<T> center() const {
return point<T>((minX + maxX)/2, (minY + maxY)/2);
}
bool intersects(const rect<T>& other) const {
// empty rectangles do not intersect
if (area()*other.area() == 0)
return false;
// two non-intersecting rectanlges are separated by a line parallel to
// either x or y
// separated by x-line
if (maxX <= other.minX || minX >= other.maxX)
return false;
// separated by y-line
if (maxY <= other.minY || minY >= other.maxY)
return false;
return true;
}
rect<T> intersection(const rect<T>& other) const {
rect<T> result(0, 0, 0, 0);
if (!intersects(other))
return result;
result.minX = std::max(minX, other.minX);
result.minY = std::max(minY, other.minY);
result.maxX = std::min(maxX, other.maxX);
result.maxY = std::min(maxY, other.maxY);
return result;
}
bool contains(const point<T>& point) const {
return minX <= point.x && minY <= point.y && maxX > point.x && maxY > point.y;
}
bool contains(const rect<T>& other) const {
return minX <= other.minX && minY <= other.minY && maxX >= other.maxX && maxY >= other.maxY;
}
/**
* Extend this rect, such that it fits the given point.
*/
void fit(const point<T>& point) {
minX = std::min(point.x, minX);
minY = std::min(point.y, minY);
maxX = std::max(point.x, maxX);
maxY = std::max(point.y, maxY);
}
/**
* Extend this rect, such that it fits the given rect.
*/
void fit(const rect<T>& rect) {
minX = std::min(rect.minX, minX);
minY = std::min(rect.minY, minY);
maxX = std::max(rect.maxX, maxX);
maxY = std::max(rect.maxY, maxY);
}
T area() const {
return width()*height();
}
bool isZero() const {
return minX == 0 && minY == 0 && maxX == 0 && maxY == 0;
}
template <typename S>
rect<T>& operator+=(const point<S>& other) {
minX += other.x;
maxX += other.x;
minY += other.y;
maxY += other.y;
return *this;
}
template <typename S>
rect<T>& operator-=(const point<S>& other) {
minX -= other.x;
maxX -= other.x;
minY -= other.y;
maxY -= other.y;
return *this;
}
template <typename S>
rect<T>& operator*=(const S& s) {
minX *= s;
maxX *= s;
minY *= s;
maxY *= s;
return *this;
}
template <typename S>
rect<T>& operator/=(const S& s) {
minX /= s;
maxX /= s;
minY /= s;
maxY /= s;
return *this;
}
template <typename S>
rect<T>& operator*=(const point<S>& p) {
minX *= p.x;
maxX *= p.x;
minY *= p.y;
maxY *= p.y;
return *this;
}
template <typename S>
rect<T>& operator/=(const point<S>& p) {
minX /= p.x;
maxX /= p.x;
minY /= p.y;
maxY /= p.y;
return *this;
}
template <typename S>
bool operator==(const rect<S>& other) const {
return minX == other.minX &&
minY == other.minY &&
maxX == other.maxX &&
maxY == other.maxY;
}
template <typename S>
bool operator!=(const rect<S>& other) const {
return !(*this == other);
}
};
} // namespace util
template <typename T, typename S>
util::rect<T> operator+(const util::rect<T>& p, const util::point<S>& o) {
util::rect<T> result(p);
return result += o;
}
template <typename T, typename S>
util::rect<T> operator-(const util::rect<T>& p, const util::point<S>& o) {
util::rect<T> result(p);
return result -= o;
}
template <typename T, typename S>
util::rect<T> operator*(const util::rect<T>& p, const S& s) {
util::rect<T> result(p);
return result *= s;
}
template <typename T, typename S>
util::rect<S> operator*(const S& s, const util::rect<T>& p) {
util::rect<S> result(p);
return result *= s;
}
template <typename T, typename S>
util::rect<T> operator/(const util::rect<T>& p, const S& s) {
util::rect<T> result(p);
return result /= s;
}
template <typename T>
std::ostream& operator<<(std::ostream& os, const util::rect<T>& rect) {
os << "[" << rect.minX << ", " << rect.minY
<< ", " << rect.maxX << ", " << rect.maxY << "]";
return os;
}
#endif // UTIL_RECT_H__
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <qfont.h>
#include <qfontmetrics.h>
#include <qfontdatabase.h>
#include <qstringlist.h>
#include <qlist.h>
//TESTED_CLASS=
//TESTED_FILES=
class tst_QFontMetrics : public QObject
{
Q_OBJECT
public:
tst_QFontMetrics();
virtual ~tst_QFontMetrics();
public slots:
void init();
void cleanup();
private slots:
void same();
void metrics();
void boundingRect();
void elidedText_data();
void elidedText();
void veryNarrowElidedText();
void averageCharWidth();
void elidedMultiLength();
void bearingIncludedInBoundingRect();
};
tst_QFontMetrics::tst_QFontMetrics()
{
}
tst_QFontMetrics::~tst_QFontMetrics()
{
}
void tst_QFontMetrics::init()
{
}
void tst_QFontMetrics::cleanup()
{
}
void tst_QFontMetrics::same()
{
QFont font;
font.setBold(true);
QFontMetrics fm(font);
const QString text = QLatin1String("Some stupid STRING");
QCOMPARE(fm.size(0, text), fm.size(0, text)) ;
}
void tst_QFontMetrics::metrics()
{
QFont font;
QFontDatabase fdb;
// Query the QFontDatabase for a specific font, store the
// result in family, style and size.
QStringList families = fdb.families();
if (families.isEmpty())
return;
QStringList::ConstIterator f_it, f_end = families.end();
for (f_it = families.begin(); f_it != f_end; ++f_it) {
const QString &family = *f_it;
QStringList styles = fdb.styles(family);
QStringList::ConstIterator s_it, s_end = styles.end();
for (s_it = styles.begin(); s_it != s_end; ++s_it) {
const QString &style = *s_it;
if (fdb.isSmoothlyScalable(family, style)) {
// smoothly scalable font... don't need to load every pointsize
font = fdb.font(family, style, 12);
QFontMetrics fontmetrics(font);
QCOMPARE(fontmetrics.ascent() + fontmetrics.descent() + 1,
fontmetrics.height());
QCOMPARE(fontmetrics.height() + fontmetrics.leading(),
fontmetrics.lineSpacing());
} else {
QList<int> sizes = fdb.pointSizes(family, style);
QVERIFY(!sizes.isEmpty());
QList<int>::ConstIterator z_it, z_end = sizes.end();
for (z_it = sizes.begin(); z_it != z_end; ++z_it) {
const int size = *z_it;
// Initialize the font, and check if it is an exact match
font = fdb.font(family, style, size);
QFontMetrics fontmetrics(font);
QCOMPARE(fontmetrics.ascent() + fontmetrics.descent() + 1,
fontmetrics.height());
QCOMPARE(fontmetrics.height() + fontmetrics.leading(),
fontmetrics.lineSpacing());
}
}
}
}
}
void tst_QFontMetrics::boundingRect()
{
QFont f;
f.setPointSize(24);
QFontMetrics fm(f);
QRect r = fm.boundingRect(QChar('Y'));
QVERIFY(r.top() < 0);
r = fm.boundingRect(QString("Y"));
QVERIFY(r.top() < 0);
}
void tst_QFontMetrics::elidedText_data()
{
QTest::addColumn<QFont>("font");
QTest::addColumn<QString>("text");
QTest::newRow("helvetica hello") << QFont("helvetica",10) << QString("hello") ;
QTest::newRow("helvetica hello &Bye") << QFont("helvetica",10) << QString("hello&Bye") ;
}
void tst_QFontMetrics::elidedText()
{
QFETCH(QFont, font);
QFETCH(QString, text);
QFontMetrics fm(font);
int w = fm.width(text);
QString newtext = fm.elidedText(text,Qt::ElideRight,w+1, 0);
QCOMPARE(text,newtext); // should not elide
newtext = fm.elidedText(text,Qt::ElideRight,w-1, 0);
QVERIFY(text != newtext); // should elide
}
void tst_QFontMetrics::veryNarrowElidedText()
{
QFont f;
QFontMetrics fm(f);
QString text("hello");
QCOMPARE(fm.elidedText(text, Qt::ElideRight, 0), QString());
}
void tst_QFontMetrics::averageCharWidth()
{
QFont f;
QFontMetrics fm(f);
QVERIFY(fm.averageCharWidth() != 0);
QFontMetricsF fmf(f);
QVERIFY(fmf.averageCharWidth() != 0);
}
void tst_QFontMetrics::elidedMultiLength()
{
QString text1 = "Long Text 1\x9cShorter\x9csmall";
QString text1_long = "Long Text 1";
QString text1_short = "Shorter";
QString text1_small = "small";
QFontMetrics fm = QFontMetrics(QFont());
int width_long = fm.size(0, text1_long).width();
QCOMPARE(fm.elidedText(text1,Qt::ElideRight, 8000), text1_long);
QCOMPARE(fm.elidedText(text1,Qt::ElideRight, width_long + 1), text1_long);
QCOMPARE(fm.elidedText(text1,Qt::ElideRight, width_long - 1), text1_short);
int width_short = fm.size(0, text1_short).width();
QCOMPARE(fm.elidedText(text1,Qt::ElideRight, width_short + 1), text1_short);
QCOMPARE(fm.elidedText(text1,Qt::ElideRight, width_short - 1), text1_small);
// Not even wide enough for "small" - should use ellipsis
QChar ellipsisChar(0x2026);
QString text1_el = QString::fromLatin1("s") + ellipsisChar;
int width_small = fm.width(text1_el);
QCOMPARE(fm.elidedText(text1,Qt::ElideRight, width_small + 1), text1_el);
}
void tst_QFontMetrics::bearingIncludedInBoundingRect()
{
QFont font;
font.setItalic(true);
QRect brectItalic = QFontMetrics(font).boundingRect("ITALIC");
font.setItalic(false);
QRect brectNormal = QFontMetrics(font).boundingRect("ITALIC");
QVERIFY(brectItalic.width() > brectNormal.width());
}
QTEST_MAIN(tst_QFontMetrics)
#include "tst_qfontmetrics.moc"
<commit_msg>QFontMetrics test<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <qfont.h>
#include <qfontmetrics.h>
#include <qfontdatabase.h>
#include <qstringlist.h>
#include <qlist.h>
//TESTED_CLASS=
//TESTED_FILES=
class tst_QFontMetrics : public QObject
{
Q_OBJECT
public:
tst_QFontMetrics();
virtual ~tst_QFontMetrics();
public slots:
void init();
void cleanup();
private slots:
void same();
void metrics();
void boundingRect();
void elidedText_data();
void elidedText();
void veryNarrowElidedText();
void averageCharWidth();
void elidedMultiLength();
void bearingIncludedInBoundingRect();
};
tst_QFontMetrics::tst_QFontMetrics()
{
}
tst_QFontMetrics::~tst_QFontMetrics()
{
}
void tst_QFontMetrics::init()
{
}
void tst_QFontMetrics::cleanup()
{
}
void tst_QFontMetrics::same()
{
QFont font;
font.setBold(true);
QFontMetrics fm(font);
const QString text = QLatin1String("Some stupid STRING");
QCOMPARE(fm.size(0, text), fm.size(0, text)) ;
{
QImage image;
QFontMetrics fm2(font, &image);
QString text2 = QLatin1String("Foo Foo");
QCOMPARE(fm2.size(0, text2), fm2.size(0, text2)); //used to crash
}
{
QImage image;
QFontMetricsF fm3(font, &image);
QString text2 = QLatin1String("Foo Foo");
QCOMPARE(fm3.size(0, text2), fm3.size(0, text2)); //used to crash
}
}
void tst_QFontMetrics::metrics()
{
QFont font;
QFontDatabase fdb;
// Query the QFontDatabase for a specific font, store the
// result in family, style and size.
QStringList families = fdb.families();
if (families.isEmpty())
return;
QStringList::ConstIterator f_it, f_end = families.end();
for (f_it = families.begin(); f_it != f_end; ++f_it) {
const QString &family = *f_it;
QStringList styles = fdb.styles(family);
QStringList::ConstIterator s_it, s_end = styles.end();
for (s_it = styles.begin(); s_it != s_end; ++s_it) {
const QString &style = *s_it;
if (fdb.isSmoothlyScalable(family, style)) {
// smoothly scalable font... don't need to load every pointsize
font = fdb.font(family, style, 12);
QFontMetrics fontmetrics(font);
QCOMPARE(fontmetrics.ascent() + fontmetrics.descent() + 1,
fontmetrics.height());
QCOMPARE(fontmetrics.height() + fontmetrics.leading(),
fontmetrics.lineSpacing());
} else {
QList<int> sizes = fdb.pointSizes(family, style);
QVERIFY(!sizes.isEmpty());
QList<int>::ConstIterator z_it, z_end = sizes.end();
for (z_it = sizes.begin(); z_it != z_end; ++z_it) {
const int size = *z_it;
// Initialize the font, and check if it is an exact match
font = fdb.font(family, style, size);
QFontMetrics fontmetrics(font);
QCOMPARE(fontmetrics.ascent() + fontmetrics.descent() + 1,
fontmetrics.height());
QCOMPARE(fontmetrics.height() + fontmetrics.leading(),
fontmetrics.lineSpacing());
}
}
}
}
}
void tst_QFontMetrics::boundingRect()
{
QFont f;
f.setPointSize(24);
QFontMetrics fm(f);
QRect r = fm.boundingRect(QChar('Y'));
QVERIFY(r.top() < 0);
r = fm.boundingRect(QString("Y"));
QVERIFY(r.top() < 0);
}
void tst_QFontMetrics::elidedText_data()
{
QTest::addColumn<QFont>("font");
QTest::addColumn<QString>("text");
QTest::newRow("helvetica hello") << QFont("helvetica",10) << QString("hello") ;
QTest::newRow("helvetica hello &Bye") << QFont("helvetica",10) << QString("hello&Bye") ;
}
void tst_QFontMetrics::elidedText()
{
QFETCH(QFont, font);
QFETCH(QString, text);
QFontMetrics fm(font);
int w = fm.width(text);
QString newtext = fm.elidedText(text,Qt::ElideRight,w+1, 0);
QCOMPARE(text,newtext); // should not elide
newtext = fm.elidedText(text,Qt::ElideRight,w-1, 0);
QVERIFY(text != newtext); // should elide
}
void tst_QFontMetrics::veryNarrowElidedText()
{
QFont f;
QFontMetrics fm(f);
QString text("hello");
QCOMPARE(fm.elidedText(text, Qt::ElideRight, 0), QString());
}
void tst_QFontMetrics::averageCharWidth()
{
QFont f;
QFontMetrics fm(f);
QVERIFY(fm.averageCharWidth() != 0);
QFontMetricsF fmf(f);
QVERIFY(fmf.averageCharWidth() != 0);
}
void tst_QFontMetrics::elidedMultiLength()
{
QString text1 = "Long Text 1\x9cShorter\x9csmall";
QString text1_long = "Long Text 1";
QString text1_short = "Shorter";
QString text1_small = "small";
QFontMetrics fm = QFontMetrics(QFont());
int width_long = fm.size(0, text1_long).width();
QCOMPARE(fm.elidedText(text1,Qt::ElideRight, 8000), text1_long);
QCOMPARE(fm.elidedText(text1,Qt::ElideRight, width_long + 1), text1_long);
QCOMPARE(fm.elidedText(text1,Qt::ElideRight, width_long - 1), text1_short);
int width_short = fm.size(0, text1_short).width();
QCOMPARE(fm.elidedText(text1,Qt::ElideRight, width_short + 1), text1_short);
QCOMPARE(fm.elidedText(text1,Qt::ElideRight, width_short - 1), text1_small);
// Not even wide enough for "small" - should use ellipsis
QChar ellipsisChar(0x2026);
QString text1_el = QString::fromLatin1("s") + ellipsisChar;
int width_small = fm.width(text1_el);
QCOMPARE(fm.elidedText(text1,Qt::ElideRight, width_small + 1), text1_el);
}
void tst_QFontMetrics::bearingIncludedInBoundingRect()
{
QFont font;
font.setItalic(true);
QRect brectItalic = QFontMetrics(font).boundingRect("ITALIC");
font.setItalic(false);
QRect brectNormal = QFontMetrics(font).boundingRect("ITALIC");
QVERIFY(brectItalic.width() > brectNormal.width());
}
QTEST_MAIN(tst_QFontMetrics)
#include "tst_qfontmetrics.moc"
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fmtwrapinfluenceonobjpos.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2007-09-27 08:25:24 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifndef _FMTWRAPINFLUENCEONOBJPOS_HXX
#include <fmtwrapinfluenceonobjpos.hxx>
#endif
#ifndef _UNOMID_H
#include <unomid.h>
#endif
using namespace ::com::sun::star::uno;
TYPEINIT1(SwFmtWrapInfluenceOnObjPos, SfxPoolItem);
SwFmtWrapInfluenceOnObjPos::SwFmtWrapInfluenceOnObjPos(
sal_Int16 _nWrapInfluenceOnPosition )
: SfxPoolItem( RES_WRAP_INFLUENCE_ON_OBJPOS ),
mnWrapInfluenceOnPosition( _nWrapInfluenceOnPosition )
{
}
SwFmtWrapInfluenceOnObjPos::SwFmtWrapInfluenceOnObjPos(
const SwFmtWrapInfluenceOnObjPos& _rCpy )
: SfxPoolItem( RES_WRAP_INFLUENCE_ON_OBJPOS ),
mnWrapInfluenceOnPosition( _rCpy.GetWrapInfluenceOnObjPos() )
{
}
SwFmtWrapInfluenceOnObjPos::~SwFmtWrapInfluenceOnObjPos()
{
}
SwFmtWrapInfluenceOnObjPos& SwFmtWrapInfluenceOnObjPos::operator=(
const SwFmtWrapInfluenceOnObjPos& _rSource )
{
mnWrapInfluenceOnPosition = _rSource.GetWrapInfluenceOnObjPos();
return *this;
}
int SwFmtWrapInfluenceOnObjPos::operator==( const SfxPoolItem& _rAttr ) const
{
ASSERT( SfxPoolItem::operator==( _rAttr ), "keine gleichen Attribute" );
return ( mnWrapInfluenceOnPosition ==
static_cast<const SwFmtWrapInfluenceOnObjPos&>(_rAttr).
GetWrapInfluenceOnObjPos() );
}
SfxPoolItem* SwFmtWrapInfluenceOnObjPos::Clone( SfxItemPool * ) const
{
return new SwFmtWrapInfluenceOnObjPos(*this);
}
BOOL SwFmtWrapInfluenceOnObjPos::QueryValue( Any& rVal, BYTE nMemberId ) const
{
nMemberId &= ~CONVERT_TWIPS;
sal_Bool bRet = sal_True;
switch ( nMemberId )
{
case MID_WRAP_INFLUENCE:
{
rVal <<= GetWrapInfluenceOnObjPos();
}
break;
default:
ASSERT( false, "<SwFmtWrapInfluenceOnObjPos::QueryValue()> - unknown MemberId" );
bRet = sal_False;
}
return bRet;
}
BOOL SwFmtWrapInfluenceOnObjPos::PutValue( const Any& rVal, BYTE nMemberId )
{
nMemberId &= ~CONVERT_TWIPS;
sal_Bool bRet = sal_True;
switch ( nMemberId )
{
case MID_WRAP_INFLUENCE:
{
sal_Int16 nNewWrapInfluence;
rVal >>= nNewWrapInfluence;
// --> OD 2004-10-18 #i35017# - constant names have changed and
// <ITERATIVE> has been added
if ( nNewWrapInfluence == text::WrapInfluenceOnPosition::ONCE_SUCCESSIVE ||
nNewWrapInfluence == text::WrapInfluenceOnPosition::ONCE_CONCURRENT ||
nNewWrapInfluence == text::WrapInfluenceOnPosition::ITERATIVE )
// <--
{
SetWrapInfluenceOnObjPos( nNewWrapInfluence );
}
else
{
ASSERT( false, "<SwFmtWrapInfluenceOnObjPos::PutValue(..)> - invalid attribute value" );
bRet = sal_False;
}
}
break;
default:
ASSERT( false, "<SwFmtWrapInfluenceOnObjPos::QueryValue()> - unknown MemberId" );
bRet = sal_False;
}
return bRet;
}
void SwFmtWrapInfluenceOnObjPos::SetWrapInfluenceOnObjPos( sal_Int16 _nWrapInfluenceOnPosition )
{
// --> OD 2004-10-18 #i35017# - constant names have changed and consider
// new value <ITERATIVE>
if ( _nWrapInfluenceOnPosition == text::WrapInfluenceOnPosition::ONCE_SUCCESSIVE ||
_nWrapInfluenceOnPosition == text::WrapInfluenceOnPosition::ONCE_CONCURRENT ||
_nWrapInfluenceOnPosition == text::WrapInfluenceOnPosition::ITERATIVE )
// <--
{
mnWrapInfluenceOnPosition = _nWrapInfluenceOnPosition;
}
else
{
ASSERT( false, "<SwFmtWrapInfluenceOnObjPos::SetWrapInfluenceOnObjPos(..)> - invalid attribute value" );
}
}
// --> OD 2004-10-18 #i35017# - add parameter <_bIterativeAsOnceConcurrent>
// to control, if value <ITERATIVE> has to be treated as <ONCE_CONCURRENT>
sal_Int16 SwFmtWrapInfluenceOnObjPos::GetWrapInfluenceOnObjPos(
const bool _bIterativeAsOnceConcurrent ) const
{
sal_Int16 nWrapInfluenceOnPosition( mnWrapInfluenceOnPosition );
if ( _bIterativeAsOnceConcurrent &&
nWrapInfluenceOnPosition == text::WrapInfluenceOnPosition::ITERATIVE )
{
nWrapInfluenceOnPosition = text::WrapInfluenceOnPosition::ONCE_CONCURRENT;
}
return nWrapInfluenceOnPosition;
}
// <--
<commit_msg>INTEGRATION: CWS swusing (1.6.38); FILE MERGED 2007/10/11 08:34:51 tl 1.6.38.1: #i82476# make 'using' declarations private<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fmtwrapinfluenceonobjpos.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: vg $ $Date: 2007-10-22 15:10:25 $
*
* 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_sw.hxx"
#ifndef _FMTWRAPINFLUENCEONOBJPOS_HXX
#include <fmtwrapinfluenceonobjpos.hxx>
#endif
#ifndef _UNOMID_H
#include <unomid.h>
#endif
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
TYPEINIT1(SwFmtWrapInfluenceOnObjPos, SfxPoolItem);
SwFmtWrapInfluenceOnObjPos::SwFmtWrapInfluenceOnObjPos(
sal_Int16 _nWrapInfluenceOnPosition )
: SfxPoolItem( RES_WRAP_INFLUENCE_ON_OBJPOS ),
mnWrapInfluenceOnPosition( _nWrapInfluenceOnPosition )
{
}
SwFmtWrapInfluenceOnObjPos::SwFmtWrapInfluenceOnObjPos(
const SwFmtWrapInfluenceOnObjPos& _rCpy )
: SfxPoolItem( RES_WRAP_INFLUENCE_ON_OBJPOS ),
mnWrapInfluenceOnPosition( _rCpy.GetWrapInfluenceOnObjPos() )
{
}
SwFmtWrapInfluenceOnObjPos::~SwFmtWrapInfluenceOnObjPos()
{
}
SwFmtWrapInfluenceOnObjPos& SwFmtWrapInfluenceOnObjPos::operator=(
const SwFmtWrapInfluenceOnObjPos& _rSource )
{
mnWrapInfluenceOnPosition = _rSource.GetWrapInfluenceOnObjPos();
return *this;
}
int SwFmtWrapInfluenceOnObjPos::operator==( const SfxPoolItem& _rAttr ) const
{
ASSERT( SfxPoolItem::operator==( _rAttr ), "keine gleichen Attribute" );
return ( mnWrapInfluenceOnPosition ==
static_cast<const SwFmtWrapInfluenceOnObjPos&>(_rAttr).
GetWrapInfluenceOnObjPos() );
}
SfxPoolItem* SwFmtWrapInfluenceOnObjPos::Clone( SfxItemPool * ) const
{
return new SwFmtWrapInfluenceOnObjPos(*this);
}
BOOL SwFmtWrapInfluenceOnObjPos::QueryValue( Any& rVal, BYTE nMemberId ) const
{
nMemberId &= ~CONVERT_TWIPS;
sal_Bool bRet = sal_True;
switch ( nMemberId )
{
case MID_WRAP_INFLUENCE:
{
rVal <<= GetWrapInfluenceOnObjPos();
}
break;
default:
ASSERT( false, "<SwFmtWrapInfluenceOnObjPos::QueryValue()> - unknown MemberId" );
bRet = sal_False;
}
return bRet;
}
BOOL SwFmtWrapInfluenceOnObjPos::PutValue( const Any& rVal, BYTE nMemberId )
{
nMemberId &= ~CONVERT_TWIPS;
sal_Bool bRet = sal_True;
switch ( nMemberId )
{
case MID_WRAP_INFLUENCE:
{
sal_Int16 nNewWrapInfluence;
rVal >>= nNewWrapInfluence;
// --> OD 2004-10-18 #i35017# - constant names have changed and
// <ITERATIVE> has been added
if ( nNewWrapInfluence == text::WrapInfluenceOnPosition::ONCE_SUCCESSIVE ||
nNewWrapInfluence == text::WrapInfluenceOnPosition::ONCE_CONCURRENT ||
nNewWrapInfluence == text::WrapInfluenceOnPosition::ITERATIVE )
// <--
{
SetWrapInfluenceOnObjPos( nNewWrapInfluence );
}
else
{
ASSERT( false, "<SwFmtWrapInfluenceOnObjPos::PutValue(..)> - invalid attribute value" );
bRet = sal_False;
}
}
break;
default:
ASSERT( false, "<SwFmtWrapInfluenceOnObjPos::QueryValue()> - unknown MemberId" );
bRet = sal_False;
}
return bRet;
}
void SwFmtWrapInfluenceOnObjPos::SetWrapInfluenceOnObjPos( sal_Int16 _nWrapInfluenceOnPosition )
{
// --> OD 2004-10-18 #i35017# - constant names have changed and consider
// new value <ITERATIVE>
if ( _nWrapInfluenceOnPosition == text::WrapInfluenceOnPosition::ONCE_SUCCESSIVE ||
_nWrapInfluenceOnPosition == text::WrapInfluenceOnPosition::ONCE_CONCURRENT ||
_nWrapInfluenceOnPosition == text::WrapInfluenceOnPosition::ITERATIVE )
// <--
{
mnWrapInfluenceOnPosition = _nWrapInfluenceOnPosition;
}
else
{
ASSERT( false, "<SwFmtWrapInfluenceOnObjPos::SetWrapInfluenceOnObjPos(..)> - invalid attribute value" );
}
}
// --> OD 2004-10-18 #i35017# - add parameter <_bIterativeAsOnceConcurrent>
// to control, if value <ITERATIVE> has to be treated as <ONCE_CONCURRENT>
sal_Int16 SwFmtWrapInfluenceOnObjPos::GetWrapInfluenceOnObjPos(
const bool _bIterativeAsOnceConcurrent ) const
{
sal_Int16 nWrapInfluenceOnPosition( mnWrapInfluenceOnPosition );
if ( _bIterativeAsOnceConcurrent &&
nWrapInfluenceOnPosition == text::WrapInfluenceOnPosition::ITERATIVE )
{
nWrapInfluenceOnPosition = text::WrapInfluenceOnPosition::ONCE_CONCURRENT;
}
return nWrapInfluenceOnPosition;
}
// <--
<|endoftext|> |
<commit_before>#include "ObjectManager.h"
#include "Object.h"
#include "Engine.h"
#include "ComponentSystem.hpp"
#include "Transform.h"
using namespace Core;
Object& ObjectManager::Add(const std::string& name, ComponentSystem* compoSystem, TransformPool* tfPool)
{
ObjectID key = _objIDMgr.Acquire();
_idBookmark.Add(name, key.Literal());
return _objects.Add(key, Object(key));
}
void ObjectManager::Delete(const std::string& name)
{
uint objLiteralID = _idBookmark.Find(name);
_objects.Delete(ObjectID(objLiteralID));
_idBookmark.Delete(name);
_objIDMgr.Delete(ObjectID(objLiteralID));
}
bool ObjectManager::Has(const std::string& name) const
{
return _idBookmark.Has(name);
}
Object* ObjectManager::Find(const std::string& name)
{
return _objects.Find( ObjectID(_idBookmark.Find(name)) );
}
const Object* ObjectManager::Find(const std::string& name) const
{
return _objects.Find(ObjectID(_idBookmark.Find(name)));
}
void Core::ObjectManager::Delete(ObjectID id)
{
Object* findObj = _objects.Find(id);
if(findObj == nullptr) return;
_idBookmark.Delete(findObj->GetName());
_objects.Delete(id);
_objIDMgr.Delete(id);
}
bool Core::ObjectManager::Has(ObjectID id) const
{
return _objects.Has(id);
}
Object* Core::ObjectManager::Find(ObjectID id)
{
return _objects.Find(id);
}
const Object* Core::ObjectManager::Find(ObjectID id) const
{
return _objects.Find(id);
}
void ObjectManager::DeleteAll()
{
_objects.DeleteAll();
_idBookmark.DeleteAll();
_objIDMgr.DeleteAll();
}<commit_msg>ObjectManager - Add에 필요없는 파라메터 제거<commit_after>#include "ObjectManager.h"
#include "Object.h"
#include "Engine.h"
#include "ComponentSystem.hpp"
#include "Transform.h"
using namespace Core;
Object& ObjectManager::Add(const std::string& name)
{
ObjectID key = _objIDMgr.Acquire();
_idBookmark.Add(name, key.Literal());
return _objects.Add(key, Object(key));
}
void ObjectManager::Delete(const std::string& name)
{
uint objLiteralID = _idBookmark.Find(name);
_objects.Delete(ObjectID(objLiteralID));
_idBookmark.Delete(name);
_objIDMgr.Delete(ObjectID(objLiteralID));
}
bool ObjectManager::Has(const std::string& name) const
{
return _idBookmark.Has(name);
}
Object* ObjectManager::Find(const std::string& name)
{
return _objects.Find( ObjectID(_idBookmark.Find(name)) );
}
const Object* ObjectManager::Find(const std::string& name) const
{
return _objects.Find(ObjectID(_idBookmark.Find(name)));
}
void Core::ObjectManager::Delete(ObjectID id)
{
Object* findObj = _objects.Find(id);
if(findObj == nullptr) return;
_idBookmark.Delete(findObj->GetName());
_objects.Delete(id);
_objIDMgr.Delete(id);
}
bool Core::ObjectManager::Has(ObjectID id) const
{
return _objects.Has(id);
}
Object* Core::ObjectManager::Find(ObjectID id)
{
return _objects.Find(id);
}
const Object* Core::ObjectManager::Find(ObjectID id) const
{
return _objects.Find(id);
}
void ObjectManager::DeleteAll()
{
_objects.DeleteAll();
_idBookmark.DeleteAll();
_objIDMgr.DeleteAll();
}
<|endoftext|> |
<commit_before>#include <boost/numeric/odeint.hpp>
#include <aikido/constraint/TestableIntersection.hpp>
#include <aikido/constraint/dart/JointStateSpaceHelpers.hpp>
#include <aikido/planner/vectorfield/MoveEndEffectorOffsetVectorField.hpp>
#include <aikido/planner/vectorfield/MoveEndEffectorPoseVectorField.hpp>
#include <aikido/planner/vectorfield/VectorFieldPlanner.hpp>
#include <aikido/planner/vectorfield/VectorFieldUtil.hpp>
#include <aikido/statespace/dart/MetaSkeletonStateSaver.hpp>
#include <aikido/trajectory/Spline.hpp>
#include "detail/VectorFieldIntegrator.hpp"
#include "detail/VectorFieldPlannerExceptions.hpp"
using aikido::planner::vectorfield::detail::VectorFieldIntegrator;
using aikido::planner::vectorfield::MoveEndEffectorOffsetVectorField;
using aikido::planner::vectorfield::MoveEndEffectorPoseVectorField;
using aikido::statespace::dart::MetaSkeletonStateSaver;
namespace aikido {
namespace planner {
namespace vectorfield {
constexpr double integrationTimeInterval = 10.0;
//==============================================================================
std::unique_ptr<aikido::trajectory::Spline> followVectorField(
const aikido::planner::vectorfield::VectorField& vectorField,
const aikido::statespace::StateSpace::State& startState,
const aikido::constraint::Testable& constraint,
std::chrono::duration<double> timelimit,
double initialStepSize,
double checkConstraintResolution,
planner::Planner::Result* result)
{
using namespace std::placeholders;
using errorStepper = boost::numeric::odeint::
runge_kutta_dopri5<Eigen::VectorXd,
double,
Eigen::VectorXd,
double,
boost::numeric::odeint::vector_space_algebra>;
std::size_t dimension = vectorField.getStateSpace()->getDimension();
auto integrator = std::make_shared<detail::VectorFieldIntegrator>(
&vectorField, &constraint, timelimit.count(), checkConstraintResolution);
integrator->start();
try
{
Eigen::VectorXd initialQ(dimension);
vectorField.getStateSpace()->logMap(&startState, initialQ);
// The current implementation works only in real vector spaces.
// Integrate the vector field to get a configuration space path.
boost::numeric::odeint::integrate_adaptive(
errorStepper(),
std::bind(
&detail::VectorFieldIntegrator::step,
integrator,
std::placeholders::_1,
std::placeholders::_2,
std::placeholders::_3),
initialQ,
0.,
integrationTimeInterval,
initialStepSize,
std::bind(
&detail::VectorFieldIntegrator::check,
integrator,
std::placeholders::_1,
std::placeholders::_2));
}
// VectorFieldTerminated is an exception that is raised internally to
// terminate
// integration, which does not indicate that an error has occurred.
catch (const detail::VectorFieldTerminated& e)
{
if (result)
{
result->setMessage(e.what());
}
}
catch (const detail::VectorFieldError& e)
{
dtwarn << e.what() << std::endl;
if (result)
{
result->setMessage(e.what());
}
return nullptr;
}
if (integrator->getCacheIndex() <= 1)
{
// no enough waypoints cached to make a trajectory output.
if (result)
{
result->setMessage("No segment cached.");
}
return nullptr;
}
std::vector<detail::Knot> newKnots(
integrator->getKnots().begin(),
integrator->getKnots().begin() + integrator->getCacheIndex());
auto outputTrajectory
= detail::convertToSpline(newKnots, vectorField.getStateSpace());
// evaluate constraint satisfaction on last piece of trajectory
double lastEvaluationTime = integrator->getLastEvaluationTime();
if (outputTrajectory->getEndTime() > lastEvaluationTime)
{
if (!vectorField.evaluateTrajectory(
*outputTrajectory,
&constraint,
checkConstraintResolution,
lastEvaluationTime,
true))
{
result->setMessage("Constraint violated.");
return nullptr;
}
}
return outputTrajectory;
}
//==============================================================================
std::unique_ptr<aikido::trajectory::Spline> planToEndEffectorOffset(
const aikido::statespace::dart::ConstMetaSkeletonStateSpacePtr& stateSpace,
const statespace::dart::MetaSkeletonStateSpace::State& startState,
dart::dynamics::MetaSkeletonPtr metaskeleton,
const dart::dynamics::ConstBodyNodePtr& bn,
const aikido::constraint::ConstTestablePtr& constraint,
const Eigen::Vector3d& direction,
double minDistance,
double maxDistance,
double positionTolerance,
double angularTolerance,
double initialStepSize,
double jointLimitTolerance,
double constraintCheckResolution,
std::chrono::duration<double> timelimit,
planner::Planner::Result* result)
{
// ensure that no two planners run at the same time
if (metaskeleton->getNumBodyNodes() == 0)
{
throw std::runtime_error("MetaSkeleton doesn't have any body nodes.");
}
auto robot = metaskeleton->getBodyNode(0)->getSkeleton();
std::lock_guard<std::mutex> lock(robot->getMutex());
// TODO(JS): The above code should be replaced by
// std::lock_guard<std::mutex> lock(metaskeleton->getLockableReference())
// once https://github.com/dartsim/dart/pull/1011 is released.
// TODO: Check compatibility between MetaSkeleton and MetaSkeletonStateSpace
// Save the current state of the space
auto saver = MetaSkeletonStateSaver(
metaskeleton, MetaSkeletonStateSaver::Options::POSITIONS);
DART_UNUSED(saver);
auto vectorfield
= dart::common::make_aligned_shared<MoveEndEffectorOffsetVectorField>(
stateSpace,
metaskeleton,
bn,
direction,
minDistance,
maxDistance,
positionTolerance,
angularTolerance,
initialStepSize,
jointLimitTolerance);
auto compoundConstraint
= std::make_shared<constraint::TestableIntersection>(stateSpace);
compoundConstraint->addConstraint(constraint);
compoundConstraint->addConstraint(
constraint::dart::createTestableBounds(stateSpace));
stateSpace->setState(metaskeleton.get(), &startState);
return followVectorField(
*vectorfield,
startState,
*compoundConstraint,
timelimit,
initialStepSize,
constraintCheckResolution,
result);
}
//==============================================================================
std::unique_ptr<aikido::trajectory::Spline> planToEndEffectorPose(
const aikido::statespace::dart::MetaSkeletonStateSpacePtr& stateSpace,
dart::dynamics::MetaSkeletonPtr metaskeleton,
const dart::dynamics::BodyNodePtr& bn,
const aikido::constraint::TestablePtr& constraint,
const Eigen::Isometry3d& goalPose,
double poseErrorTolerance,
double conversionRatioInGeodesicDistance,
double initialStepSize,
double jointLimitTolerance,
double constraintCheckResolution,
std::chrono::duration<double> timelimit,
planner::Planner::Result* result)
{
// TODO: Check compatibility between MetaSkeleton and MetaSkeletonStateSpace
// Save the current state of the space
auto saver = MetaSkeletonStateSaver(
metaskeleton, MetaSkeletonStateSaver::Options::POSITIONS);
DART_UNUSED(saver);
auto vectorfield
= dart::common::make_aligned_shared<MoveEndEffectorPoseVectorField>(
stateSpace,
metaskeleton,
bn,
goalPose,
poseErrorTolerance,
conversionRatioInGeodesicDistance,
initialStepSize,
jointLimitTolerance);
auto compoundConstraint
= std::make_shared<aikido::constraint::TestableIntersection>(stateSpace);
compoundConstraint->addConstraint(constraint);
compoundConstraint->addConstraint(
constraint::dart::createTestableBounds(stateSpace));
auto startState
= stateSpace->getScopedStateFromMetaSkeleton(metaskeleton.get());
return followVectorField(
*vectorfield,
*startState,
*compoundConstraint,
timelimit,
initialStepSize,
constraintCheckResolution,
result);
}
} // namespace vectorfield
} // namespace planner
} // namespace aikido
<commit_msg>Set start state to state space before creating vector field (#456)<commit_after>#include <boost/numeric/odeint.hpp>
#include <aikido/constraint/TestableIntersection.hpp>
#include <aikido/constraint/dart/JointStateSpaceHelpers.hpp>
#include <aikido/planner/vectorfield/MoveEndEffectorOffsetVectorField.hpp>
#include <aikido/planner/vectorfield/MoveEndEffectorPoseVectorField.hpp>
#include <aikido/planner/vectorfield/VectorFieldPlanner.hpp>
#include <aikido/planner/vectorfield/VectorFieldUtil.hpp>
#include <aikido/statespace/dart/MetaSkeletonStateSaver.hpp>
#include <aikido/trajectory/Spline.hpp>
#include "detail/VectorFieldIntegrator.hpp"
#include "detail/VectorFieldPlannerExceptions.hpp"
using aikido::planner::vectorfield::detail::VectorFieldIntegrator;
using aikido::planner::vectorfield::MoveEndEffectorOffsetVectorField;
using aikido::planner::vectorfield::MoveEndEffectorPoseVectorField;
using aikido::statespace::dart::MetaSkeletonStateSaver;
namespace aikido {
namespace planner {
namespace vectorfield {
constexpr double integrationTimeInterval = 10.0;
//==============================================================================
std::unique_ptr<aikido::trajectory::Spline> followVectorField(
const aikido::planner::vectorfield::VectorField& vectorField,
const aikido::statespace::StateSpace::State& startState,
const aikido::constraint::Testable& constraint,
std::chrono::duration<double> timelimit,
double initialStepSize,
double checkConstraintResolution,
planner::Planner::Result* result)
{
using namespace std::placeholders;
using errorStepper = boost::numeric::odeint::
runge_kutta_dopri5<Eigen::VectorXd,
double,
Eigen::VectorXd,
double,
boost::numeric::odeint::vector_space_algebra>;
std::size_t dimension = vectorField.getStateSpace()->getDimension();
auto integrator = std::make_shared<detail::VectorFieldIntegrator>(
&vectorField, &constraint, timelimit.count(), checkConstraintResolution);
integrator->start();
try
{
Eigen::VectorXd initialQ(dimension);
vectorField.getStateSpace()->logMap(&startState, initialQ);
// The current implementation works only in real vector spaces.
// Integrate the vector field to get a configuration space path.
boost::numeric::odeint::integrate_adaptive(
errorStepper(),
std::bind(
&detail::VectorFieldIntegrator::step,
integrator,
std::placeholders::_1,
std::placeholders::_2,
std::placeholders::_3),
initialQ,
0.,
integrationTimeInterval,
initialStepSize,
std::bind(
&detail::VectorFieldIntegrator::check,
integrator,
std::placeholders::_1,
std::placeholders::_2));
}
// VectorFieldTerminated is an exception that is raised internally to
// terminate
// integration, which does not indicate that an error has occurred.
catch (const detail::VectorFieldTerminated& e)
{
if (result)
{
result->setMessage(e.what());
}
}
catch (const detail::VectorFieldError& e)
{
dtwarn << e.what() << std::endl;
if (result)
{
result->setMessage(e.what());
}
return nullptr;
}
if (integrator->getCacheIndex() <= 1)
{
// no enough waypoints cached to make a trajectory output.
if (result)
{
result->setMessage("No segment cached.");
}
return nullptr;
}
std::vector<detail::Knot> newKnots(
integrator->getKnots().begin(),
integrator->getKnots().begin() + integrator->getCacheIndex());
auto outputTrajectory
= detail::convertToSpline(newKnots, vectorField.getStateSpace());
// evaluate constraint satisfaction on last piece of trajectory
double lastEvaluationTime = integrator->getLastEvaluationTime();
if (outputTrajectory->getEndTime() > lastEvaluationTime)
{
if (!vectorField.evaluateTrajectory(
*outputTrajectory,
&constraint,
checkConstraintResolution,
lastEvaluationTime,
true))
{
result->setMessage("Constraint violated.");
return nullptr;
}
}
return outputTrajectory;
}
//==============================================================================
std::unique_ptr<aikido::trajectory::Spline> planToEndEffectorOffset(
const aikido::statespace::dart::ConstMetaSkeletonStateSpacePtr& stateSpace,
const statespace::dart::MetaSkeletonStateSpace::State& startState,
dart::dynamics::MetaSkeletonPtr metaskeleton,
const dart::dynamics::ConstBodyNodePtr& bn,
const aikido::constraint::ConstTestablePtr& constraint,
const Eigen::Vector3d& direction,
double minDistance,
double maxDistance,
double positionTolerance,
double angularTolerance,
double initialStepSize,
double jointLimitTolerance,
double constraintCheckResolution,
std::chrono::duration<double> timelimit,
planner::Planner::Result* result)
{
// ensure that no two planners run at the same time
if (metaskeleton->getNumBodyNodes() == 0)
{
throw std::runtime_error("MetaSkeleton doesn't have any body nodes.");
}
auto robot = metaskeleton->getBodyNode(0)->getSkeleton();
std::lock_guard<std::mutex> lock(robot->getMutex());
// TODO(JS): The above code should be replaced by
// std::lock_guard<std::mutex> lock(metaskeleton->getLockableReference())
// once https://github.com/dartsim/dart/pull/1011 is released.
// TODO: Check compatibility between MetaSkeleton and MetaSkeletonStateSpace
// Save the current state of the space
auto saver = MetaSkeletonStateSaver(
metaskeleton, MetaSkeletonStateSaver::Options::POSITIONS);
DART_UNUSED(saver);
stateSpace->setState(metaskeleton.get(), &startState);
auto vectorfield
= dart::common::make_aligned_shared<MoveEndEffectorOffsetVectorField>(
stateSpace,
metaskeleton,
bn,
direction,
minDistance,
maxDistance,
positionTolerance,
angularTolerance,
initialStepSize,
jointLimitTolerance);
auto compoundConstraint
= std::make_shared<constraint::TestableIntersection>(stateSpace);
compoundConstraint->addConstraint(constraint);
compoundConstraint->addConstraint(
constraint::dart::createTestableBounds(stateSpace));
return followVectorField(
*vectorfield,
startState,
*compoundConstraint,
timelimit,
initialStepSize,
constraintCheckResolution,
result);
}
//==============================================================================
std::unique_ptr<aikido::trajectory::Spline> planToEndEffectorPose(
const aikido::statespace::dart::MetaSkeletonStateSpacePtr& stateSpace,
dart::dynamics::MetaSkeletonPtr metaskeleton,
const dart::dynamics::BodyNodePtr& bn,
const aikido::constraint::TestablePtr& constraint,
const Eigen::Isometry3d& goalPose,
double poseErrorTolerance,
double conversionRatioInGeodesicDistance,
double initialStepSize,
double jointLimitTolerance,
double constraintCheckResolution,
std::chrono::duration<double> timelimit,
planner::Planner::Result* result)
{
// TODO: Check compatibility between MetaSkeleton and MetaSkeletonStateSpace
// Save the current state of the space
auto saver = MetaSkeletonStateSaver(
metaskeleton, MetaSkeletonStateSaver::Options::POSITIONS);
DART_UNUSED(saver);
auto vectorfield
= dart::common::make_aligned_shared<MoveEndEffectorPoseVectorField>(
stateSpace,
metaskeleton,
bn,
goalPose,
poseErrorTolerance,
conversionRatioInGeodesicDistance,
initialStepSize,
jointLimitTolerance);
auto compoundConstraint
= std::make_shared<aikido::constraint::TestableIntersection>(stateSpace);
compoundConstraint->addConstraint(constraint);
compoundConstraint->addConstraint(
constraint::dart::createTestableBounds(stateSpace));
auto startState
= stateSpace->getScopedStateFromMetaSkeleton(metaskeleton.get());
return followVectorField(
*vectorfield,
*startState,
*compoundConstraint,
timelimit,
initialStepSize,
constraintCheckResolution,
result);
}
} // namespace vectorfield
} // namespace planner
} // namespace aikido
<|endoftext|> |
<commit_before>#include <pd_view.h>
#include <pd_backend.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <list>
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct Breakpoint
{
char* filename;
int line;
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct BreakpointsData
{
std::list<Breakpoint*> breakpoints;
int temp;
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void* createInstance(PDUI* uiFuncs, ServiceFunc* serviceFunc)
{
(void)serviceFunc;
BreakpointsData* userData = new BreakpointsData;
(void)uiFuncs;
(void)serviceFunc;
return userData;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void destroyInstance(void* userData)
{
BreakpointsData* data = (BreakpointsData*)userData;
delete data;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void toogleBreakpoint(BreakpointsData* data, PDReader* reader)
{
const char* filename;
uint32_t line;
PDRead_findString(reader, &filename, "filename", 0);
PDRead_findU32(reader, &line, "line", 0);
for (auto i = data->breakpoints.begin(), end = data->breakpoints.end(); i != end; ++i)
{
if ((*i)->line == (int)line && !strcmp((*i)->filename, filename))
{
free((*i)->filename);
data->breakpoints.erase(i);
return;
}
}
Breakpoint* breakpoint = (Breakpoint*)malloc(sizeof(Breakpoint));
breakpoint->filename = strdup(filename);
breakpoint->line = (int)line;
data->breakpoints.push_back(breakpoint);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static int update(void* userData, PDUI* uiFuncs, PDReader* inEvents, PDWriter* writer)
{
uint32_t event;
(void)uiFuncs;
(void)writer;
BreakpointsData* data = (BreakpointsData*)userData;
while ((event = PDRead_getEvent(inEvents)) != 0)
{
switch (event)
{
case PDEventType_setBreakpoint:
{
toogleBreakpoint(data, inEvents);
break;
}
}
}
uiFuncs->text("");
uiFuncs->columns(2, "callstack", true);
uiFuncs->text("File"); uiFuncs->nextColumn();
uiFuncs->text("Line"); uiFuncs->nextColumn();
for (auto& i : data->breakpoints)
{
uiFuncs->text(i->filename); uiFuncs->nextColumn();
uiFuncs->text("%d", i->line); uiFuncs->nextColumn();
}
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static PDViewPlugin plugin =
{
"Breakpoint View",
createInstance,
destroyInstance,
update,
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
extern "C"
{
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PD_EXPORT void InitPlugin(RegisterPlugin* registerPlugin, void* privateData)
{
registerPlugin(PD_VIEW_API_VERSION, &plugin, privateData);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
<commit_msg>WIP on breakpoint support<commit_after>#include <pd_view.h>
#include <pd_backend.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <list>
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct Location
{
char* filename;
char address[64];
int line;
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct Breakpoint
{
Location location;
char* condition;
bool enabled;
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct BreakpointsData
{
std::list<Breakpoint*> breakpoints;
int addressSize;
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void* createInstance(PDUI* uiFuncs, ServiceFunc* serviceFunc)
{
(void)serviceFunc;
BreakpointsData* userData = new BreakpointsData;
(void)uiFuncs;
(void)serviceFunc;
return userData;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void destroyInstance(void* userData)
{
BreakpointsData* data = (BreakpointsData*)userData;
delete data;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void updateCondition(Breakpoint* bp, PDReader* reader)
{
const char* condition;
bp->condition = 0;
PDRead_findString(reader, &condition, "condition", 0);
if (condition)
bp->condition = strdup(condition);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void toogleBreakpointFileLine(BreakpointsData* data, PDReader* reader)
{
const char* filename;
uint32_t line;
PDRead_findString(reader, &filename, "filename", 0);
PDRead_findU32(reader, &line, "line", 0);
if (!filename)
return;
for (auto i = data->breakpoints.begin(); i != data->breakpoints.end(); ++i)
{
if ((*i)->location.line == (int)line && !strcmp((*i)->location.filename, filename))
{
free((*i)->location.filename);
free((*i)->condition);
free(*i);
data->breakpoints.erase(i);
return;
}
}
Breakpoint* breakpoint = (Breakpoint*)malloc(sizeof(Breakpoint));
memset(breakpoint, 0, sizeof(Breakpoint));
breakpoint->location.filename = strdup(filename);
breakpoint->location.line = (int)line;
breakpoint->enabled = true;
updateCondition(breakpoint, reader);
data->breakpoints.push_back(breakpoint);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
void toggleBreakpointAddress(BreakpointsData* data, PDReader* reader)
{
uint64_t address;
if (PDRead_findU64(reader, &address, "address", 0) == PDReadStatus_notFound)
return;
for (auto i = data->breakpoints.begin(); i != data->breakpoints.end(); ++i)
{
if ((*i)->location.address == address)
{
free(*i);
data->breakpoints.erase(i);
return;
}
}
Breakpoint* breakpoint = (Breakpoint*)malloc(sizeof(Breakpoint));
memset(breakpoint, 0, sizeof(Breakpoint));
breakpoint->location.address = address;
breakpoint->enabled = true;
updateCondition(breakpoint, reader);
data->breakpoints.push_back(breakpoint);
}
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static int update(void* userData, PDUI* uiFuncs, PDReader* inEvents, PDWriter* writer)
{
uint32_t event;
(void)uiFuncs;
(void)writer;
BreakpointsData* data = (BreakpointsData*)userData;
while ((event = PDRead_getEvent(inEvents)) != 0)
{
switch (event)
{
case PDEventType_setBreakpoint:
{
toogleBreakpointFileLine(data, inEvents);
break;
}
}
}
uiFuncs->text("");
uiFuncs->columns(3, "", true);
uiFuncs->text("Name"); uiFuncs->nextColumn();
uiFuncs->text("Condition"); uiFuncs->nextColumn();
for (auto& i : data->breakpoints)
{
Breakpoint* bp = i;
//if (bp->location.filename)
{
uiFuncs->text("%s:%d", bp->location.filename, bp->location.line); uiFuncs->nextColumn();
}
//else
//{
// }
//uiFuncs->text(->locationfilename); uiFuncs->nextColumn();
uiFuncs->text("");
}
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static PDViewPlugin plugin =
{
"Breakpoint View",
createInstance,
destroyInstance,
update,
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
extern "C"
{
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PD_EXPORT void InitPlugin(RegisterPlugin* registerPlugin, void* privateData)
{
registerPlugin(PD_VIEW_API_VERSION, &plugin, privateData);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
<|endoftext|> |
<commit_before>#include <possumwood_sdk/node_implementation.h>
#define EIGEN_STACK_ALLOCATION_LIMIT 0
#include <mutex>
#include <opencv2/opencv.hpp>
#include <Eigen/Sparse>
#include <tbb/task_group.h>
#include <actions/traits.h>
#include "frame.h"
namespace {
class Triplets;
class Row {
public:
Row() = default;
void addValue(int64_t row, int64_t col, double value) {
if(value != 0.0)
m_values[(row << 32) + col] += value;
}
private:
Row(const Row&) = delete;
Row& operator = (const Row&) = delete;
std::map<int64_t, double> m_values;
friend class Triplets;
};
class Triplets {
public:
Triplets(int rows, int cols) : m_rowCount(0), m_rows(rows), m_cols(cols) {
}
void addRow(const Row& r) {
for(auto& v : r.m_values) {
int32_t row = v.first >> 32;
int32_t col = v.first & 0xffffffff;
assert(row < m_rows);
assert(col < m_cols);
m_triplets.push_back(Eigen::Triplet<double>(m_rowCount, row*m_cols + col, v.second));
}
++m_rowCount;
}
std::size_t rows() const {
return m_rowCount;
}
const std::vector<Eigen::Triplet<double>>& triplets() const {
return m_triplets;
}
private:
std::vector<Eigen::Triplet<double>> m_triplets;
int m_rowCount, m_rows, m_cols;
friend class Row;
};
static const cv::Mat kernel = (cv::Mat_<double>(3,3) <<
0.0, -1.0, 0.0,
-1.0, 4.0, -1.0,
0.0, -1.0, 0.0
);
// static const cv::Mat kernel = (cv::Mat_<double>(3,3) <<
// -1.0, -1.0, -1.0,
// -1.0, 8.0, -1.0,
// -1.0, -1.0, -1.0
// );
// static const cv::Mat kernel = (cv::Mat_<double>(3,3) <<
// -1.0, -2.0, -1.0,
// -2.0, 12.0, -2.0,
// -1.0, -2.0, -1.0
// );
// static const cv::Mat kernel = (cv::Mat_<double>(5,5) <<
// 0.0, 0.0, 1.0, 0.0, 0.0,
// 0.0, 2.0, -8.0, 2.0, 0.0,
// 1.0, -8.0, 20.0, -8.0, 1.0,
// 0.0, 2.0, -8.0, 2.0, 0.0,
// 0.0, 0.0, 1.0, 0.0, 0.0
// );
float buildMatrices(const cv::Mat& image, const cv::Mat& mask, Eigen::SparseMatrix<double>& A, Eigen::VectorXd& b, const cv::Rect2i& roi) {
Triplets triplets(image.rows, image.cols);
std::vector<double> values;
std::size_t validCtr = 0, interpolatedCtr = 0;
for(int y=0;y<image.rows;++y)
for(int x=0;x<image.cols;++x) {
Row row;
// masked and/or edge
if(mask.at<unsigned char>(y, x) > 128) {
values.push_back(0.0f);
// convolution
for(int yi=0; yi<kernel.rows; ++yi)
for(int xi=0; xi<kernel.cols; ++xi) {
int ypos = y + yi - kernel.rows/2;
int xpos = x + xi - kernel.cols/2;
// handling of edges - "clip" (or "mirror", commented out for now)
if(ypos < 0)
// ypos = -ypos;
ypos = 0;
if(ypos >= image.rows)
// ypos = (image.rows-1) - (ypos-image.rows);
ypos = image.rows-1;
if(xpos < 0)
// xpos = -xpos;
xpos = 0;
if(xpos >= image.cols)
// xpos = (image.cols-1) - (xpos-image.cols);
xpos = image.cols-1;
row.addValue(ypos, xpos, kernel.at<double>(yi, xi));
}
++interpolatedCtr;
}
// non-masked
if(mask.at<unsigned char>(y, x) <= 128) {
values.push_back(image.at<float>(y, x));
row.addValue(y, x, 1);
++validCtr;
}
triplets.addRow(row);
}
// initialise the sparse matrix
A = Eigen::SparseMatrix<double>(triplets.rows(), image.rows * image.cols);
A.setFromTriplets(triplets.triplets().begin(), triplets.triplets().end());
// and the "b" vector
assert(values.size() == triplets.rows());
b = Eigen::VectorXd(values.size());
for(std::size_t i=0; i<values.size(); ++i)
b[i] = values[i];
return (float)validCtr / ((float)validCtr + (float)interpolatedCtr);
}
dependency_graph::InAttr<possumwood::opencv::Frame> a_inFrame, a_inMask;
dependency_graph::InAttr<unsigned> a_mosaic;
dependency_graph::OutAttr<possumwood::opencv::Frame> a_outFrame;
dependency_graph::State compute(dependency_graph::Values& data) {
dependency_graph::State state;
const cv::Mat& input = *data.get(a_inFrame);
const cv::Mat& mask = *data.get(a_inMask);
const unsigned mosaic = data.get(a_mosaic);
if(input.depth() != CV_32F)
throw std::runtime_error("Laplacian inpainting - input image type has to be CV_32F.");
if(mask.type() != CV_8UC1 && mask.type() != CV_8UC3)
throw std::runtime_error("Laplacian inpainting - mask image type has to be CV_8UC1 or CV_8UC3.");
if(input.empty() || mask.empty())
throw std::runtime_error("Laplacian inpainting - empty input image and/or mask.");
if(input.size != mask.size)
throw std::runtime_error("Laplacian inpainting - input and mask image size have to match.");
std::vector<std::vector<float>> x(input.channels(), std::vector<float>(input.rows * input.cols, 0.0f));
tbb::task_group tasks;
std::mutex solve_mutex;
// split the inputs and masks per channel
std::vector<cv::Mat> inputs, masks;
cv::split(input, inputs);
cv::split(mask, masks);
assert((int)inputs.size() == input.channels());
assert((int)masks.size() == mask.channels());
for(unsigned a=0;a<mosaic; ++a) {
for(unsigned b=0;b<mosaic; ++b) {
cv::Rect2i roi;
roi.y = (a * input.rows) / mosaic;
roi.x = (b * input.cols) / mosaic;
roi.height = ((a+1) * input.rows) / mosaic - roi.y;
roi.width = ((b+1) * input.cols) / mosaic - roi.x;
for(int channel=0; channel<input.channels(); ++channel) {
tasks.run([channel, &inputs, &masks, &x, &state, &solve_mutex, roi]() {
cv::Mat inTile = inputs[channel](roi);
cv::Mat inMask;
if(masks.size() == 1)
inMask = masks[0](roi);
else
inMask = masks[channel](roi);
Eigen::SparseMatrix<double> A;
Eigen::VectorXd b, tmp;
const float ratio = buildMatrices(inTile, inMask, A, b, roi);
if(ratio > 0.003) {
const char* stage = "solver construction";
Eigen::SparseLU<Eigen::SparseMatrix<double> /*, Eigen::NaturalOrdering<int>*/ > chol(A);
if(chol.info() == Eigen::Success) {
stage = "analyze pattern";
chol.analyzePattern(A);
if(chol.info() == Eigen::Success) {
stage = "factorize";
chol.factorize(A);
if(chol.info() == Eigen::Success) {
stage = "solve";
tmp = chol.solve(b);
assert(tmp.size() == inTile.rows * inTile.cols);
for(int i=0;i<tmp.size();++i) {
const int row = i / roi.width;
const int col = i % roi.width;
const int index = (row + roi.y) * masks[0].cols + col + roi.x;
assert((std::size_t)index < x[channel].size());
x[channel][index] = tmp[i];
}
}
}
}
std::lock_guard<std::mutex> guard(solve_mutex);
if(chol.info() == Eigen::NumericalIssue)
state.addWarning("Decomposition failed - Eigen::NumericalIssue at stage " + std::string(stage));
else if(chol.info() == Eigen::NoConvergence)
state.addWarning("Decomposition failed - Eigen::NoConvergence at stage " + std::string(stage));
else if(chol.info() == Eigen::InvalidInput)
state.addWarning("Decomposition failed - Eigen::InvalidInput at stage " + std::string(stage));
else if(chol.info() != Eigen::Success)
state.addWarning("Decomposition failed - unknown error at stage " + std::string(stage));
}
});
}
}
}
tasks.wait();
cv::Mat result = input.clone();
for(int yi=0;yi<result.rows;++yi)
for(int xi=0;xi<result.cols;++xi)
for(int c=0;c<input.channels();++c)
result.ptr<float>(yi, xi)[c] = x[c][yi*result.cols + xi];
data.set(a_outFrame, possumwood::opencv::Frame(result));
return state;
}
void init(possumwood::Metadata& meta) {
meta.addAttribute(a_inFrame, "frame", possumwood::opencv::Frame(), possumwood::AttrFlags::kVertical);
meta.addAttribute(a_inMask, "mask", possumwood::opencv::Frame(), possumwood::AttrFlags::kVertical);
meta.addAttribute(a_mosaic, "mosaic", 1u);
meta.addAttribute(a_outFrame, "out_frame", possumwood::opencv::Frame(), possumwood::AttrFlags::kVertical);
meta.addInfluence(a_inFrame, a_outFrame);
meta.addInfluence(a_inMask, a_outFrame);
meta.addInfluence(a_mosaic, a_outFrame);
meta.setCompute(compute);
}
possumwood::NodeImplementation s_impl("opencv/inpaint_laplacian", init);
}
<commit_msg>Explicit handling of the region of interest inside buildMatrices of laplacian inpainting<commit_after>#include <possumwood_sdk/node_implementation.h>
#define EIGEN_STACK_ALLOCATION_LIMIT 0
#include <mutex>
#include <opencv2/opencv.hpp>
#include <Eigen/Sparse>
#include <tbb/task_group.h>
#include <actions/traits.h>
#include "frame.h"
namespace {
class Triplets;
class Row {
public:
Row() = default;
void addValue(int64_t row, int64_t col, double value) {
if(value != 0.0)
m_values[(row << 32) + col] += value;
}
private:
Row(const Row&) = delete;
Row& operator = (const Row&) = delete;
std::map<int64_t, double> m_values;
friend class Triplets;
};
class Triplets {
public:
Triplets(int rows, int cols) : m_rowCount(0), m_rows(rows), m_cols(cols) {
}
void addRow(const Row& r) {
for(auto& v : r.m_values) {
int32_t row = v.first >> 32;
int32_t col = v.first & 0xffffffff;
assert(row < m_rows);
assert(col < m_cols);
m_triplets.push_back(Eigen::Triplet<double>(m_rowCount, row*m_cols + col, v.second));
}
++m_rowCount;
}
std::size_t rows() const {
return m_rowCount;
}
const std::vector<Eigen::Triplet<double>>& triplets() const {
return m_triplets;
}
private:
std::vector<Eigen::Triplet<double>> m_triplets;
int m_rowCount, m_rows, m_cols;
friend class Row;
};
static const cv::Mat kernel = (cv::Mat_<double>(3,3) <<
0.0, -1.0, 0.0,
-1.0, 4.0, -1.0,
0.0, -1.0, 0.0
);
// static const cv::Mat kernel = (cv::Mat_<double>(3,3) <<
// -1.0, -1.0, -1.0,
// -1.0, 8.0, -1.0,
// -1.0, -1.0, -1.0
// );
// static const cv::Mat kernel = (cv::Mat_<double>(3,3) <<
// -1.0, -2.0, -1.0,
// -2.0, 12.0, -2.0,
// -1.0, -2.0, -1.0
// );
// static const cv::Mat kernel = (cv::Mat_<double>(5,5) <<
// 0.0, 0.0, 1.0, 0.0, 0.0,
// 0.0, 2.0, -8.0, 2.0, 0.0,
// 1.0, -8.0, 20.0, -8.0, 1.0,
// 0.0, 2.0, -8.0, 2.0, 0.0,
// 0.0, 0.0, 1.0, 0.0, 0.0
// );
float buildMatrices(const cv::Mat& image, const cv::Mat& mask, Eigen::SparseMatrix<double>& A, Eigen::VectorXd& b, const cv::Rect2i& roi) {
Triplets triplets(roi.height, roi.width);
std::vector<double> values;
std::size_t validCtr = 0, interpolatedCtr = 0;
for(int y=roi.y; y<roi.y+roi.height; ++y)
for(int x=roi.x; x<roi.x+roi.width; ++x) {
Row row;
// masked and/or edge
if(mask.at<unsigned char>(y, x) > 128) {
values.push_back(0.0f);
// convolution
for(int yi=0; yi<kernel.rows; ++yi)
for(int xi=0; xi<kernel.cols; ++xi) {
int ypos = y + yi - kernel.rows/2;
int xpos = x + xi - kernel.cols/2;
// handling of edges - "clip" (or "mirror", commented out for now)
if(ypos < roi.y)
// ypos = -ypos;
ypos = roi.y;
if(ypos >= roi.y + roi.height)
// ypos = (image.rows-1) - (ypos-image.rows);
ypos = roi.y + roi.height - 1;
if(xpos < roi.x)
// xpos = -xpos;
xpos = roi.x;
if(xpos >= roi.x + roi.width)
// xpos = (image.cols-1) - (xpos-image.cols);
xpos = roi.x + roi.width - 1;
row.addValue(ypos - roi.y, xpos - roi.x, kernel.at<double>(yi, xi));
}
++interpolatedCtr;
}
// non-masked
if(mask.at<unsigned char>(y, x) <= 128) {
values.push_back(image.at<float>(y, x));
row.addValue(y-roi.y, x-roi.x, 1);
++validCtr;
}
triplets.addRow(row);
}
// initialise the sparse matrix
A = Eigen::SparseMatrix<double>(triplets.rows(), roi.height * roi.width);
A.setFromTriplets(triplets.triplets().begin(), triplets.triplets().end());
// and the "b" vector
assert(values.size() == triplets.rows());
b = Eigen::VectorXd(values.size());
for(std::size_t i=0; i<values.size(); ++i)
b[i] = values[i];
return (float)validCtr / ((float)validCtr + (float)interpolatedCtr);
}
dependency_graph::InAttr<possumwood::opencv::Frame> a_inFrame, a_inMask;
dependency_graph::InAttr<unsigned> a_mosaic;
dependency_graph::OutAttr<possumwood::opencv::Frame> a_outFrame;
dependency_graph::State compute(dependency_graph::Values& data) {
dependency_graph::State state;
const cv::Mat& input = *data.get(a_inFrame);
const cv::Mat& mask = *data.get(a_inMask);
const unsigned mosaic = data.get(a_mosaic);
if(input.depth() != CV_32F)
throw std::runtime_error("Laplacian inpainting - input image type has to be CV_32F.");
if(mask.type() != CV_8UC1 && mask.type() != CV_8UC3)
throw std::runtime_error("Laplacian inpainting - mask image type has to be CV_8UC1 or CV_8UC3.");
if(input.empty() || mask.empty())
throw std::runtime_error("Laplacian inpainting - empty input image and/or mask.");
if(input.size != mask.size)
throw std::runtime_error("Laplacian inpainting - input and mask image size have to match.");
if(input.cols % mosaic != 0 || input.rows % mosaic != 0)
throw std::runtime_error("Laplacian inpainting - image size is not divisible by mosaic count - invalid mosaic?.");
std::vector<std::vector<float>> x(input.channels(), std::vector<float>(input.rows * input.cols, 0.0f));
tbb::task_group tasks;
std::mutex solve_mutex;
// split the inputs and masks per channel
std::vector<cv::Mat> inputs, masks;
cv::split(input, inputs);
cv::split(mask, masks);
assert((int)inputs.size() == input.channels());
assert((int)masks.size() == mask.channels());
const unsigned mosaic_rows = input.rows / mosaic;
const unsigned mosaic_cols = input.cols / mosaic;
for(unsigned yi=0;yi<mosaic; ++yi) {
for(unsigned xi=0;xi<mosaic; ++xi) {
cv::Rect2i roi;
roi.y = yi * mosaic_rows;
roi.x = xi * mosaic_cols;
roi.height = mosaic_rows;
roi.width = mosaic_cols;
for(int channel=0; channel<input.channels(); ++channel) {
tasks.run([channel, &inputs, &masks, &x, &state, &solve_mutex, roi]() {
cv::Mat inTile = inputs[channel];
cv::Mat inMask;
if(masks.size() == 1)
inMask = masks[0];
else
inMask = masks[channel];
Eigen::SparseMatrix<double> A;
Eigen::VectorXd b, tmp;
const float ratio = buildMatrices(inTile, inMask, A, b, roi);
if(ratio > 0.003) {
const char* stage = "solver construction";
Eigen::SparseLU<Eigen::SparseMatrix<double> /*, Eigen::NaturalOrdering<int>*/ > chol(A);
if(chol.info() == Eigen::Success) {
stage = "analyze pattern";
chol.analyzePattern(A);
if(chol.info() == Eigen::Success) {
stage = "factorize";
chol.factorize(A);
if(chol.info() == Eigen::Success) {
stage = "solve";
tmp = chol.solve(b);
assert(tmp.size() == roi.height * roi.width);
for(int i=0;i<tmp.size();++i) {
const int row = i / roi.width;
const int col = i % roi.width;
const int index = (row + roi.y) * masks[0].cols + col + roi.x;
assert((std::size_t)index < x[channel].size());
x[channel][index] = tmp[i];
}
}
}
}
std::lock_guard<std::mutex> guard(solve_mutex);
if(chol.info() == Eigen::NumericalIssue)
state.addWarning("Decomposition failed - Eigen::NumericalIssue at stage " + std::string(stage));
else if(chol.info() == Eigen::NoConvergence)
state.addWarning("Decomposition failed - Eigen::NoConvergence at stage " + std::string(stage));
else if(chol.info() == Eigen::InvalidInput)
state.addWarning("Decomposition failed - Eigen::InvalidInput at stage " + std::string(stage));
else if(chol.info() != Eigen::Success)
state.addWarning("Decomposition failed - unknown error at stage " + std::string(stage));
}
});
}
}
}
tasks.wait();
cv::Mat result = input.clone();
for(int yi=0;yi<result.rows;++yi)
for(int xi=0;xi<result.cols;++xi)
for(int c=0;c<input.channels();++c)
result.ptr<float>(yi, xi)[c] = x[c][yi*result.cols + xi];
data.set(a_outFrame, possumwood::opencv::Frame(result));
return state;
}
void init(possumwood::Metadata& meta) {
meta.addAttribute(a_inFrame, "frame", possumwood::opencv::Frame(), possumwood::AttrFlags::kVertical);
meta.addAttribute(a_inMask, "mask", possumwood::opencv::Frame(), possumwood::AttrFlags::kVertical);
meta.addAttribute(a_mosaic, "mosaic", 1u);
meta.addAttribute(a_outFrame, "out_frame", possumwood::opencv::Frame(), possumwood::AttrFlags::kVertical);
meta.addInfluence(a_inFrame, a_outFrame);
meta.addInfluence(a_inMask, a_outFrame);
meta.addInfluence(a_mosaic, a_outFrame);
meta.setCompute(compute);
}
possumwood::NodeImplementation s_impl("opencv/inpaint_laplacian", init);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "Serial.h"
#include <Log.h>
X86Serial::X86Serial()
: m_Port("COM")
{
}
X86Serial::~X86Serial()
{
}
void X86Serial::setBase(uintptr_t nBaseAddr)
{
m_Port.allocate(nBaseAddr, 8);
m_Port.write8(0x00, serial::inten); // Disable all interrupts
m_Port.write8(0x80, serial::lctrl); // Enable DLAB (set baud rate divisor)
m_Port.write8(0x03, serial::rxtx); // Set divisor to 3 (lo byte) 38400 baud
m_Port.write8(0x00, serial::inten); // (hi byte)
m_Port.write8(0x03, serial::lctrl); // 8 bits, no parity, one stop bit
m_Port.write8(0xC7, serial::iififo);// Enable FIFO, clear them, with 14-byte threshold
m_Port.write8(0x0B, serial::mctrl); // IRQs enabled, RTS/DSR set
m_Port.write8(0x0C, serial::inten); // enable all interrupts.
NOTICE("Modem status: " << Hex << m_Port.read8(serial::mstat));
NOTICE("Line status: " << Hex << m_Port.read8(serial::lstat));
}
char X86Serial::read()
{
if (!isConnected())
return 0;
while ( !(m_Port.read8(serial::lstat) & 0x1) ) ;
return m_Port.read8(serial::rxtx);
}
char X86Serial::readNonBlock()
{
if (!isConnected())
return 0;
if ( m_Port.read8(serial::lstat) & 0x1)
return m_Port.read8(serial::rxtx);
else
return '\0';
}
void X86Serial::write(char c)
{
if (!isConnected())
return;
while ( !(m_Port.read8(serial::lstat) & 0x20) ) ;
m_Port.write8(static_cast<unsigned char> (c), serial::rxtx);
}
bool X86Serial::isConnected()
{
return true;
uint8_t nStatus = m_Port.read8(serial::mstat);
// Bits 0x30 = Clear to send & Data set ready.
// Mstat seems to be 0xFF when the device isn't present.
if ((nStatus & 0x30) && nStatus != 0xFF)
return true;
else
return false;
}
<commit_msg>x86: serial port now defaults to 115200 baud rather than 38400. Needs to be made configurable!!!<commit_after>/*
* Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "Serial.h"
#include <Log.h>
X86Serial::X86Serial()
: m_Port("COM")
{
}
X86Serial::~X86Serial()
{
}
void X86Serial::setBase(uintptr_t nBaseAddr)
{
m_Port.allocate(nBaseAddr, 8);
m_Port.write8(0x00, serial::inten); // Disable all interrupts
m_Port.write8(0x80, serial::lctrl); // Enable DLAB (set baud rate divisor)
m_Port.write8(0x13, serial::rxtx); // Set divisor to 3 (lo byte) 115200 baud
m_Port.write8(0x00, serial::inten); // (hi byte)
m_Port.write8(0x03, serial::lctrl); // 8 bits, no parity, one stop bit
m_Port.write8(0xC7, serial::iififo);// Enable FIFO, clear them, with 14-byte threshold
m_Port.write8(0x0B, serial::mctrl); // IRQs enabled, RTS/DSR set
m_Port.write8(0x0C, serial::inten); // enable all interrupts.
NOTICE("Modem status: " << Hex << m_Port.read8(serial::mstat));
NOTICE("Line status: " << Hex << m_Port.read8(serial::lstat));
}
char X86Serial::read()
{
if (!isConnected())
return 0;
while ( !(m_Port.read8(serial::lstat) & 0x1) ) ;
return m_Port.read8(serial::rxtx);
}
char X86Serial::readNonBlock()
{
if (!isConnected())
return 0;
if ( m_Port.read8(serial::lstat) & 0x1)
return m_Port.read8(serial::rxtx);
else
return '\0';
}
void X86Serial::write(char c)
{
if (!isConnected())
return;
while ( !(m_Port.read8(serial::lstat) & 0x20) ) ;
m_Port.write8(static_cast<unsigned char> (c), serial::rxtx);
}
bool X86Serial::isConnected()
{
return true;
uint8_t nStatus = m_Port.read8(serial::mstat);
// Bits 0x30 = Clear to send & Data set ready.
// Mstat seems to be 0xFF when the device isn't present.
if ((nStatus & 0x30) && nStatus != 0xFF)
return true;
else
return false;
}
<|endoftext|> |
<commit_before>#define NB_PROFILE \
(sizeof(video_profile_value_list)/sizeof(video_profile_value_list[0]))
static const char *const video_profile_name_list[] = {
"Video - H.264 + AAC (TS)",
"Video - Dirac + AAC (TS)",
"Video - Theora + Vorbis (OGG)",
"Video - Theora + Flac (OGG)",
"Video - MPEG-4 + AAC (MP4)",
"Video - MPEG-2 + MPGA (TS)",
"Video - WMV + WMA (ASF)",
"Video - DIV3 + MP3 (ASF)",
"Audio - Vorbis (OGG)",
"Audio - MP3",
"Audio - AAC (MP4)",
"Audio - FLAC",
};
static const char *const video_profile_value_list[] = {
/* Container(string), transcode video(bool), transcode audio(bool), */
/* use subtitles(bool), video codec(string), video bitrate(integer), */
/* scale(float), fps(float), width(integer, height(integer), */
/* audio codec(string), audio bitrate(integer), channels(integer), */
/* samplerate(integer), subtitle codec(string), subtitle overlay(bool) */
"ts;1;1;0;h264;800;1;0;0;0;mp4a;128;2;44100;0;0",
"ts;1;1;0;drac;800;1;0;0;0;mp4a;128;2;44100;0;0",
"ogg;1;1;0;theo;800;1;0;0;0;vorb;128;2;44100;0;0",
"ogg;1;1;0;theo;800;1;0;0;0;flac;128;2;44100;0;0",
"mp4;1;1;0;mp4v;800;1;0;0;0;mp4a;128;2;44100;0;0",
"ts;1;1;0;mp2v;800;1;0;0;0;mpga;128;2;44100;0;0",
"asf;1;1;0;WMV2;800;1;0;0;0;wma2;128;2;44100;0;0",
"asf;1;1;0;DIV3;800;1;0;0;0;mp3;128;2;44100;0;0",
"ogg;0;1;0;0;800;1;0;0;0;vorb;128;2;44100;0;0",
"raw;0;1;0;0;800;1;0;0;0;mp3;128;2;44100;0;0",
"mp4;0;1;0;0;800;1;0;0;0;mp4a;128;2;44100;0;0",
"raw;0;1;0;0;800;1;0;0;0;flac;128;2;44100;0;0",
};
<commit_msg>Kill a few relocations<commit_after>#define NB_PROFILE \
(sizeof(video_profile_value_list)/sizeof(video_profile_value_list[0]))
static const char video_profile_name_list[][32] = {
"Video - H.264 + AAC (TS)",
"Video - Dirac + AAC (TS)",
"Video - Theora + Vorbis (OGG)",
"Video - Theora + Flac (OGG)",
"Video - MPEG-4 + AAC (MP4)",
"Video - MPEG-2 + MPGA (TS)",
"Video - WMV + WMA (ASF)",
"Video - DIV3 + MP3 (ASF)",
"Audio - Vorbis (OGG)",
"Audio - MP3",
"Audio - AAC (MP4)",
"Audio - FLAC",
};
static const char video_profile_value_list[][48] = {
/* Container(string), transcode video(bool), transcode audio(bool), */
/* use subtitles(bool), video codec(string), video bitrate(integer), */
/* scale(float), fps(float), width(integer, height(integer), */
/* audio codec(string), audio bitrate(integer), channels(integer), */
/* samplerate(integer), subtitle codec(string), subtitle overlay(bool) */
"ts;1;1;0;h264;800;1;0;0;0;mp4a;128;2;44100;0;0",
"ts;1;1;0;drac;800;1;0;0;0;mp4a;128;2;44100;0;0",
"ogg;1;1;0;theo;800;1;0;0;0;vorb;128;2;44100;0;0",
"ogg;1;1;0;theo;800;1;0;0;0;flac;128;2;44100;0;0",
"mp4;1;1;0;mp4v;800;1;0;0;0;mp4a;128;2;44100;0;0",
"ts;1;1;0;mp2v;800;1;0;0;0;mpga;128;2;44100;0;0",
"asf;1;1;0;WMV2;800;1;0;0;0;wma2;128;2;44100;0;0",
"asf;1;1;0;DIV3;800;1;0;0;0;mp3;128;2;44100;0;0",
"ogg;0;1;0;0;800;1;0;0;0;vorb;128;2;44100;0;0",
"raw;0;1;0;0;800;1;0;0;0;mp3;128;2;44100;0;0",
"mp4;0;1;0;0;800;1;0;0;0;mp4a;128;2;44100;0;0",
"raw;0;1;0;0;800;1;0;0;0;flac;128;2;44100;0;0",
};
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/isteps/istep14/call_mss_thermal_init.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2020 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
/**
* @file call_mss_thermal_init.C
*
* @details Run Thermal Sensor Initialization on a set of targets
*
*/
/******************************************************************************/
// Includes
/******************************************************************************/
// Standard headers
#include <stdint.h> // uint32_t
// Trace
#include <trace/interface.H> // TRACFCOMP
#include <initservice/isteps_trace.H> // ISTEPS_TRACE::g_trac_isteps_trace
// Error logging
#include <errl/errlentry.H> // errlHndl_t
#include <isteps/hwpisteperror.H> // IStepError, getErrorHandle
#include <istepHelperFuncs.H> // captureError
// Targeting support
#include <targeting/common/target.H> // TargetHandleList, getAttr
#include <targeting/common/utilFilter.H> // getAllChips
// Fapi
#include <fapi2/target.H> // fapi2::TARGET_TYPE_OCMB_CHIP
#include <fapi2/plat_hwp_invoker.H> // FAPI_INVOKE_HWP
// HWP
#include <exp_mss_thermal_init.H> // exp_mss_thermal_init
#include <p10_throttle_sync.H> // p10_throttle_sync
// Misc
#include <chipids.H> // POWER_CHIPID::EXPLORER_16
/******************************************************************************/
// namespace shortcuts
/******************************************************************************/
using namespace ISTEP;
using namespace ISTEP_ERROR;
using namespace ERRORLOG;
using namespace TARGETING;
namespace ISTEP_14
{
// Forward declare these methods
void p10_call_mss_thermal_init(IStepError & io_iStepError);
void run_proc_throttle_sync(IStepError & io_iStepError);
/**
* @brief Run Thermal Sensor Initialization followed by Process
* Throttle Synchronization on a list of targets
*
* @return nullptr if success, else a handle to an error log
*/
void* call_mss_thermal_init (void*)
{
IStepError l_iStepError;
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
ENTER_MRK"call_mss_thermal_init");
// Call HWP to thermal initialization on a list of OCMB chips
p10_call_mss_thermal_init(l_iStepError);
// Do not continue if the HWP call to thermal initialization encounters an
// error. Breaking out here will facilitate in the efficiency of the
// reconfig loop and not cause confusion for the next HWP call.
if ( !l_iStepError.isNull() )
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, ERR_MRK
"ERROR: call_mss_thermal_init exited early because "
"p10_call_mss_thermal_init had failures" );
}
else
{
// If no prior error, then call HWP to processor throttle
// synchronization on a list of PROC chips
run_proc_throttle_sync(l_iStepError);
}
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
EXIT_MRK"call_mss_thermal_init, returning %s",
(l_iStepError.isNull()? "success" : "failure") );
// end task, returning any errorlogs to IStepDisp
return l_iStepError.getErrorHandle();
} // call_mss_thermal_init
/**
* @brief Run Thermal Sensor Initialization on a list Explorer OCMB chips
*
* param[in/out] io_iStepError - Container for errors if an error occurs
*/
void p10_call_mss_thermal_init(IStepError & io_iStepError)
{
errlHndl_t l_err(nullptr);
// Get a list of all OCMB chips to run Thermal Sensor Initialization on
TARGETING::TargetHandleList l_ocmbTargetList;
getAllChips(l_ocmbTargetList, TYPE_OCMB_CHIP);
for (const auto & l_ocmbTarget : l_ocmbTargetList)
{
// Only run Thermal Sensor Initialization (exp_mss_thermal_init)
// on Explorer OCMBs.
uint32_t l_chipId = l_ocmbTarget->getAttr<TARGETING::ATTR_CHIP_ID>();
if (l_chipId == POWER_CHIPID::EXPLORER_16)
{
// Convert the TARGETING::Target into a fapi2::Target by passing
// l_ocmbTarget into the fapi2::Target constructor
fapi2::Target <fapi2::TARGET_TYPE_OCMB_CHIP>
l_fapiOcmbTarget ( l_ocmbTarget );
// Calling exp_mss_thermal_init HWP on Explorer chip,
// trace out stating so
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, INFO_MRK
"Running exp_mss_thermal_init HWP call on Explorer "
"chip, target HUID 0x%.8X, chipId 0x%.8X",
TARGETING::get_huid(l_ocmbTarget),
l_chipId );
// Call the HWP exp_mss_thermal_init call on each fapi2::Target
FAPI_INVOKE_HWP(l_err, exp_mss_thermal_init, l_fapiOcmbTarget);
if (l_err)
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, ERR_MRK
"ERROR: exp_mss_thermal_init HWP call on Explorer "
"chip, target HUID 0x%08x, chipId 0x%.8X failed."
TRACE_ERR_FMT,
get_huid(l_ocmbTarget),
l_chipId,
TRACE_ERR_ARGS(l_err) );
// Capture error, commit and continue, do not break out here.
// Continue here and consolidate all the errors that might
// occur in a batch before bailing. This will facilitate in the
// efficiency of the reconfig loop.
captureError(l_err, io_iStepError, HWPF_COMP_ID, l_ocmbTarget);
}
else
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, INFO_MRK
"SUCCESS: exp_mss_thermal_init HWP on Explorer "
"chip, target HUID 0x%.8X, chipId 0x%.8X",
TARGETING::get_huid(l_ocmbTarget),
l_chipId );
}
} // end if (l_chipId == POWER_CHIPID::EXPLORER_16)
else
{
// Non-Explorer chip, a NOOP operation, trace out stating so
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, INFO_MRK
"Skipping call to exp_mss_thermal_init HWP on target "
"HUID 0x%.8X, chipId 0x%.8X is not an Explorer OCMB",
TARGETING::get_huid(l_ocmbTarget),
l_chipId );
}
} // end for (const auto & l_ocmbTarget : l_ocmbTargetList)
} // p10_call_mss_thermal_init
/**
* @brief Run Processor Throttle Synchronization on all functional
* Processor Chip targets
*
* param[in/out] io_iStepError - Container for errors if an error occurs
*
*/
void run_proc_throttle_sync(IStepError & io_iStepError)
{
errlHndl_t l_err(nullptr);
// Get a list of all processors to run Throttle Synchronization on
TARGETING::TargetHandleList l_procChips;
getAllChips( l_procChips, TARGETING::TYPE_PROC );
for (const auto & l_procChip: l_procChips)
{
// Convert the TARGETING::Target into a fapi2::Target by passing
// l_procChip into the fapi2::Target constructor
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>
l_fapiProcTarget(l_procChip);
// Calling p10_throttle_sync HWP on PROC chip, trace out stating so
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, INFO_MRK
"Running p10_throttle_sync HWP on PROC target HUID 0x%.8X",
TARGETING::get_huid(l_procChip) );
// Call the HWP p10_throttle_sync call on each fapi2::Target
FAPI_INVOKE_HWP( l_err, p10_throttle_sync, l_fapiProcTarget );
if (l_err)
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, ERR_MRK
"ERROR: p10_throttle_sync HWP call on PROC target "
"HUID 0x%08x failed."
TRACE_ERR_FMT,
get_huid(l_procChip),
TRACE_ERR_ARGS(l_err) );
// Capture error, commit and continue, do not break out here.
// Continue here and consolidate all the errors that might
// occur in a batch before bailing. This will facilitate in the
// efficiency of the reconfig loop.
captureError(l_err, io_iStepError, HWPF_COMP_ID, l_procChip);
}
else
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, INFO_MRK
"SUCCESS : p10_throttle_sync HWP call on "
"PROC target HUID 0x%08x",
TARGETING::get_huid(l_procChip) );
}
}
} // run_proc_throttle_sync
}; // namespace ISTEP_14
<commit_msg>Make exp_mss_thermal_init errors non-fatal<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/isteps/istep14/call_mss_thermal_init.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2021 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
/**
* @file call_mss_thermal_init.C
*
* @details Run Thermal Sensor Initialization on a set of targets
*
*/
/******************************************************************************/
// Includes
/******************************************************************************/
// Standard headers
#include <stdint.h> // uint32_t
// Trace
#include <trace/interface.H> // TRACFCOMP
#include <initservice/isteps_trace.H> // ISTEPS_TRACE::g_trac_isteps_trace
// Error logging
#include <errl/errlentry.H> // errlHndl_t
#include <isteps/hwpisteperror.H> // IStepError, getErrorHandle
#include <istepHelperFuncs.H> // captureError
// Targeting support
#include <targeting/common/target.H> // TargetHandleList, getAttr
#include <targeting/common/utilFilter.H> // getAllChips
// Fapi
#include <fapi2/target.H> // fapi2::TARGET_TYPE_OCMB_CHIP
#include <fapi2/plat_hwp_invoker.H> // FAPI_INVOKE_HWP
// HWP
#include <exp_mss_thermal_init.H> // exp_mss_thermal_init
#include <p10_throttle_sync.H> // p10_throttle_sync
// Misc
#include <chipids.H> // POWER_CHIPID::EXPLORER_16
/******************************************************************************/
// namespace shortcuts
/******************************************************************************/
using namespace ISTEP;
using namespace ISTEP_ERROR;
using namespace ERRORLOG;
using namespace TARGETING;
namespace ISTEP_14
{
// Forward declare these methods
void p10_call_mss_thermal_init(IStepError & io_iStepError);
void run_proc_throttle_sync(IStepError & io_iStepError);
/**
* @brief Run Thermal Sensor Initialization followed by Process
* Throttle Synchronization on a list of targets
*
* @return nullptr if success, else a handle to an error log
*/
void* call_mss_thermal_init (void*)
{
IStepError l_iStepError;
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
ENTER_MRK"call_mss_thermal_init");
// Call HWP to thermal initialization on a list of OCMB chips
p10_call_mss_thermal_init(l_iStepError);
// Do not continue if the HWP call to thermal initialization encounters an
// error. Breaking out here will facilitate in the efficiency of the
// reconfig loop and not cause confusion for the next HWP call.
if ( !l_iStepError.isNull() )
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, ERR_MRK
"ERROR: call_mss_thermal_init exited early because "
"p10_call_mss_thermal_init had failures" );
}
else
{
// If no prior error, then call HWP to processor throttle
// synchronization on a list of PROC chips
run_proc_throttle_sync(l_iStepError);
}
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
EXIT_MRK"call_mss_thermal_init, returning %s",
(l_iStepError.isNull()? "success" : "failure") );
// end task, returning any errorlogs to IStepDisp
return l_iStepError.getErrorHandle();
} // call_mss_thermal_init
/**
* @brief Run Thermal Sensor Initialization on a list Explorer OCMB chips
*
* param[in/out] io_iStepError - Container for errors if an error occurs
*/
void p10_call_mss_thermal_init(IStepError & io_iStepError)
{
errlHndl_t l_err(nullptr);
// Get a list of all OCMB chips to run Thermal Sensor Initialization on
TARGETING::TargetHandleList l_ocmbTargetList;
getAllChips(l_ocmbTargetList, TYPE_OCMB_CHIP);
for (const auto & l_ocmbTarget : l_ocmbTargetList)
{
// Only run Thermal Sensor Initialization (exp_mss_thermal_init)
// on Explorer OCMBs.
uint32_t l_chipId = l_ocmbTarget->getAttr<TARGETING::ATTR_CHIP_ID>();
if (l_chipId == POWER_CHIPID::EXPLORER_16)
{
// Convert the TARGETING::Target into a fapi2::Target by passing
// l_ocmbTarget into the fapi2::Target constructor
fapi2::Target <fapi2::TARGET_TYPE_OCMB_CHIP>
l_fapiOcmbTarget ( l_ocmbTarget );
// Calling exp_mss_thermal_init HWP on Explorer chip,
// trace out stating so
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, INFO_MRK
"Running exp_mss_thermal_init HWP call on Explorer "
"chip, target HUID 0x%.8X, chipId 0x%.8X",
TARGETING::get_huid(l_ocmbTarget),
l_chipId );
// Call the HWP exp_mss_thermal_init call on each fapi2::Target
FAPI_INVOKE_HWP(l_err, exp_mss_thermal_init, l_fapiOcmbTarget);
if (l_err)
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, ERR_MRK
"ERROR: exp_mss_thermal_init HWP call on Explorer "
"chip, target HUID 0x%08x, chipId 0x%.8X failed."
TRACE_ERR_FMT,
get_huid(l_ocmbTarget),
l_chipId,
TRACE_ERR_ARGS(l_err) );
// We don't want to fail the IPL due to problems setting
// up the temperature sensors on the DIMM, so just commit
// the log here.
errlCommit(l_err, ISTEP_COMP_ID);
}
else
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, INFO_MRK
"SUCCESS: exp_mss_thermal_init HWP on Explorer "
"chip, target HUID 0x%.8X, chipId 0x%.8X",
TARGETING::get_huid(l_ocmbTarget),
l_chipId );
}
} // end if (l_chipId == POWER_CHIPID::EXPLORER_16)
else
{
// Non-Explorer chip, a NOOP operation, trace out stating so
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, INFO_MRK
"Skipping call to exp_mss_thermal_init HWP on target "
"HUID 0x%.8X, chipId 0x%.8X is not an Explorer OCMB",
TARGETING::get_huid(l_ocmbTarget),
l_chipId );
}
} // end for (const auto & l_ocmbTarget : l_ocmbTargetList)
} // p10_call_mss_thermal_init
/**
* @brief Run Processor Throttle Synchronization on all functional
* Processor Chip targets
*
* param[in/out] io_iStepError - Container for errors if an error occurs
*
*/
void run_proc_throttle_sync(IStepError & io_iStepError)
{
errlHndl_t l_err(nullptr);
// Get a list of all processors to run Throttle Synchronization on
TARGETING::TargetHandleList l_procChips;
getAllChips( l_procChips, TARGETING::TYPE_PROC );
for (const auto & l_procChip: l_procChips)
{
// Convert the TARGETING::Target into a fapi2::Target by passing
// l_procChip into the fapi2::Target constructor
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>
l_fapiProcTarget(l_procChip);
// Calling p10_throttle_sync HWP on PROC chip, trace out stating so
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, INFO_MRK
"Running p10_throttle_sync HWP on PROC target HUID 0x%.8X",
TARGETING::get_huid(l_procChip) );
// Call the HWP p10_throttle_sync call on each fapi2::Target
FAPI_INVOKE_HWP( l_err, p10_throttle_sync, l_fapiProcTarget );
if (l_err)
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, ERR_MRK
"ERROR: p10_throttle_sync HWP call on PROC target "
"HUID 0x%08x failed."
TRACE_ERR_FMT,
get_huid(l_procChip),
TRACE_ERR_ARGS(l_err) );
// Capture error, commit and continue, do not break out here.
// Continue here and consolidate all the errors that might
// occur in a batch before bailing. This will facilitate in the
// efficiency of the reconfig loop.
captureError(l_err, io_iStepError, HWPF_COMP_ID, l_procChip);
}
else
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, INFO_MRK
"SUCCESS : p10_throttle_sync HWP call on "
"PROC target HUID 0x%08x",
TARGETING::get_huid(l_procChip) );
}
}
} // run_proc_throttle_sync
}; // namespace ISTEP_14
<|endoftext|> |
<commit_before>// RUN: %clang_cc1 -O1 -std=c++11 -emit-llvm -disable-llvm-passes -o - %s | FileCheck %s
// Clang should not generate alias to available_externally definitions.
// Check that the destructor of Foo is defined.
// The destructors have different return type for different targets.
// CHECK: define linkonce_odr {{.*}} @_ZN3FooD2Ev
template <class CharT>
struct String {
String() {}
~String();
};
template <class CharT>
inline __attribute__((visibility("hidden"), always_inline))
String<CharT>::~String() {}
extern template struct String<char>;
struct Foo : public String<char> { Foo() { String<char> s; } };
Foo f;
<commit_msg>Keep the test only for Itanium abi<commit_after>// RUN: %clang_cc1 -O1 -std=c++11 -emit-llvm -triple %itanium_abi_triple -disable-llvm-passes -o - %s | FileCheck %s
// Clang should not generate alias to available_externally definitions.
// Check that the destructor of Foo is defined.
// The destructors have different return type for different targets.
// CHECK: define linkonce_odr {{.*}} @_ZN3FooD2Ev
template <class CharT>
struct String {
String() {}
~String();
};
template <class CharT>
inline __attribute__((visibility("hidden"), always_inline))
String<CharT>::~String() {}
extern template struct String<char>;
struct Foo : public String<char> { Foo() { String<char> s; } };
Foo f;
<|endoftext|> |
<commit_before>#include "Rendu.hpp"
using namespace irr;
using namespace core;
using namespace video;
using namespace scene;
using namespace std;
Rendu::Rendu(Plateau* plateauRendu)
{
m_plateauRendu = plateauRendu;
//Device avec API = OPENGL, Fenêtre de taille 640 x 480p et 32bits par pixel
m_device = createDevice(EDT_OPENGL, dimension2d<u32>(640,480), 32);
m_driver = m_device->getVideoDriver();
m_sceneManager = m_device->getSceneManager();
//Lumière ambiante
m_sceneManager->setAmbientLight(SColorf(1.0,1.0,1.0,0.0));
//Caméra fixe
m_sceneManager->addCameraSceneNode(0, vector3df(1.6f, 3, 4.3f), vector3df(1.6f, 0, 2.2f));
//Debug FPS
//m_sceneManager->addCameraSceneNodeFPS(0,100.0f,0.005f,-1);
//Noeud père des cases du plateau
m_pereCases = m_sceneManager->addEmptySceneNode(0, CASE);
//Noeud père des cases du plateau
m_pereSpheres = m_sceneManager->addEmptySceneNode(0, SPHERE);
m_clickedSphere = nullptr;
dessinerPlateau();
dessinerSpheres();
m_device->setEventReceiver(this);
}
IrrlichtDevice* Rendu::getDevice()
{
return m_device;
}
IVideoDriver* Rendu::getDriver()
{
return m_driver;
}
ISceneManager* Rendu::getSceneManager()
{
return m_sceneManager;
}
void Rendu::dessinerPlateau()
{
f32 x, y, z;
x = y = z = 0.0f;
m_casePlateau = new ISceneNode**[m_plateauRendu->getTaille()];
for(int i = 0; i < m_plateauRendu->getTaille(); ++i, x = 0.0f, z += 1.1f)
{
m_casePlateau[i] = new ISceneNode*[m_plateauRendu->getTaille()];
for(int j = 0; j < m_plateauRendu->getTaille(); ++j, x+= 1.1f)
{
m_casePlateau[i][j] = m_sceneManager->addCubeSceneNode(
1.0f, //Taille du cube
m_pereCases, //Tous les cubes sont fils du noeud pereCases
i * m_plateauRendu->getTaille() + j, //Calcul du numéro ID
vector3df(x, y, z), //Position du cube, change à chaque tour de boucle
vector3df(0, 0, 0), //Rotation, ici aucune
vector3df(1.0f, 0.15f , 1.0f)); //Échelle, 0.15f en y pour une caisse fine en hauteur
m_casePlateau[i][j]->setMaterialTexture(0, m_driver->getTexture("caisse.png"));
}
}
}
void Rendu::dessinerSpheres()
{
vector3df tailleWumpa[4], echelle;
tailleWumpa[3] = vector3df(1.0f,1.0f,1.0f);
tailleWumpa[2] = tailleWumpa[3] * (2.0f/3.0f);
tailleWumpa[1] = tailleWumpa[3] / 3.0f;
m_sphere = new IAnimatedMeshSceneNode**[m_plateauRendu->getTaille()];
IAnimatedMesh* wumpa = m_sceneManager->getMesh("appletest.obj");
for(int i = 0; i < m_plateauRendu->getTaille(); ++i)
{
m_sphere[i] = new IAnimatedMeshSceneNode*[m_plateauRendu->getTaille()];
for(int j = 0; j < m_plateauRendu->getTaille(); ++j)
{
vector3df positionCase(m_casePlateau[i][j]->getPosition()); //Récupération position case courante
vector3df positionSphere(positionCase.X , positionCase.Y + 0.11f, positionCase.Z); //Place la sphère au dessus de cette case
if(m_plateauRendu->getGrille()[i][j] != 0)
{
echelle = tailleWumpa[m_plateauRendu->getGrille()[i][j]]; //Échelle calculée selon le niveau de la case
m_sphere[i][j] = m_sceneManager->addAnimatedMeshSceneNode(
wumpa, //Mesh chargé plus haut
m_pereSpheres, //Toutes les sphères sont filles de pereSpheres
i * m_plateauRendu->getTaille() + j, //Calcul du numéro ID
positionSphere, //Position calculée
vector3df(0,0,0), //Rotation, ici aucune
echelle); //Echelle calculée
m_sphere[i][j]->setMaterialFlag(EMF_LIGHTING, false);
}
else
m_sphere[i][j] = nullptr;
}
}
}
Rendu::~Rendu()
{
for(int i = 0; i < m_plateauRendu->getTaille(); ++i)
for(int j = 0; j < m_plateauRendu->getTaille(); ++j)
{
delete m_casePlateau[i][j];
delete m_sphere[i][j];
}
for(int i = 0; i < m_plateauRendu->getTaille(); ++i)
{
delete[] m_casePlateau[i];
delete[] m_sphere[i];
}
delete[] m_casePlateau;
delete[] m_sphere;
}
bool Rendu::OnEvent(const SEvent &event)
{
if(event.EventType == EET_MOUSE_INPUT_EVENT)
{
if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
{
position2d <s32> curseur = m_device
->getCursorControl()
->getPosition(); //Position du curseur au clic
m_clickedSphere = m_sceneManager
->getSceneCollisionManager()
->getSceneNodeFromScreenCoordinatesBB(curseur, 0, false, m_pereSpheres); //Sphère en collision avec le clic
return true;
}
}
return false;
}
void Rendu::majSphere()
{
if(m_clickedSphere == nullptr)
return;
s32 i = m_clickedSphere->getID() / m_plateauRendu->getTaille();
s32 j = m_clickedSphere->getID() % m_plateauRendu->getTaille();
IAnimatedMesh* wumpa = m_sceneManager->getMesh("appletest.obj");
if(m_plateauRendu->getGrille()[i][j] == 0)
{
vector3df positionCase(m_casePlateau[i][j]->getPosition()); //Récupération position case
vector3df positionSphere(positionCase.X , positionCase.Y + 0.11f, positionCase.Z); //Place la sphère au dessus du plateau
m_sphere[i][j] = m_sceneManager->addAnimatedMeshSceneNode(
wumpa, //Mesh chargé plus haut
m_pereSpheres, //Toutes les sphères sont filles de pereSpheres
i * m_plateauRendu->getTaille() + j, //Calcul du numéro ID
positionSphere, //Position de la sphère, fonction de celle de la case
vector3df(0, 0, 0), //Rotation, ici aucune
vector3df(1.0/3.0, 1.0/3.0, 1.0/3.0)); //Échelle, ici 1/3 car c'est une petite sphère qu'on ajoute
m_sphere[i][j]->setMaterialFlag(EMF_LIGHTING, false);
m_plateauRendu->augmenterNiveauCase(i,j);
}
else if(m_plateauRendu->getGrille()[i][j] == 1)
{
m_sphere[i][j]
->setScale(m_sphere[i][j]
->getScale() * 2.0);
m_plateauRendu->augmenterNiveauCase(i,j);
}
else if(m_plateauRendu->getGrille()[i][j] == 2)
{
m_sphere[i][j]
->setScale(m_sphere[i][j]
->getScale() * 3.0/2.0);
m_plateauRendu->augmenterNiveauCase(i,j);
}
else if(m_plateauRendu->getGrille()[i][j] == 3)
{
m_sphere[i][j]->remove();
m_sphere[i][j] = nullptr;
vector3df positionCase(m_casePlateau[i][j]->getPosition()); //Récupération position case courante
vector3df positionSphere[4];
positionSphere[NORD] = vector3df(positionCase.X, positionCase.Y + 0.11f, positionCase.Z - 0.20f);
positionSphere[SUD] = vector3df(positionCase.X, positionCase.Y + 0.11f, positionCase.Z + 0.20f );
positionSphere[EST] = vector3df(positionCase.X + 0.20f , positionCase.Y + 0.11f, positionCase.Z);
positionSphere[OUEST] = vector3df(positionCase.X - 0.20f, positionCase.Y + 0.11f, positionCase.Z);
IAnimatedMeshSceneNode** miniSphere = new IAnimatedMeshSceneNode*[4];
for(s32 i = NORD; i <= OUEST; ++i)
{
miniSphere[i] = m_sceneManager->addAnimatedMeshSceneNode(
wumpa, //Mesh chargé plus haut
m_pereSpheres, //Toutes les sphères sont filles de pereSpheres
i * m_plateauRendu->getTaille() + j, //Calcul du numéro ID
positionSphere[i], //Position de la sphère, fonction de celle de la case
vector3df(0, 0, 0), //Rotation, ici aucune
vector3df(1.0/3.0, 1.0/3.0, 1.0/3.0)); //Échelle, ici 1/3 car c'est une petite sphère qu'on ajoute
miniSphere[i]->setMaterialFlag(EMF_LIGHTING, false);
}
}
m_clickedSphere = nullptr;
return;
}
<commit_msg>Suppression d'un petit bug des mini sphères<commit_after>#include "Rendu.hpp"
using namespace irr;
using namespace core;
using namespace video;
using namespace scene;
using namespace std;
Rendu::Rendu(Plateau* plateauRendu)
{
m_plateauRendu = plateauRendu;
//Device avec API = OPENGL, Fenêtre de taille 640 x 480p et 32bits par pixel
m_device = createDevice(EDT_OPENGL, dimension2d<u32>(640,480), 32);
m_driver = m_device->getVideoDriver();
m_sceneManager = m_device->getSceneManager();
//Lumière ambiante
m_sceneManager->setAmbientLight(SColorf(1.0,1.0,1.0,0.0));
//Caméra fixe
m_sceneManager->addCameraSceneNode(0, vector3df(1.6f, 3, 4.3f), vector3df(1.6f, 0, 2.2f));
//Debug FPS
//m_sceneManager->addCameraSceneNodeFPS(0,100.0f,0.005f,-1);
//Noeud père des cases du plateau
m_pereCases = m_sceneManager->addEmptySceneNode(0, CASE);
//Noeud père des cases du plateau
m_pereSpheres = m_sceneManager->addEmptySceneNode(0, SPHERE);
m_clickedSphere = nullptr;
dessinerPlateau();
dessinerSpheres();
m_device->setEventReceiver(this);
}
IrrlichtDevice* Rendu::getDevice()
{
return m_device;
}
IVideoDriver* Rendu::getDriver()
{
return m_driver;
}
ISceneManager* Rendu::getSceneManager()
{
return m_sceneManager;
}
void Rendu::dessinerPlateau()
{
f32 x, y, z;
x = y = z = 0.0f;
m_casePlateau = new ISceneNode**[m_plateauRendu->getTaille()];
for(int i = 0; i < m_plateauRendu->getTaille(); ++i, x = 0.0f, z += 1.1f)
{
m_casePlateau[i] = new ISceneNode*[m_plateauRendu->getTaille()];
for(int j = 0; j < m_plateauRendu->getTaille(); ++j, x+= 1.1f)
{
m_casePlateau[i][j] = m_sceneManager->addCubeSceneNode(
1.0f, //Taille du cube
m_pereCases, //Tous les cubes sont fils du noeud pereCases
i * m_plateauRendu->getTaille() + j, //Calcul du numéro ID
vector3df(x, y, z), //Position du cube, change à chaque tour de boucle
vector3df(0, 0, 0), //Rotation, ici aucune
vector3df(1.0f, 0.15f , 1.0f)); //Échelle, 0.15f en y pour une caisse fine en hauteur
m_casePlateau[i][j]->setMaterialTexture(0, m_driver->getTexture("caisse.png"));
}
}
}
void Rendu::dessinerSpheres()
{
vector3df tailleWumpa[4], echelle;
tailleWumpa[3] = vector3df(1.0f,1.0f,1.0f);
tailleWumpa[2] = tailleWumpa[3] * (2.0f/3.0f);
tailleWumpa[1] = tailleWumpa[3] / 3.0f;
m_sphere = new IAnimatedMeshSceneNode**[m_plateauRendu->getTaille()];
IAnimatedMesh* wumpa = m_sceneManager->getMesh("appletest.obj");
for(int i = 0; i < m_plateauRendu->getTaille(); ++i)
{
m_sphere[i] = new IAnimatedMeshSceneNode*[m_plateauRendu->getTaille()];
for(int j = 0; j < m_plateauRendu->getTaille(); ++j)
{
vector3df positionCase(m_casePlateau[i][j]->getPosition()); //Récupération position case courante
vector3df positionSphere(positionCase.X , positionCase.Y + 0.11f, positionCase.Z); //Place la sphère au dessus de cette case
if(m_plateauRendu->getGrille()[i][j] != 0)
{
echelle = tailleWumpa[m_plateauRendu->getGrille()[i][j]]; //Échelle calculée selon le niveau de la case
m_sphere[i][j] = m_sceneManager->addAnimatedMeshSceneNode(
wumpa, //Mesh chargé plus haut
m_pereSpheres, //Toutes les sphères sont filles de pereSpheres
i * m_plateauRendu->getTaille() + j, //Calcul du numéro ID
positionSphere, //Position calculée
vector3df(0,0,0), //Rotation, ici aucune
echelle); //Echelle calculée
m_sphere[i][j]->setMaterialFlag(EMF_LIGHTING, false);
}
else
m_sphere[i][j] = nullptr;
}
}
}
Rendu::~Rendu()
{
for(int i = 0; i < m_plateauRendu->getTaille(); ++i)
for(int j = 0; j < m_plateauRendu->getTaille(); ++j)
{
delete m_casePlateau[i][j];
delete m_sphere[i][j];
}
for(int i = 0; i < m_plateauRendu->getTaille(); ++i)
{
delete[] m_casePlateau[i];
delete[] m_sphere[i];
}
delete[] m_casePlateau;
delete[] m_sphere;
}
bool Rendu::OnEvent(const SEvent &event)
{
if(event.EventType == EET_MOUSE_INPUT_EVENT)
{
if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
{
position2d <s32> curseur = m_device
->getCursorControl()
->getPosition(); //Position du curseur au clic
m_clickedSphere = m_sceneManager
->getSceneCollisionManager()
->getSceneNodeFromScreenCoordinatesBB(curseur, 0, false, m_pereSpheres); //Sphère en collision avec le clic
return true;
}
}
return false;
}
void Rendu::majSphere()
{
if(m_clickedSphere == nullptr)
return;
s32 i = m_clickedSphere->getID() / m_plateauRendu->getTaille();
s32 j = m_clickedSphere->getID() % m_plateauRendu->getTaille();
IAnimatedMesh* wumpa = m_sceneManager->getMesh("appletest.obj");
if(m_plateauRendu->getGrille()[i][j] == 0)
{
vector3df positionCase(m_casePlateau[i][j]->getPosition()); //Récupération position case
vector3df positionSphere(positionCase.X , positionCase.Y + 0.11f, positionCase.Z); //Place la sphère au dessus du plateau
m_sphere[i][j] = m_sceneManager->addAnimatedMeshSceneNode(
wumpa, //Mesh chargé plus haut
m_pereSpheres, //Toutes les sphères sont filles de pereSpheres
i * m_plateauRendu->getTaille() + j, //Calcul du numéro ID
positionSphere, //Position de la sphère, fonction de celle de la case
vector3df(0, 0, 0), //Rotation, ici aucune
vector3df(1.0/3.0, 1.0/3.0, 1.0/3.0)); //Échelle, ici 1/3 car c'est une petite sphère qu'on ajoute
m_sphere[i][j]->setMaterialFlag(EMF_LIGHTING, false);
m_plateauRendu->augmenterNiveauCase(i,j);
}
else if(m_plateauRendu->getGrille()[i][j] == 1)
{
m_sphere[i][j]
->setScale(m_sphere[i][j]
->getScale() * 2.0);
m_plateauRendu->augmenterNiveauCase(i,j);
}
else if(m_plateauRendu->getGrille()[i][j] == 2)
{
m_sphere[i][j]
->setScale(m_sphere[i][j]
->getScale() * 3.0/2.0);
m_plateauRendu->augmenterNiveauCase(i,j);
}
else if(m_plateauRendu->getGrille()[i][j] == 3)
{
m_sphere[i][j]->remove();
m_sphere[i][j] = nullptr;
vector3df positionCase(m_casePlateau[i][j]->getPosition()); //Récupération position case courante
vector3df positionSphere[4];
positionSphere[NORD] = vector3df(positionCase.X, positionCase.Y + 0.11f, positionCase.Z - 0.20f);
positionSphere[SUD] = vector3df(positionCase.X, positionCase.Y + 0.11f, positionCase.Z + 0.20f );
positionSphere[EST] = vector3df(positionCase.X + 0.20f , positionCase.Y + 0.11f, positionCase.Z);
positionSphere[OUEST] = vector3df(positionCase.X - 0.20f, positionCase.Y + 0.11f, positionCase.Z);
IAnimatedMeshSceneNode** miniSphere = new IAnimatedMeshSceneNode*[4];
for(s32 i = NORD; i <= OUEST; ++i)
{
miniSphere[i] = m_sceneManager->addAnimatedMeshSceneNode(
wumpa, //Mesh chargé plus haut
0, //Pas de père car vouée à disparaître
-1, //Pas besoin d'ID non plus
positionSphere[i],
vector3df(0, 0, 0), //Rotation, ici aucune
vector3df(1.0/3.0, 1.0/3.0, 1.0/3.0)); //Échelle, ici 1/3 car c'est une petite sphère qu'on ajoute
miniSphere[i]->setMaterialFlag(EMF_LIGHTING, false);
}
}
m_clickedSphere = nullptr;
return;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 "CppUTest/TestHarness.h"
#include "CppUTest/TestRegistry.h"
#include "CppUTest/TestOutput.h"
#include "CppUTest/MemoryLeakWarningPlugin.h"
#include "CppUTest/MemoryLeakDetector.h"
#include "CppUTest/TestMemoryAllocator.h"
#include "CppUTest/TestTestingFixture.h"
#include "CppUTest/TestHarness_c.h"
#include "CppUTest/SimpleMutex.h"
static char* leak1;
static long* leak2;
class DummyReporter: public MemoryLeakFailure
{
public:
virtual ~DummyReporter()
{
}
virtual void fail(char* /*fail_string*/)
{
}
};
static MemoryLeakDetector* detector;
static MemoryLeakWarningPlugin* memPlugin;
static DummyReporter dummy;
static TestMemoryAllocator* allocator;
TEST_GROUP(MemoryLeakWarningLocalDetectorTest)
{
};
TEST(MemoryLeakWarningLocalDetectorTest, localDetectorReturnsNewGlobalWhenNoneWasSet)
{
MemoryLeakWarningPlugin memoryLeakWarningPlugin("TestMemoryLeakWarningPlugin", NULL);
CHECK(0 != memoryLeakWarningPlugin.getMemoryLeakDetector());
}
TEST(MemoryLeakWarningLocalDetectorTest, localDetectorIsTheOneSpecifiedInConstructor)
{
MemoryLeakDetector localDetector(&dummy);
MemoryLeakWarningPlugin memoryLeakWarningPlugin("TestMemoryLeakWarningPlugin", &localDetector);
POINTERS_EQUAL(&localDetector, memoryLeakWarningPlugin.getMemoryLeakDetector());
}
TEST(MemoryLeakWarningLocalDetectorTest, localDetectorIsGlobalDetector)
{
MemoryLeakDetector* globalDetector = MemoryLeakWarningPlugin::getGlobalDetector();
MemoryLeakWarningPlugin memoryLeakWarningPlugin("TestMemoryLeakWarningPlugin", NULL);
MemoryLeakDetector* localDetector = memoryLeakWarningPlugin.getMemoryLeakDetector();
POINTERS_EQUAL(globalDetector, localDetector);
}
TEST_GROUP(MemoryLeakWarningTest)
{
TestTestingFixture* fixture;
void setup()
{
fixture = new TestTestingFixture();
detector = new MemoryLeakDetector(&dummy);
allocator = new TestMemoryAllocator;
memPlugin = new MemoryLeakWarningPlugin("TestMemoryLeakWarningPlugin", detector);
fixture->registry_->installPlugin(memPlugin);
memPlugin->enable();
leak1 = 0;
leak2 = 0;
}
void teardown()
{
detector->deallocMemory(allocator, leak1);
detector->deallocMemory(allocator, leak2);
delete fixture;
delete memPlugin;
delete detector;
delete allocator;
}
};
static void _testTwoLeaks()
{
leak1 = detector->allocMemory(allocator, 10);
leak2 = (long*) (void*) detector->allocMemory(allocator, 4);
}
TEST(MemoryLeakWarningTest, TwoLeaks)
{
fixture->setTestFunction(_testTwoLeaks);
fixture->runAllTests();
LONGS_EQUAL(1, fixture->getFailureCount());
fixture->assertPrintContains("Total number of leaks: 2");
}
static void _testIgnore2()
{
memPlugin->expectLeaksInTest(2);
leak1 = detector->allocMemory(allocator, 10);
leak2 = (long*) (void*) detector->allocMemory(allocator, 4);
}
TEST(MemoryLeakWarningTest, Ignore2)
{
fixture->setTestFunction(_testIgnore2);
fixture->runAllTests();
LONGS_EQUAL(0, fixture->getFailureCount());
}
static void _failAndLeakMemory()
{
leak1 = detector->allocMemory(allocator, 10);
FAIL("");
}
TEST(MemoryLeakWarningTest, FailingTestDoesNotReportMemoryLeaks)
{
fixture->setTestFunction(_failAndLeakMemory);
fixture->runAllTests();
LONGS_EQUAL(1, fixture->getFailureCount());
}
static bool memoryLeakDetectorWasDeleted = false;
static bool memoryLeakFailureWasDelete = false;
class DummyMemoryLeakDetector : public MemoryLeakDetector
{
public:
DummyMemoryLeakDetector(MemoryLeakFailure* reporter) : MemoryLeakDetector(reporter) {}
virtual ~DummyMemoryLeakDetector()
{
memoryLeakDetectorWasDeleted = true;
}
};
class DummyMemoryLeakFailure : public MemoryLeakFailure
{
virtual ~DummyMemoryLeakFailure()
{
memoryLeakFailureWasDelete = true;
}
virtual void fail(char*)
{
}
};
static bool cpputestHasCrashed;
TEST_GROUP(MemoryLeakWarningGlobalDetectorTest)
{
MemoryLeakDetector* detector;
MemoryLeakFailure* failureReporter;
DummyMemoryLeakDetector * dummyDetector;
MemoryLeakFailure* dummyReporter;
static void crashMethod()
{
cpputestHasCrashed = true;
}
void setup()
{
detector = MemoryLeakWarningPlugin::getGlobalDetector();
failureReporter = MemoryLeakWarningPlugin::getGlobalFailureReporter();
memoryLeakDetectorWasDeleted = false;
memoryLeakFailureWasDelete = false;
MemoryLeakWarningPlugin::turnOffNewDeleteOverloads();
dummyReporter = new DummyMemoryLeakFailure;
dummyDetector = new DummyMemoryLeakDetector(dummyReporter);
UtestShell::setCrashMethod(crashMethod);
cpputestHasCrashed = false;
}
void teardown()
{
MemoryLeakWarningPlugin::turnOffNewDeleteOverloads();
if (!memoryLeakDetectorWasDeleted) delete dummyDetector;
if (!memoryLeakFailureWasDelete) delete dummyReporter;
MemoryLeakWarningPlugin::setGlobalDetector(detector, failureReporter);
MemoryLeakWarningPlugin::turnOnNewDeleteOverloads();
UtestShell::resetCrashMethod();
setCurrentMallocAllocatorToDefault();
setCurrentNewAllocatorToDefault();
setCurrentNewArrayAllocatorToDefault();
}
};
TEST(MemoryLeakWarningGlobalDetectorTest, turnOffNewOverloadsCausesNoAdditionalLeaks)
{
int storedAmountOfLeaks = detector->totalMemoryLeaks(mem_leak_period_all);
char* arrayMemory = new char[100];
char* nonArrayMemory = new char;
char* mallocMemory = (char*) cpputest_malloc_location_with_leak_detection(10, "file", 10);
char* reallocMemory = (char*) cpputest_realloc_location_with_leak_detection(NULL, 10, "file", 10);
LONGS_EQUAL(storedAmountOfLeaks, detector->totalMemoryLeaks(mem_leak_period_all));
cpputest_free_location_with_leak_detection(mallocMemory, "file", 10);
cpputest_free_location_with_leak_detection(reallocMemory, "file", 10);
delete [] arrayMemory;
delete nonArrayMemory;
}
TEST(MemoryLeakWarningGlobalDetectorTest, destroyGlobalDetector)
{
MemoryLeakWarningPlugin::setGlobalDetector(dummyDetector, dummyReporter);
MemoryLeakWarningPlugin::destroyGlobalDetector();
CHECK(memoryLeakDetectorWasDeleted);
CHECK(memoryLeakFailureWasDelete);
}
TEST(MemoryLeakWarningGlobalDetectorTest, MemoryWarningPluginCanBeSetToDestroyTheGlobalDetector)
{
MemoryLeakWarningPlugin* plugin = new MemoryLeakWarningPlugin("dummy");
plugin->destroyGlobalDetectorAndTurnOffMemoryLeakDetectionInDestructor(true);
MemoryLeakWarningPlugin::setGlobalDetector(dummyDetector, dummyReporter);
delete plugin;
CHECK(memoryLeakDetectorWasDeleted);
}
#ifndef CPPUTEST_MEM_LEAK_DETECTION_DISABLED
TEST(MemoryLeakWarningGlobalDetectorTest, crashOnLeakWithOperatorNew)
{
MemoryLeakWarningPlugin::setGlobalDetector(dummyDetector, dummyReporter);
MemoryLeakWarningPlugin::turnOnNewDeleteOverloads();
crash_on_allocation_number(1);
char* memory = new char[100];
CHECK(cpputestHasCrashed);
delete [] memory;
}
TEST(MemoryLeakWarningGlobalDetectorTest, crashOnLeakWithOperatorNewArray)
{
MemoryLeakWarningPlugin::setGlobalDetector(dummyDetector, dummyReporter);
MemoryLeakWarningPlugin::turnOnNewDeleteOverloads();
crash_on_allocation_number(1);
char* memory = new char;
CHECK(cpputestHasCrashed);
delete memory;
}
TEST(MemoryLeakWarningGlobalDetectorTest, crashOnLeakWithOperatorMalloc)
{
MemoryLeakWarningPlugin::setGlobalDetector(dummyDetector, dummyReporter);
MemoryLeakWarningPlugin::turnOnNewDeleteOverloads();
crash_on_allocation_number(1);
char* memory = (char*) cpputest_malloc(10);
CHECK(cpputestHasCrashed);
cpputest_free(memory);
}
TEST(MemoryLeakWarningGlobalDetectorTest, gettingTheGlobalDetectorDoesNotRestoreTheMemoryLeakOverloadsWhenTheyWereAlreadyOff)
{
MemoryLeakWarningPlugin::setGlobalDetector(NULL, NULL);
MemoryLeakDetector* temporaryDetector = MemoryLeakWarningPlugin::getGlobalDetector();
MemoryLeakFailure* temporaryReporter = MemoryLeakWarningPlugin::getGlobalFailureReporter();
MemoryLeakWarningPlugin::turnOffNewDeleteOverloads();
bool areNewDeleteOverloaded = MemoryLeakWarningPlugin::areNewDeleteOverloaded();
MemoryLeakWarningPlugin::turnOnNewDeleteOverloads();
CHECK(!areNewDeleteOverloaded);
MemoryLeakWarningPlugin::turnOffNewDeleteOverloads();
delete temporaryReporter;
delete temporaryDetector;
}
TEST(MemoryLeakWarningGlobalDetectorTest, checkIfTheMemoryLeakOverloadsAreOn)
{
MemoryLeakWarningPlugin::turnOnNewDeleteOverloads();
CHECK(MemoryLeakWarningPlugin::areNewDeleteOverloaded());
MemoryLeakWarningPlugin::turnOffNewDeleteOverloads();
}
TEST(MemoryLeakWarningGlobalDetectorTest, checkIfTheMemoryLeakOverloadsAreOff)
{
MemoryLeakWarningPlugin::turnOffNewDeleteOverloads();
bool areNewDeleteOverloaded = MemoryLeakWarningPlugin::areNewDeleteOverloaded();
MemoryLeakWarningPlugin::turnOnNewDeleteOverloads();
CHECK(!areNewDeleteOverloaded);
}
#endif
#if CPPUTEST_USE_STD_CPP_LIB
TEST(MemoryLeakWarningGlobalDetectorTest, turnOffNewOverloadsNoThrowCausesNoAdditionalLeaks)
{
#undef new
int storedAmountOfLeaks = detector->totalMemoryLeaks(mem_leak_period_all);
char* nonMemoryNoThrow = new (std::nothrow) char;
char* nonArrayMemoryNoThrow = new (std::nothrow) char[10];
char* nonArrayMemoryThrow = new char[10];
LONGS_EQUAL(storedAmountOfLeaks, detector->totalMemoryLeaks(mem_leak_period_all));
delete nonMemoryNoThrow;
delete nonArrayMemoryNoThrow;
delete nonArrayMemoryThrow;
#ifdef CPPUTEST_USE_NEW_MACROS
#include "CppUTest/MemoryLeakDetectorNewMacros.h"
#endif
}
#ifndef CPPUTEST_MEM_LEAK_DETECTION_DISABLED
static int mutexLockCount = 0;
static int mutexUnlockCount = 0;
static void StubMutexLock(PlatformSpecificMutex)
{
mutexLockCount++;
}
static void StubMutexUnlock(PlatformSpecificMutex)
{
mutexUnlockCount++;
}
TEST_GROUP(MemoryLeakWarningThreadSafe)
{
void setup()
{
UT_PTR_SET(PlatformSpecificMutexLock, StubMutexLock);
UT_PTR_SET(PlatformSpecificMutexUnlock, StubMutexUnlock);
mutexLockCount = 0;
mutexUnlockCount = 0;
}
void teardown()
{
}
};
TEST(MemoryLeakWarningThreadSafe, turnOnThreadSafeMallocFreeReallocOverloadsDebug)
{
int storedAmountOfLeaks = MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all);
MemoryLeakWarningPlugin::turnOnThreadSafeNewDeleteOverloads();
int *n = (int*) cpputest_malloc(sizeof(int));
LONGS_EQUAL(storedAmountOfLeaks + 1, MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all));
CHECK_EQUAL(1, mutexLockCount);
CHECK_EQUAL(1, mutexUnlockCount);
n = (int*) cpputest_realloc(n, sizeof(int)*3);
LONGS_EQUAL(storedAmountOfLeaks + 1, MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all));
CHECK_EQUAL(2, mutexLockCount);
CHECK_EQUAL(2, mutexUnlockCount);
cpputest_free(n);
LONGS_EQUAL(storedAmountOfLeaks, MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all));
CHECK_EQUAL(3, mutexLockCount);
CHECK_EQUAL(3, mutexUnlockCount);
MemoryLeakWarningPlugin::turnOnNewDeleteOverloads();
}
TEST(MemoryLeakWarningThreadSafe, turnOnThreadSafeNewDeleteOverloadsDebug)
{
int storedAmountOfLeaks = MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all);
MemoryLeakWarningPlugin::turnOnThreadSafeNewDeleteOverloads();
int *n = new int;
char *str = new char[20];
LONGS_EQUAL(storedAmountOfLeaks + 2, MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all));
CHECK_EQUAL(2, mutexLockCount);
CHECK_EQUAL(2, mutexUnlockCount);
delete [] str;
delete n;
LONGS_EQUAL(storedAmountOfLeaks, MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all));
CHECK_EQUAL(4, mutexLockCount);
CHECK_EQUAL(4, mutexUnlockCount);
MemoryLeakWarningPlugin::turnOnNewDeleteOverloads();
}
#ifdef __clang__
IGNORE_TEST(MemoryLeakWarningThreadSafe, turnOnThreadSafeNewDeleteOverloads)
{
/* Clang misbehaves with -O2 - it will not overload operator new or
* operator new[] no matter what. Therefore, this test is must be ignored.
*/
}
#else
TEST(MemoryLeakWarningThreadSafe, turnOnThreadSafeNewDeleteOverloads)
{
#undef new
int storedAmountOfLeaks = MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all);
MemoryLeakWarningPlugin::turnOnThreadSafeNewDeleteOverloads();
int *n = new int;
int *n_nothrow = new (std::nothrow) int;
char *str = new char[20];
char *str_nothrow = new (std::nothrow) char[20];
LONGS_EQUAL(storedAmountOfLeaks + 4, MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all));
CHECK_EQUAL(4, mutexLockCount);
CHECK_EQUAL(4, mutexUnlockCount);
delete [] str_nothrow;
delete [] str;
delete n;
delete n_nothrow;
LONGS_EQUAL(storedAmountOfLeaks, MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all));
CHECK_EQUAL(8, mutexLockCount);
CHECK_EQUAL(8, mutexUnlockCount);
MemoryLeakWarningPlugin::turnOnNewDeleteOverloads();
#ifdef CPPUTEST_USE_NEW_MACROS
#include "CppUTest/MemoryLeakDetectorNewMacros.h"
#endif
}
#endif
#endif
#endif
<commit_msg>Removed another warning related to missing [] on the delete<commit_after>/*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 "CppUTest/TestHarness.h"
#include "CppUTest/TestRegistry.h"
#include "CppUTest/TestOutput.h"
#include "CppUTest/MemoryLeakWarningPlugin.h"
#include "CppUTest/MemoryLeakDetector.h"
#include "CppUTest/TestMemoryAllocator.h"
#include "CppUTest/TestTestingFixture.h"
#include "CppUTest/TestHarness_c.h"
#include "CppUTest/SimpleMutex.h"
static char* leak1;
static long* leak2;
class DummyReporter: public MemoryLeakFailure
{
public:
virtual ~DummyReporter()
{
}
virtual void fail(char* /*fail_string*/)
{
}
};
static MemoryLeakDetector* detector;
static MemoryLeakWarningPlugin* memPlugin;
static DummyReporter dummy;
static TestMemoryAllocator* allocator;
TEST_GROUP(MemoryLeakWarningLocalDetectorTest)
{
};
TEST(MemoryLeakWarningLocalDetectorTest, localDetectorReturnsNewGlobalWhenNoneWasSet)
{
MemoryLeakWarningPlugin memoryLeakWarningPlugin("TestMemoryLeakWarningPlugin", NULL);
CHECK(0 != memoryLeakWarningPlugin.getMemoryLeakDetector());
}
TEST(MemoryLeakWarningLocalDetectorTest, localDetectorIsTheOneSpecifiedInConstructor)
{
MemoryLeakDetector localDetector(&dummy);
MemoryLeakWarningPlugin memoryLeakWarningPlugin("TestMemoryLeakWarningPlugin", &localDetector);
POINTERS_EQUAL(&localDetector, memoryLeakWarningPlugin.getMemoryLeakDetector());
}
TEST(MemoryLeakWarningLocalDetectorTest, localDetectorIsGlobalDetector)
{
MemoryLeakDetector* globalDetector = MemoryLeakWarningPlugin::getGlobalDetector();
MemoryLeakWarningPlugin memoryLeakWarningPlugin("TestMemoryLeakWarningPlugin", NULL);
MemoryLeakDetector* localDetector = memoryLeakWarningPlugin.getMemoryLeakDetector();
POINTERS_EQUAL(globalDetector, localDetector);
}
TEST_GROUP(MemoryLeakWarningTest)
{
TestTestingFixture* fixture;
void setup()
{
fixture = new TestTestingFixture();
detector = new MemoryLeakDetector(&dummy);
allocator = new TestMemoryAllocator;
memPlugin = new MemoryLeakWarningPlugin("TestMemoryLeakWarningPlugin", detector);
fixture->registry_->installPlugin(memPlugin);
memPlugin->enable();
leak1 = 0;
leak2 = 0;
}
void teardown()
{
detector->deallocMemory(allocator, leak1);
detector->deallocMemory(allocator, leak2);
delete fixture;
delete memPlugin;
delete detector;
delete allocator;
}
};
static void _testTwoLeaks()
{
leak1 = detector->allocMemory(allocator, 10);
leak2 = (long*) (void*) detector->allocMemory(allocator, 4);
}
TEST(MemoryLeakWarningTest, TwoLeaks)
{
fixture->setTestFunction(_testTwoLeaks);
fixture->runAllTests();
LONGS_EQUAL(1, fixture->getFailureCount());
fixture->assertPrintContains("Total number of leaks: 2");
}
static void _testIgnore2()
{
memPlugin->expectLeaksInTest(2);
leak1 = detector->allocMemory(allocator, 10);
leak2 = (long*) (void*) detector->allocMemory(allocator, 4);
}
TEST(MemoryLeakWarningTest, Ignore2)
{
fixture->setTestFunction(_testIgnore2);
fixture->runAllTests();
LONGS_EQUAL(0, fixture->getFailureCount());
}
static void _failAndLeakMemory()
{
leak1 = detector->allocMemory(allocator, 10);
FAIL("");
}
TEST(MemoryLeakWarningTest, FailingTestDoesNotReportMemoryLeaks)
{
fixture->setTestFunction(_failAndLeakMemory);
fixture->runAllTests();
LONGS_EQUAL(1, fixture->getFailureCount());
}
static bool memoryLeakDetectorWasDeleted = false;
static bool memoryLeakFailureWasDelete = false;
class DummyMemoryLeakDetector : public MemoryLeakDetector
{
public:
DummyMemoryLeakDetector(MemoryLeakFailure* reporter) : MemoryLeakDetector(reporter) {}
virtual ~DummyMemoryLeakDetector()
{
memoryLeakDetectorWasDeleted = true;
}
};
class DummyMemoryLeakFailure : public MemoryLeakFailure
{
virtual ~DummyMemoryLeakFailure()
{
memoryLeakFailureWasDelete = true;
}
virtual void fail(char*)
{
}
};
static bool cpputestHasCrashed;
TEST_GROUP(MemoryLeakWarningGlobalDetectorTest)
{
MemoryLeakDetector* detector;
MemoryLeakFailure* failureReporter;
DummyMemoryLeakDetector * dummyDetector;
MemoryLeakFailure* dummyReporter;
static void crashMethod()
{
cpputestHasCrashed = true;
}
void setup()
{
detector = MemoryLeakWarningPlugin::getGlobalDetector();
failureReporter = MemoryLeakWarningPlugin::getGlobalFailureReporter();
memoryLeakDetectorWasDeleted = false;
memoryLeakFailureWasDelete = false;
MemoryLeakWarningPlugin::turnOffNewDeleteOverloads();
dummyReporter = new DummyMemoryLeakFailure;
dummyDetector = new DummyMemoryLeakDetector(dummyReporter);
UtestShell::setCrashMethod(crashMethod);
cpputestHasCrashed = false;
}
void teardown()
{
MemoryLeakWarningPlugin::turnOffNewDeleteOverloads();
if (!memoryLeakDetectorWasDeleted) delete dummyDetector;
if (!memoryLeakFailureWasDelete) delete dummyReporter;
MemoryLeakWarningPlugin::setGlobalDetector(detector, failureReporter);
MemoryLeakWarningPlugin::turnOnNewDeleteOverloads();
UtestShell::resetCrashMethod();
setCurrentMallocAllocatorToDefault();
setCurrentNewAllocatorToDefault();
setCurrentNewArrayAllocatorToDefault();
}
};
TEST(MemoryLeakWarningGlobalDetectorTest, turnOffNewOverloadsCausesNoAdditionalLeaks)
{
int storedAmountOfLeaks = detector->totalMemoryLeaks(mem_leak_period_all);
char* arrayMemory = new char[100];
char* nonArrayMemory = new char;
char* mallocMemory = (char*) cpputest_malloc_location_with_leak_detection(10, "file", 10);
char* reallocMemory = (char*) cpputest_realloc_location_with_leak_detection(NULL, 10, "file", 10);
LONGS_EQUAL(storedAmountOfLeaks, detector->totalMemoryLeaks(mem_leak_period_all));
cpputest_free_location_with_leak_detection(mallocMemory, "file", 10);
cpputest_free_location_with_leak_detection(reallocMemory, "file", 10);
delete [] arrayMemory;
delete nonArrayMemory;
}
TEST(MemoryLeakWarningGlobalDetectorTest, destroyGlobalDetector)
{
MemoryLeakWarningPlugin::setGlobalDetector(dummyDetector, dummyReporter);
MemoryLeakWarningPlugin::destroyGlobalDetector();
CHECK(memoryLeakDetectorWasDeleted);
CHECK(memoryLeakFailureWasDelete);
}
TEST(MemoryLeakWarningGlobalDetectorTest, MemoryWarningPluginCanBeSetToDestroyTheGlobalDetector)
{
MemoryLeakWarningPlugin* plugin = new MemoryLeakWarningPlugin("dummy");
plugin->destroyGlobalDetectorAndTurnOffMemoryLeakDetectionInDestructor(true);
MemoryLeakWarningPlugin::setGlobalDetector(dummyDetector, dummyReporter);
delete plugin;
CHECK(memoryLeakDetectorWasDeleted);
}
#ifndef CPPUTEST_MEM_LEAK_DETECTION_DISABLED
TEST(MemoryLeakWarningGlobalDetectorTest, crashOnLeakWithOperatorNew)
{
MemoryLeakWarningPlugin::setGlobalDetector(dummyDetector, dummyReporter);
MemoryLeakWarningPlugin::turnOnNewDeleteOverloads();
crash_on_allocation_number(1);
char* memory = new char[100];
CHECK(cpputestHasCrashed);
delete [] memory;
}
TEST(MemoryLeakWarningGlobalDetectorTest, crashOnLeakWithOperatorNewArray)
{
MemoryLeakWarningPlugin::setGlobalDetector(dummyDetector, dummyReporter);
MemoryLeakWarningPlugin::turnOnNewDeleteOverloads();
crash_on_allocation_number(1);
char* memory = new char;
CHECK(cpputestHasCrashed);
delete memory;
}
TEST(MemoryLeakWarningGlobalDetectorTest, crashOnLeakWithOperatorMalloc)
{
MemoryLeakWarningPlugin::setGlobalDetector(dummyDetector, dummyReporter);
MemoryLeakWarningPlugin::turnOnNewDeleteOverloads();
crash_on_allocation_number(1);
char* memory = (char*) cpputest_malloc(10);
CHECK(cpputestHasCrashed);
cpputest_free(memory);
}
TEST(MemoryLeakWarningGlobalDetectorTest, gettingTheGlobalDetectorDoesNotRestoreTheMemoryLeakOverloadsWhenTheyWereAlreadyOff)
{
MemoryLeakWarningPlugin::setGlobalDetector(NULL, NULL);
MemoryLeakDetector* temporaryDetector = MemoryLeakWarningPlugin::getGlobalDetector();
MemoryLeakFailure* temporaryReporter = MemoryLeakWarningPlugin::getGlobalFailureReporter();
MemoryLeakWarningPlugin::turnOffNewDeleteOverloads();
bool areNewDeleteOverloaded = MemoryLeakWarningPlugin::areNewDeleteOverloaded();
MemoryLeakWarningPlugin::turnOnNewDeleteOverloads();
CHECK(!areNewDeleteOverloaded);
MemoryLeakWarningPlugin::turnOffNewDeleteOverloads();
delete temporaryReporter;
delete temporaryDetector;
}
TEST(MemoryLeakWarningGlobalDetectorTest, checkIfTheMemoryLeakOverloadsAreOn)
{
MemoryLeakWarningPlugin::turnOnNewDeleteOverloads();
CHECK(MemoryLeakWarningPlugin::areNewDeleteOverloaded());
MemoryLeakWarningPlugin::turnOffNewDeleteOverloads();
}
TEST(MemoryLeakWarningGlobalDetectorTest, checkIfTheMemoryLeakOverloadsAreOff)
{
MemoryLeakWarningPlugin::turnOffNewDeleteOverloads();
bool areNewDeleteOverloaded = MemoryLeakWarningPlugin::areNewDeleteOverloaded();
MemoryLeakWarningPlugin::turnOnNewDeleteOverloads();
CHECK(!areNewDeleteOverloaded);
}
#endif
#if CPPUTEST_USE_STD_CPP_LIB
TEST(MemoryLeakWarningGlobalDetectorTest, turnOffNewOverloadsNoThrowCausesNoAdditionalLeaks)
{
#undef new
int storedAmountOfLeaks = detector->totalMemoryLeaks(mem_leak_period_all);
char* nonMemoryNoThrow = new (std::nothrow) char;
char* nonArrayMemoryNoThrow = new (std::nothrow) char[10];
char* nonArrayMemoryThrow = new char[10];
LONGS_EQUAL(storedAmountOfLeaks, detector->totalMemoryLeaks(mem_leak_period_all));
delete nonMemoryNoThrow;
delete [] nonArrayMemoryNoThrow;
delete [] nonArrayMemoryThrow;
#ifdef CPPUTEST_USE_NEW_MACROS
#include "CppUTest/MemoryLeakDetectorNewMacros.h"
#endif
}
#ifndef CPPUTEST_MEM_LEAK_DETECTION_DISABLED
static int mutexLockCount = 0;
static int mutexUnlockCount = 0;
static void StubMutexLock(PlatformSpecificMutex)
{
mutexLockCount++;
}
static void StubMutexUnlock(PlatformSpecificMutex)
{
mutexUnlockCount++;
}
TEST_GROUP(MemoryLeakWarningThreadSafe)
{
void setup()
{
UT_PTR_SET(PlatformSpecificMutexLock, StubMutexLock);
UT_PTR_SET(PlatformSpecificMutexUnlock, StubMutexUnlock);
mutexLockCount = 0;
mutexUnlockCount = 0;
}
void teardown()
{
}
};
TEST(MemoryLeakWarningThreadSafe, turnOnThreadSafeMallocFreeReallocOverloadsDebug)
{
int storedAmountOfLeaks = MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all);
MemoryLeakWarningPlugin::turnOnThreadSafeNewDeleteOverloads();
int *n = (int*) cpputest_malloc(sizeof(int));
LONGS_EQUAL(storedAmountOfLeaks + 1, MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all));
CHECK_EQUAL(1, mutexLockCount);
CHECK_EQUAL(1, mutexUnlockCount);
n = (int*) cpputest_realloc(n, sizeof(int)*3);
LONGS_EQUAL(storedAmountOfLeaks + 1, MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all));
CHECK_EQUAL(2, mutexLockCount);
CHECK_EQUAL(2, mutexUnlockCount);
cpputest_free(n);
LONGS_EQUAL(storedAmountOfLeaks, MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all));
CHECK_EQUAL(3, mutexLockCount);
CHECK_EQUAL(3, mutexUnlockCount);
MemoryLeakWarningPlugin::turnOnNewDeleteOverloads();
}
TEST(MemoryLeakWarningThreadSafe, turnOnThreadSafeNewDeleteOverloadsDebug)
{
int storedAmountOfLeaks = MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all);
MemoryLeakWarningPlugin::turnOnThreadSafeNewDeleteOverloads();
int *n = new int;
char *str = new char[20];
LONGS_EQUAL(storedAmountOfLeaks + 2, MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all));
CHECK_EQUAL(2, mutexLockCount);
CHECK_EQUAL(2, mutexUnlockCount);
delete [] str;
delete n;
LONGS_EQUAL(storedAmountOfLeaks, MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all));
CHECK_EQUAL(4, mutexLockCount);
CHECK_EQUAL(4, mutexUnlockCount);
MemoryLeakWarningPlugin::turnOnNewDeleteOverloads();
}
#ifdef __clang__
IGNORE_TEST(MemoryLeakWarningThreadSafe, turnOnThreadSafeNewDeleteOverloads)
{
/* Clang misbehaves with -O2 - it will not overload operator new or
* operator new[] no matter what. Therefore, this test is must be ignored.
*/
}
#else
TEST(MemoryLeakWarningThreadSafe, turnOnThreadSafeNewDeleteOverloads)
{
#undef new
int storedAmountOfLeaks = MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all);
MemoryLeakWarningPlugin::turnOnThreadSafeNewDeleteOverloads();
int *n = new int;
int *n_nothrow = new (std::nothrow) int;
char *str = new char[20];
char *str_nothrow = new (std::nothrow) char[20];
LONGS_EQUAL(storedAmountOfLeaks + 4, MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all));
CHECK_EQUAL(4, mutexLockCount);
CHECK_EQUAL(4, mutexUnlockCount);
delete [] str_nothrow;
delete [] str;
delete n;
delete n_nothrow;
LONGS_EQUAL(storedAmountOfLeaks, MemoryLeakWarningPlugin::getGlobalDetector()->totalMemoryLeaks(mem_leak_period_all));
CHECK_EQUAL(8, mutexLockCount);
CHECK_EQUAL(8, mutexUnlockCount);
MemoryLeakWarningPlugin::turnOnNewDeleteOverloads();
#ifdef CPPUTEST_USE_NEW_MACROS
#include "CppUTest/MemoryLeakDetectorNewMacros.h"
#endif
}
#endif
#endif
#endif
<|endoftext|> |
<commit_before><commit_msg>Leetcode P263<commit_after><|endoftext|> |
<commit_before>// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //
//! @file
#ifndef DO_IMAGEPROCESSING_INTERPOLATION_HPP
#define DO_IMAGEPROCESSING_INTERPOLATION_HPP
#include <stdexcept>
namespace DO {
/*!
\ingroup ImageProcessing
\defgroup Interpolation Interpolation
@{
*/
// ====================================================================== //
// Interpolation
//! \brief Interpolation function
template <typename T, int N, typename F>
typename ColorTraits<T>::Color64f interpolate(const Image<T,N>& image,
const Matrix<F, N, 1>& pos)
{
DO_STATIC_ASSERT(
!std::numeric_limits<F>::is_integer,
INTERPOLATION_NOT_ALLOWED_FROM_VECTOR_WITH_INTEGRAL_SCALAR_TYPE);
Matrix<F, N, 1> a, b;
a.setZero();
b = image.sizes().template cast<F>() - Matrix<F, N, 1>::Ones();
if ((pos - a).minCoeff() < 0 || (b - pos).minCoeff() <= 0)
throw std::range_error("Cannot interpolate: position is out of range");
Matrix<int, N, 1> start, end;
Matrix<F, N, 1> frac;
for (int i = 0; i < N; ++i)
{
double ith_int_part;
frac[i] = std::modf(pos[i], &ith_int_part);
start[i] = static_cast<int>(ith_int_part);
}
end.array() = start.array() + 2;
typedef typename ColorTraits<T>::Color64f Col64f;
typedef typename Image<T, N>::const_subrange_iterator CSubrangeIterator;
Col64f val(ColorTraits<Col64f>::zero());
CSubrangeIterator it(image.begin_subrange(start, end));
static const int num_times = 1 << N;
for (int i = 0; i < num_times; ++i, ++it)
{
double weight = 1.;
for (int i = 0; i < N; ++i)
weight *= (it.position()[i] == start[i]) ? (1.-frac[i]) : frac[i];
Col64f color;
convertColor(color, *it);
val += color*weight;
}
return val;
}
}
#endif /* DO_IMAGEPROCESSING_INTERPOLATION_HPP */<commit_msg>Fix interpolation function.<commit_after>// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //
//! @file
#ifndef DO_IMAGEPROCESSING_INTERPOLATION_HPP
#define DO_IMAGEPROCESSING_INTERPOLATION_HPP
#include <stdexcept>
#include <DO/Core/Image.hpp>
#include <DO/Core/Pixel/PixelTraits.hpp>
namespace DO {
/*!
\ingroup ImageProcessing
\defgroup Interpolation Interpolation
@{
*/
// ====================================================================== //
// Interpolation
//! \brief Interpolation function
template <typename T, int N>
typename PixelTraits<T>::template Cast<double>::pixel_type
interpolate(const Image<T, N>& image, const Matrix<double, N, 1>& pos)
{
typedef typename PixelTraits<T>::template Cast<double>::pixel_type
pixel_type;
typedef typename Image<T, N>::const_subarray_iterator
const_subarray_iterator;
Matrix<double, N, 1> a, b;
a.setZero();
b = image.sizes().template cast<double>() - Matrix<double, N, 1>::Ones();
if ((pos - a).minCoeff() < 0 || (b - pos).minCoeff() <= 0)
throw std::range_error("Cannot interpolate: position is out of range");
Matrix<int, N, 1> start, end;
Matrix<double, N, 1> frac;
for (int i = 0; i < N; ++i)
{
double ith_int_part;
frac[i] = std::modf(pos[i], &ith_int_part);
start[i] = static_cast<int>(ith_int_part);
}
end.array() = start.array() + 2;
pixel_type value(color_min_value<pixel_type>());
const_subarray_iterator it(image.begin_subrange(start, end));
const_subarray_iterator it_end(image.end_subrange());
for ( ; it != it_end; ++it)
{
double weight = 1.;
for (int i = 0; i < N; ++i)
weight *= (it.position()[i] == start[i]) ? (1.-frac[i]) : frac[i];
pixel_type color;
convert_channel(*it, color);
value += weight*color;
}
return value;
}
}
#endif /* DO_IMAGEPROCESSING_INTERPOLATION_HPP */<|endoftext|> |
<commit_before>#include "SingleSampleAnalysisDialog.h"
#include <QInputDialog>
#include <QMessageBox>
#include <Settings.h>
#include <QPlainTextEdit>
#include <ProcessedSampleSelector.h>
#include "GUIHelper.h"
#include "ProcessedSampleWidget.h"
#include "GlobalServiceProvider.h"
SingleSampleAnalysisDialog::SingleSampleAnalysisDialog(QWidget *parent)
: QDialog(parent)
, ui_()
, db_()
, samples_()
{
ui_.setupUi(this);
initTable(ui_.samples_table);
connect(ui_.annotate_only, SIGNAL(stateChanged(int)), this, SLOT(annotate_only_state_changed()));
}
void SingleSampleAnalysisDialog::setAnalysisSteps()
{
// load and display correct analysis steps
if (steps_.size() == 0 && samples_.size() > 0)
{
if (analysis_type_ == "cfDNA")
{
steps_ = loadSteps("analysis_steps_cfdna");
}
else if (analysis_type_ == "RNA")
{
steps_ = loadSteps("analysis_steps_single_sample_rna");
}
else if (analysis_type_.startsWith("DNA"))
{
steps_ = loadSteps("analysis_steps_single_sample");
}
else
{
THROW(NotImplementedException, "Invalid analysis type '" + analysis_type_ + "'!");
}
// set correct steps
addStepsToParameters(steps_, qobject_cast<QFormLayout*>(ui_.param_group->layout()));
}
updateSampleTable();
updateStartButton();
}
void SingleSampleAnalysisDialog::setSamples(QList<AnalysisJobSample> samples)
{
// add samples
foreach(AnalysisJobSample sample, samples)
{
addSample(sample.info, sample.name);
}
setAnalysisSteps();
}
QList<AnalysisJobSample> SingleSampleAnalysisDialog::samples() const
{
return samples(samples_);
}
QStringList SingleSampleAnalysisDialog::arguments() const
{
return arguments(this);
}
bool SingleSampleAnalysisDialog::highPriority() const
{
return ui_.high_priority->isChecked();
}
QString SingleSampleAnalysisDialog::addSample(NGSD& db, QString status, QList<SampleDetails>& samples, QString& analysis_type, QString ps_name, bool throw_if_bam_missing, bool force_showing_dialog)
{
status = status.trimmed();
//get sample name if unset
if (force_showing_dialog || ps_name.isEmpty())
{
ProcessedSampleSelector dlg(QApplication::activeWindow(), false);
dlg.setLabel(status.isEmpty() ? "Processed sample:" : status + ":");
dlg.setSelection(ps_name);
if (dlg.exec())
{
ps_name = dlg.processedSampleName();
}
}
if (ps_name.isEmpty()) return "";
//check NGSD data
QString ps_id = db.processedSampleId(ps_name);
//check if sample fits to the selected analysis type
QString sample_type = db.getSampleData(db.sampleId(ps_name)).type;
if (sample_type.startsWith("DNA (")) sample_type = "DNA"; //convert "DNA (amplicon)" and "DNA (native)" to "DNA"
if (analysis_type.isEmpty())
{
//set analysis type based on the first sample
analysis_type = sample_type;
}
else
{
//check if sample have the same type as the widget
if (analysis_type != sample_type)
{
THROW(ArgumentException, "Sample " + ps_name + " doesn't match previously determined analysis typ (" + analysis_type + ")!");
}
}
//check BAM file exists
if (throw_if_bam_missing)
{
QString bam = GlobalServiceProvider::database().processedSamplePath(ps_id, PathType::BAM).filename;
if (!QFile::exists(bam))
{
THROW(FileAccessException, "Sample BAM file does not exist: '" + bam);
}
}
//add sample
ProcessedSampleData processed_sample_data = db.getProcessedSampleData(ps_id);
QString s_id = db.sampleId(ps_name);
SampleData sample_data = db.getSampleData(s_id);
samples.append(SampleDetails {ps_name, processed_sample_data.processing_system, status, processed_sample_data.quality, processed_sample_data.gender, sample_data.disease_group, sample_data.disease_status});
return ps_id;
}
void SingleSampleAnalysisDialog::initTable(QTableWidget* samples_table)
{
samples_table->clear();
samples_table->setColumnCount(7);
samples_table->setHorizontalHeaderItem(0, new QTableWidgetItem("processed sample"));
samples_table->setHorizontalHeaderItem(1, new QTableWidgetItem("status"));
samples_table->setHorizontalHeaderItem(2, new QTableWidgetItem("quality"));
samples_table->setHorizontalHeaderItem(3, new QTableWidgetItem("processing system"));
samples_table->setHorizontalHeaderItem(4, new QTableWidgetItem("gender"));
samples_table->setHorizontalHeaderItem(5, new QTableWidgetItem("disease group"));
samples_table->setHorizontalHeaderItem(6, new QTableWidgetItem("disease status"));
}
void SingleSampleAnalysisDialog::updateSampleTable(const QList<SampleDetails>& samples, QTableWidget* samples_table)
{
samples_table->clearContents();
samples_table->setRowCount(samples.count());
for (int i=0; i<samples.count(); ++i)
{
samples_table->setItem(i, 0, new QTableWidgetItem(samples[i].name));
samples_table->setItem(i, 1, new QTableWidgetItem(samples[i].status));
QLabel* quality_label = new QLabel();
quality_label->setAlignment(Qt::AlignLeft|Qt::AlignVCenter);
quality_label->setMargin(1);
ProcessedSampleWidget::styleQualityLabel(quality_label, samples[i].quality);
samples_table->setCellWidget(i, 2, quality_label);
samples_table->setItem(i, 3, new QTableWidgetItem(samples[i].system));
samples_table->setItem(i, 4, new QTableWidgetItem(samples[i].gender));
samples_table->setItem(i, 5, new QTableWidgetItem(samples[i].disease_group));
samples_table->setItem(i, 6, new QTableWidgetItem(samples[i].disease_status));
}
GUIHelper::resizeTableCells(samples_table);
}
QList<AnalysisJobSample> SingleSampleAnalysisDialog::samples(const QList<SampleDetails>& samples)
{
QList<AnalysisJobSample> output;
foreach(const SampleDetails& info, samples)
{
output << AnalysisJobSample { info.name, info.status };
}
return output;
}
QList<AnalysisStep> SingleSampleAnalysisDialog::loadSteps(QString ini_name)
{
QList<AnalysisStep> output;
QStringList tmp = Settings::stringList(ini_name);
foreach(QString step, tmp)
{
int index = step.indexOf("-");
output << AnalysisStep { step.left(index).trimmed(), step.mid(index+1).trimmed() };
}
return output;
}
void SingleSampleAnalysisDialog::addStepsToParameters(QList<AnalysisStep> steps, QFormLayout* layout)
{
if (steps.count()<2) return;
bool first_step = true;
foreach(AnalysisStep step, steps)
{
QLabel* label = nullptr;
if (first_step)
{
label = new QLabel("analysis steps:");
first_step = false;
}
QCheckBox* box = new QCheckBox(step.description);
box->setObjectName("step_" + step.name);
box->setChecked(true);
layout->addRow(label, box);
}
}
QStringList SingleSampleAnalysisDialog::arguments(const QWidget* widget)
{
QStringList output;
QLineEdit* custom = widget->findChild<QLineEdit*>("custom_args");
if (custom!=nullptr && !custom->text().isEmpty())
{
output << custom->text();
}
QCheckBox* anno_only = widget->findChild<QCheckBox*>("annotate_only");
if (anno_only!=nullptr && anno_only->isChecked()) output << "-annotation_only";
QStringList steps;
QList<QCheckBox*> step_boxes = widget->findChildren<QCheckBox*>(QRegExp("^step_"));
if (step_boxes.count()>0)
{
foreach(QCheckBox* box, step_boxes)
{
if (box->isChecked())
{
steps << box->objectName().mid(5);
}
}
// do not set "-steps" parameter if no steps are checked
if (steps.size() > 0) output << "-steps " + steps.join(",");
}
return output;
}
void SingleSampleAnalysisDialog::on_add_sample_clicked(bool)
{
addSample("");
updateSampleTable();
updateStartButton();
}
void SingleSampleAnalysisDialog::on_add_batch_clicked(bool)
{
//edit
QPlainTextEdit* edit = new QPlainTextEdit(this);
auto dlg = GUIHelper::createDialog(edit, "Enter processed samples (one per line).", "", true);
if (dlg->exec()==QDialog::Accepted)
{
QStringList samples = edit->toPlainText().split('\n');
foreach(QString sample, samples)
{
sample = sample.trimmed();
if (sample.contains("\t")) sample = sample.split("\t").first();
if (sample.isEmpty() || sample[0]=='#') continue;
addSample("", sample);
}
updateSampleTable();
updateStartButton();
}
}
void SingleSampleAnalysisDialog::on_clear_clicked(bool)
{
samples_.clear();
updateSampleTable();
updateStartButton();
}
void SingleSampleAnalysisDialog::updateStartButton()
{
ui_.start_button->setEnabled(samples_.count()>=1);
}
void SingleSampleAnalysisDialog::annotate_only_state_changed()
{
// get all step check boxes
QList<QCheckBox*> step_boxes = this->findChildren<QCheckBox*>(QRegExp("^step_"));
if(ui_.annotate_only->isChecked())
{
foreach (QCheckBox* step, step_boxes)
{
// deactivate mapping/db import check box
if ((step->objectName() == "step_ma") || (step->objectName() == "step_db"))
{
step->setChecked(false);
}
// activate vc, cn and sv by default
if ((step->objectName() == "step_vc") || (step->objectName() == "step_cn") || (step->objectName() == "step_sv"))
{
step->setChecked(true);
}
}
}
}
void SingleSampleAnalysisDialog::addSample(QString status, QString sample)
{
try
{
addSample(db_, status, samples_, analysis_type_, sample, false);
}
catch(const Exception& e)
{
QMessageBox::warning(this, "Error adding sample", e.message());
samples_.clear();
}
setAnalysisSteps();
}
void SingleSampleAnalysisDialog::updateSampleTable()
{
updateSampleTable(samples_, ui_.samples_table);
}
<commit_msg>GSvar: fixed bug in single sample analysis dialog<commit_after>#include "SingleSampleAnalysisDialog.h"
#include <QInputDialog>
#include <QMessageBox>
#include <Settings.h>
#include <QPlainTextEdit>
#include <ProcessedSampleSelector.h>
#include "GUIHelper.h"
#include "ProcessedSampleWidget.h"
#include "GlobalServiceProvider.h"
SingleSampleAnalysisDialog::SingleSampleAnalysisDialog(QWidget *parent)
: QDialog(parent)
, ui_()
, db_()
, samples_()
{
ui_.setupUi(this);
initTable(ui_.samples_table);
connect(ui_.annotate_only, SIGNAL(stateChanged(int)), this, SLOT(annotate_only_state_changed()));
}
void SingleSampleAnalysisDialog::setAnalysisSteps()
{
// load and display correct analysis steps
if (steps_.size() == 0 && samples_.size() > 0)
{
if (analysis_type_ == "cfDNA")
{
steps_ = loadSteps("analysis_steps_cfdna");
}
else if (analysis_type_ == "RNA")
{
steps_ = loadSteps("analysis_steps_single_sample_rna");
}
else if (analysis_type_.startsWith("DNA"))
{
steps_ = loadSteps("analysis_steps_single_sample");
}
else
{
THROW(NotImplementedException, "Invalid analysis type '" + analysis_type_ + "'!");
}
// set correct steps
addStepsToParameters(steps_, qobject_cast<QFormLayout*>(ui_.param_group->layout()));
}
updateSampleTable();
updateStartButton();
}
void SingleSampleAnalysisDialog::setSamples(QList<AnalysisJobSample> samples)
{
// add samples
foreach(AnalysisJobSample sample, samples)
{
addSample(sample.info, sample.name);
}
setAnalysisSteps();
}
QList<AnalysisJobSample> SingleSampleAnalysisDialog::samples() const
{
return samples(samples_);
}
QStringList SingleSampleAnalysisDialog::arguments() const
{
return arguments(this);
}
bool SingleSampleAnalysisDialog::highPriority() const
{
return ui_.high_priority->isChecked();
}
QString SingleSampleAnalysisDialog::addSample(NGSD& db, QString status, QList<SampleDetails>& samples, QString& analysis_type, QString ps_name, bool throw_if_bam_missing, bool force_showing_dialog)
{
status = status.trimmed();
//get sample name if unset
if (force_showing_dialog || ps_name.isEmpty())
{
ProcessedSampleSelector dlg(QApplication::activeWindow(), false);
dlg.setLabel(status.isEmpty() ? "Processed sample:" : status + ":");
dlg.setSelection(ps_name);
if (dlg.exec())
{
ps_name = dlg.processedSampleName();
}
}
if (ps_name.isEmpty()) return "";
//check NGSD data
QString ps_id = db.processedSampleId(ps_name);
//check if sample fits to the selected analysis type
QString sample_type = db.getSampleData(db.sampleId(ps_name)).type;
if (sample_type.startsWith("DNA (")) sample_type = "DNA"; //convert "DNA (amplicon)" and "DNA (native)" to "DNA"
if (analysis_type.isEmpty())
{
//set analysis type based on the first sample
analysis_type = sample_type;
}
else
{
//check if sample have the same type as the widget
if (analysis_type != sample_type)
{
THROW(ArgumentException, "Sample " + ps_name + " doesn't match previously determined analysis typ (" + analysis_type + ")!");
}
}
//check BAM file exists
if (throw_if_bam_missing)
{
FileLocation bam_file = GlobalServiceProvider::database().processedSamplePath(ps_id, PathType::BAM);
if (!bam_file.exists)
{
THROW(FileAccessException, "Sample BAM file does not exist: '" + bam_file.filename);
}
}
//add sample
ProcessedSampleData processed_sample_data = db.getProcessedSampleData(ps_id);
QString s_id = db.sampleId(ps_name);
SampleData sample_data = db.getSampleData(s_id);
samples.append(SampleDetails {ps_name, processed_sample_data.processing_system, status, processed_sample_data.quality, processed_sample_data.gender, sample_data.disease_group, sample_data.disease_status});
return ps_id;
}
void SingleSampleAnalysisDialog::initTable(QTableWidget* samples_table)
{
samples_table->clear();
samples_table->setColumnCount(7);
samples_table->setHorizontalHeaderItem(0, new QTableWidgetItem("processed sample"));
samples_table->setHorizontalHeaderItem(1, new QTableWidgetItem("status"));
samples_table->setHorizontalHeaderItem(2, new QTableWidgetItem("quality"));
samples_table->setHorizontalHeaderItem(3, new QTableWidgetItem("processing system"));
samples_table->setHorizontalHeaderItem(4, new QTableWidgetItem("gender"));
samples_table->setHorizontalHeaderItem(5, new QTableWidgetItem("disease group"));
samples_table->setHorizontalHeaderItem(6, new QTableWidgetItem("disease status"));
}
void SingleSampleAnalysisDialog::updateSampleTable(const QList<SampleDetails>& samples, QTableWidget* samples_table)
{
samples_table->clearContents();
samples_table->setRowCount(samples.count());
for (int i=0; i<samples.count(); ++i)
{
samples_table->setItem(i, 0, new QTableWidgetItem(samples[i].name));
samples_table->setItem(i, 1, new QTableWidgetItem(samples[i].status));
QLabel* quality_label = new QLabel();
quality_label->setAlignment(Qt::AlignLeft|Qt::AlignVCenter);
quality_label->setMargin(1);
ProcessedSampleWidget::styleQualityLabel(quality_label, samples[i].quality);
samples_table->setCellWidget(i, 2, quality_label);
samples_table->setItem(i, 3, new QTableWidgetItem(samples[i].system));
samples_table->setItem(i, 4, new QTableWidgetItem(samples[i].gender));
samples_table->setItem(i, 5, new QTableWidgetItem(samples[i].disease_group));
samples_table->setItem(i, 6, new QTableWidgetItem(samples[i].disease_status));
}
GUIHelper::resizeTableCells(samples_table);
}
QList<AnalysisJobSample> SingleSampleAnalysisDialog::samples(const QList<SampleDetails>& samples)
{
QList<AnalysisJobSample> output;
foreach(const SampleDetails& info, samples)
{
output << AnalysisJobSample { info.name, info.status };
}
return output;
}
QList<AnalysisStep> SingleSampleAnalysisDialog::loadSteps(QString ini_name)
{
QList<AnalysisStep> output;
QStringList tmp = Settings::stringList(ini_name);
foreach(QString step, tmp)
{
int index = step.indexOf("-");
output << AnalysisStep { step.left(index).trimmed(), step.mid(index+1).trimmed() };
}
return output;
}
void SingleSampleAnalysisDialog::addStepsToParameters(QList<AnalysisStep> steps, QFormLayout* layout)
{
if (steps.count()<2) return;
bool first_step = true;
foreach(AnalysisStep step, steps)
{
QLabel* label = nullptr;
if (first_step)
{
label = new QLabel("analysis steps:");
first_step = false;
}
QCheckBox* box = new QCheckBox(step.description);
box->setObjectName("step_" + step.name);
box->setChecked(true);
layout->addRow(label, box);
}
}
QStringList SingleSampleAnalysisDialog::arguments(const QWidget* widget)
{
QStringList output;
QLineEdit* custom = widget->findChild<QLineEdit*>("custom_args");
if (custom!=nullptr && !custom->text().isEmpty())
{
output << custom->text();
}
QCheckBox* anno_only = widget->findChild<QCheckBox*>("annotate_only");
if (anno_only!=nullptr && anno_only->isChecked()) output << "-annotation_only";
QStringList steps;
QList<QCheckBox*> step_boxes = widget->findChildren<QCheckBox*>(QRegExp("^step_"));
if (step_boxes.count()>0)
{
foreach(QCheckBox* box, step_boxes)
{
if (box->isChecked())
{
steps << box->objectName().mid(5);
}
}
// do not set "-steps" parameter if no steps are checked
if (steps.size() > 0) output << "-steps " + steps.join(",");
}
return output;
}
void SingleSampleAnalysisDialog::on_add_sample_clicked(bool)
{
addSample("");
updateSampleTable();
updateStartButton();
}
void SingleSampleAnalysisDialog::on_add_batch_clicked(bool)
{
//edit
QPlainTextEdit* edit = new QPlainTextEdit(this);
auto dlg = GUIHelper::createDialog(edit, "Enter processed samples (one per line).", "", true);
if (dlg->exec()==QDialog::Accepted)
{
QStringList samples = edit->toPlainText().split('\n');
foreach(QString sample, samples)
{
sample = sample.trimmed();
if (sample.contains("\t")) sample = sample.split("\t").first();
if (sample.isEmpty() || sample[0]=='#') continue;
addSample("", sample);
}
updateSampleTable();
updateStartButton();
}
}
void SingleSampleAnalysisDialog::on_clear_clicked(bool)
{
samples_.clear();
updateSampleTable();
updateStartButton();
}
void SingleSampleAnalysisDialog::updateStartButton()
{
ui_.start_button->setEnabled(samples_.count()>=1);
}
void SingleSampleAnalysisDialog::annotate_only_state_changed()
{
// get all step check boxes
QList<QCheckBox*> step_boxes = this->findChildren<QCheckBox*>(QRegExp("^step_"));
if(ui_.annotate_only->isChecked())
{
foreach (QCheckBox* step, step_boxes)
{
// deactivate mapping/db import check box
if ((step->objectName() == "step_ma") || (step->objectName() == "step_db"))
{
step->setChecked(false);
}
// activate vc, cn and sv by default
if ((step->objectName() == "step_vc") || (step->objectName() == "step_cn") || (step->objectName() == "step_sv"))
{
step->setChecked(true);
}
}
}
}
void SingleSampleAnalysisDialog::addSample(QString status, QString sample)
{
try
{
addSample(db_, status, samples_, analysis_type_, sample, false);
}
catch(const Exception& e)
{
QMessageBox::warning(this, "Error adding sample", e.message());
samples_.clear();
}
setAnalysisSteps();
}
void SingleSampleAnalysisDialog::updateSampleTable()
{
updateSampleTable(samples_, ui_.samples_table);
}
<|endoftext|> |
<commit_before>#include "Logger.hpp"
#include <QString>
#include <boost/foreach.hpp>
using namespace std;
using namespace Packet;
Logger::Logger()
{
_history.resize(100000, 0);
_nextFrameNumber = 0;
_spaceUsed = sizeof(_history[0]) * _history.size();
}
bool Logger::open(QString filename)
{
QMutexLocker locker(&_mutex);
_file.open((const char *)filename.toAscii(), ofstream::out);
return _file.is_open();
}
void Logger::close()
{
QMutexLocker locker(&_mutex);
_file.close();
}
void Logger::addFrame(const LogFrame& frame)
{
QMutexLocker locker(&_mutex);
// Write this from to the file
if (_file.is_open())
{
if (frame.IsInitialized())
{
frame.SerializeToOstream(&_file);
} else {
vector<string> errors;
frame.FindInitializationErrors(&errors);
printf("Logger: Not writing frame missing fields:");
BOOST_FOREACH(const string &str, errors)
{
printf(" %s", str.c_str());
}
printf("\n");
}
}
// Get the place in the circular buffer where we will store this frame
int i = _nextFrameNumber % _history.size();
if (_history[i])
{
// Remove the space used by the old data
_spaceUsed -= _history[i]->SpaceUsed();
} else {
// Create a new LogFrame
_history[i] = new LogFrame();
}
// Store the frame
_history[i]->CopyFrom(frame);
// Add space used by the new data
_spaceUsed += _history[i]->SpaceUsed();
// Go to the next frame
++_nextFrameNumber;
}
bool Logger::getFrame(int i, LogFrame& frame)
{
QMutexLocker locker(&_mutex);
if (i < 0 || i < (_nextFrameNumber - (int)_history.size()) || i >= _nextFrameNumber)
{
// Frame number is out of range
return false;
}
frame.CopyFrom(*_history[i % _history.size()]);
return true;
}
int Logger::getFrames(int start, vector<LogFrame> &frames)
{
QMutexLocker locker(&_mutex);
int minFrame = _nextFrameNumber - (int)_history.size();
if (minFrame < 0)
{
minFrame = 0;
}
if (start < minFrame || start >= _nextFrameNumber)
{
return 0;
}
int end = start - frames.size() + 1;
if (end < minFrame)
{
end = minFrame;
}
int n = start - end + 1;
for (int i = 0; i < n; ++i)
{
frames[i].CopyFrom(*_history[(start - i) % _history.size()]);
}
return n;
}
<commit_msg>Logger::getFrames() clears frames that couldn't be read. This bug was leaving stale data in the field view near the beginning of log data.<commit_after>#include "Logger.hpp"
#include <QString>
#include <boost/foreach.hpp>
using namespace std;
using namespace Packet;
Logger::Logger()
{
_history.resize(100000, 0);
_nextFrameNumber = 0;
_spaceUsed = sizeof(_history[0]) * _history.size();
}
bool Logger::open(QString filename)
{
QMutexLocker locker(&_mutex);
_file.open((const char *)filename.toAscii(), ofstream::out);
return _file.is_open();
}
void Logger::close()
{
QMutexLocker locker(&_mutex);
_file.close();
}
void Logger::addFrame(const LogFrame& frame)
{
QMutexLocker locker(&_mutex);
// Write this from to the file
if (_file.is_open())
{
if (frame.IsInitialized())
{
frame.SerializeToOstream(&_file);
} else {
vector<string> errors;
frame.FindInitializationErrors(&errors);
printf("Logger: Not writing frame missing fields:");
BOOST_FOREACH(const string &str, errors)
{
printf(" %s", str.c_str());
}
printf("\n");
}
}
// Get the place in the circular buffer where we will store this frame
int i = _nextFrameNumber % _history.size();
if (_history[i])
{
// Remove the space used by the old data
_spaceUsed -= _history[i]->SpaceUsed();
} else {
// Create a new LogFrame
_history[i] = new LogFrame();
}
// Store the frame
_history[i]->CopyFrom(frame);
// Add space used by the new data
_spaceUsed += _history[i]->SpaceUsed();
// Go to the next frame
++_nextFrameNumber;
}
bool Logger::getFrame(int i, LogFrame& frame)
{
QMutexLocker locker(&_mutex);
if (i < 0 || i < (_nextFrameNumber - (int)_history.size()) || i >= _nextFrameNumber)
{
// Frame number is out of range
return false;
}
frame.CopyFrom(*_history[i % _history.size()]);
return true;
}
int Logger::getFrames(int start, vector<LogFrame> &frames)
{
QMutexLocker locker(&_mutex);
int minFrame = _nextFrameNumber - (int)_history.size();
if (minFrame < 0)
{
minFrame = 0;
}
if (start < minFrame || start >= _nextFrameNumber)
{
return 0;
}
int end = start - frames.size() + 1;
if (end < minFrame)
{
end = minFrame;
}
int n = start - end + 1;
for (int i = 0; i < n; ++i)
{
frames[i].CopyFrom(*_history[(start - i) % _history.size()]);
}
for (int i = n; i < (int)frames.size(); ++i)
{
frames[i].Clear();
}
return n;
}
<|endoftext|> |
<commit_before>// SPDX-License-Identifier: BSD-3-Clause
// Copyright Contributors to the OpenColorIO Project.
#include <algorithm>
#include <OpenColorIO/OpenColorIO.h>
#include "GpuShaderUtils.h"
#include "MathUtils.h"
#include "ops/lut3d/Lut3DOpGPU.h"
#include "utils/StringUtils.h"
namespace OCIO_NAMESPACE
{
void GetLut3DGPUShaderProgram(GpuShaderCreatorRcPtr & shaderCreator, ConstLut3DOpDataRcPtr & lutData)
{
if (shaderCreator->getLanguage() == LANGUAGE_OSL_1)
{
throw Exception("The Lut3DOp is not yet supported by the 'Open Shading language (OSL)' translation");
}
std::ostringstream resName;
resName << shaderCreator->getResourcePrefix()
<< std::string("_")
<< std::string("lut3d_")
<< shaderCreator->getNextResourceIndex();
// Note: Remove potentially problematic double underscores from GLSL resource names.
std::string name(resName.str());
StringUtils::ReplaceInPlace(name, "__", "_");
// (Using CacheID here to potentially allow reuse of existing textures.)
shaderCreator->add3DTexture(name.c_str(),
GpuShaderText::getSamplerName(name).c_str(),
lutData->getGridSize(),
lutData->getConcreteInterpolation(),
&lutData->getArray()[0]);
{
GpuShaderText ss(shaderCreator->getLanguage());
ss.declareTex3D(name);
shaderCreator->addToDeclareShaderCode(ss.string().c_str());
}
const float dim = (float)lutData->getGridSize();
// incr = 1/dim (amount needed to increment one index in the grid)
const float incr = 1.0f / dim;
{
GpuShaderText ss(shaderCreator->getLanguage());
ss.indent();
ss.newLine() << "";
ss.newLine() << "// Add LUT 3D processing for " << name;
ss.newLine() << "";
// Tetrahedral interpolation
// The strategy is to use texture3d lookups with GL_NEAREST to fetch the
// 4 corners of the cube (v1,v2,v3,v4), compute the 4 barycentric weights
// (f1,f2,f3,f4), and then perform the interpolation manually.
// One side benefit of this is that we are not subject to the 8-bit
// quantization of the fractional weights that happens using GL_LINEAR.
if (lutData->getConcreteInterpolation() == INTERP_TETRAHEDRAL)
{
ss.newLine() << "{";
ss.indent();
ss.newLine() << ss.float3Decl("coords") << " = "
<< shaderCreator->getPixelName() << ".rgb * "
<< ss.float3Const(dim - 1) << "; ";
// baseInd is on [0,dim-1]
ss.newLine() << ss.float3Decl("baseInd") << " = floor(coords);";
// frac is on [0,1]
ss.newLine() << ss.float3Decl("frac") << " = coords - baseInd;";
// scale/offset baseInd onto [0,1] as usual for doing texture lookups
// we use zyx to flip the order since blue varies most rapidly
// in the grid array ordering
ss.newLine() << ss.float3Decl("f1, f4") << ";";
ss.newLine() << "baseInd = ( baseInd.zyx + " << ss.float3Const(0.5f) << " ) / " << ss.float3Const(dim) << ";";
ss.newLine() << ss.float3Decl("v1") << " = " << ss.sampleTex3D(name, "baseInd") << ".rgb;";
ss.newLine() << ss.float3Decl("nextInd") << " = baseInd + " << ss.float3Const(incr) << ";";
ss.newLine() << ss.float3Decl("v4") << " = " << ss.sampleTex3D(name, "nextInd") << ".rgb;";
ss.newLine() << "if (frac.r >= frac.g)";
ss.newLine() << "{";
ss.indent();
ss.newLine() << "if (frac.g >= frac.b)"; // R > G > B
ss.newLine() << "{";
ss.indent();
// Note that compared to the CPU version of the algorithm,
// we increment in inverted order since baseInd & nextInd
// are essentially BGR rather than RGB.
ss.newLine() << "nextInd = baseInd + " << ss.float3Const(0.0f, 0.0f, incr) << ";";
ss.newLine() << ss.float3Decl("v2") << " = " << ss.sampleTex3D(name, "nextInd") << ".rgb;";
ss.newLine() << "nextInd = baseInd + " << ss.float3Const(0.0f, incr, incr) << ";";
ss.newLine() << ss.float3Decl("v3") << " = " << ss.sampleTex3D(name, "nextInd") << ".rgb;";
ss.newLine() << "f1 = " << ss.float3Const("1. - frac.r") << ";";
ss.newLine() << "f4 = " << ss.float3Const("frac.b") << ";";
ss.newLine() << ss.float3Decl("f2") << " = " << ss.float3Const("frac.r - frac.g") << ";";
ss.newLine() << ss.float3Decl("f3") << " = " << ss.float3Const("frac.g - frac.b") << ";";
ss.newLine() << shaderCreator->getPixelName() << ".rgb = (f2 * v2) + (f3 * v3);";
ss.dedent();
ss.newLine() << "}";
ss.newLine() << "else if (frac.r >= frac.b)"; // R > B > G
ss.newLine() << "{";
ss.indent();
ss.newLine() << "nextInd = baseInd + " << ss.float3Const(0.0f, 0.0f, incr) << ";";
ss.newLine() << ss.float3Decl("v2") << " = " << ss.sampleTex3D(name, "nextInd") << ".rgb;";
ss.newLine() << "nextInd = baseInd + " << ss.float3Const(incr, 0.0f, incr) << ";";
ss.newLine() << ss.float3Decl("v3") << " = " << ss.sampleTex3D(name, "nextInd") << ".rgb;";
ss.newLine() << "f1 = " << ss.float3Const("1. - frac.r") << ";";
ss.newLine() << "f4 = " << ss.float3Const("frac.g") << ";";
ss.newLine() << ss.float3Decl("f2") << " = " << ss.float3Const("frac.r - frac.b") << ";";
ss.newLine() << ss.float3Decl("f3") << " = " << ss.float3Const("frac.b - frac.g") << ";";
ss.newLine() << shaderCreator->getPixelName() << ".rgb = (f2 * v2) + (f3 * v3);";
ss.dedent();
ss.newLine() << "}";
ss.newLine() << "else"; // B > R > G
ss.newLine() << "{";
ss.indent();
ss.newLine() << "nextInd = baseInd + " << ss.float3Const(incr, 0.0f, 0.0f) << ";";
ss.newLine() << ss.float3Decl("v2") << " = " << ss.sampleTex3D(name, "nextInd") << ".rgb;";
ss.newLine() << "nextInd = baseInd + " << ss.float3Const(incr, 0.0f, incr) << ";";
ss.newLine() << ss.float3Decl("v3") << " = " << ss.sampleTex3D(name, "nextInd") << ".rgb;";
ss.newLine() << "f1 = " << ss.float3Const("1. - frac.b") << ";";
ss.newLine() << "f4 = " << ss.float3Const("frac.g") << ";";
ss.newLine() << ss.float3Decl("f2") << " = " << ss.float3Const("frac.b - frac.r") << ";";
ss.newLine() << ss.float3Decl("f3") << " = " << ss.float3Const("frac.r - frac.g") << ";";
ss.newLine() << shaderCreator->getPixelName() << ".rgb = (f2 * v2) + (f3 * v3);";
ss.dedent();
ss.newLine() << "}";
ss.dedent();
ss.newLine() << "}";
ss.newLine() << "else";
ss.newLine() << "{";
ss.indent();
ss.newLine() << "if (frac.g <= frac.b)"; // B > G > R
ss.newLine() << "{";
ss.indent();
ss.newLine() << "nextInd = baseInd + " << ss.float3Const(incr, 0.0f, 0.0f) << ";";
ss.newLine() << ss.float3Decl("v2") << " = " << ss.sampleTex3D(name, "nextInd") << ".rgb;";
ss.newLine() << "nextInd = baseInd + " << ss.float3Const(incr, incr, 0.0f) << ";";
ss.newLine() << ss.float3Decl("v3") << " = " << ss.sampleTex3D(name, "nextInd") << ".rgb;";
ss.newLine() << "f1 = " << ss.float3Const("1. - frac.b") << ";";
ss.newLine() << "f4 = " << ss.float3Const("frac.r") << ";";
ss.newLine() << ss.float3Decl("f2") << " = " << ss.float3Const("frac.b - frac.g") << ";";
ss.newLine() << ss.float3Decl("f3") << " = " << ss.float3Const("frac.g - frac.r") << ";";
ss.newLine() << shaderCreator->getPixelName() << ".rgb = (f2 * v2) + (f3 * v3);";
ss.dedent();
ss.newLine() << "}";
ss.newLine() << "else if (frac.r >= frac.b)"; // G > R > B
ss.newLine() << "{";
ss.indent();
ss.newLine() << "nextInd = baseInd + " << ss.float3Const(0.0f, incr, 0.0f) << ";";
ss.newLine() << ss.float3Decl("v2") << " = " << ss.sampleTex3D(name, "nextInd") << ".rgb;";
ss.newLine() << "nextInd = baseInd + " << ss.float3Const(0.0f, incr, incr) << ";";
ss.newLine() << ss.float3Decl("v3") << " = " << ss.sampleTex3D(name, "nextInd") << ".rgb;";
ss.newLine() << "f1 = " << ss.float3Const("1. - frac.g") << ";";
ss.newLine() << "f4 = " << ss.float3Const("frac.b") << ";";
ss.newLine() << ss.float3Decl("f2") << " = " << ss.float3Const("frac.g - frac.r") << ";";
ss.newLine() << ss.float3Decl("f3") << " = " << ss.float3Const("frac.r - frac.b") << ";";
ss.newLine() << shaderCreator->getPixelName() << ".rgb = (f2 * v2) + (f3 * v3);";
ss.dedent();
ss.newLine() << "}";
ss.newLine() << "else"; // G > B > R
ss.newLine() << "{";
ss.indent();
ss.newLine() << "nextInd = baseInd + " << ss.float3Const(0.0f, incr, 0.0f) << ";";
ss.newLine() << ss.float3Decl("v2") << " = " << ss.sampleTex3D(name, "nextInd") << ".rgb;";
ss.newLine() << "nextInd = baseInd + " << ss.float3Const(incr, incr, 0.0f) << ";";
ss.newLine() << ss.float3Decl("v3") << " = " << ss.sampleTex3D(name, "nextInd") << ".rgb;";
ss.newLine() << "f1 = " << ss.float3Const("1. - frac.g") << ";";
ss.newLine() << "f4 = " << ss.float3Const("frac.r") << ";";
ss.newLine() << ss.float3Decl("f2") << " = " << ss.float3Const("frac.g - frac.b") << ";";
ss.newLine() << ss.float3Decl("f3") << " = " << ss.float3Const("frac.b - frac.r") << ";";
ss.newLine() << shaderCreator->getPixelName() << ".rgb = (f2 * v2) + (f3 * v3);";
ss.dedent();
ss.newLine() << "}";
ss.dedent();
ss.newLine() << "}";
ss.newLine() << shaderCreator->getPixelName()
<< ".rgb = "
<< shaderCreator->getPixelName()
<< ".rgb + (f1 * v1) + (f4 * v4);";
ss.dedent();
ss.newLine() << "}";
}
else
{
// Trilinear interpolation
// Use texture3d and GL_LINEAR and the GPU's built-in trilinear algorithm.
// Note that the fractional components are quantized to 8-bits on some
// hardware, which introduces significant error with small grid sizes.
ss.newLine() << ss.float3Decl(name + "_coords")
<< " = (" << shaderCreator->getPixelName() << ".zyx * "
<< ss.float3Const(dim - 1) << " + "
<< ss.float3Const(0.5f) + ") / "
<< ss.float3Const(dim) << ";";
ss.newLine() << shaderCreator->getPixelName() << ".rgb = "
<< ss.sampleTex3D(name, name + "_coords") << ".rgb;";
}
shaderCreator->addToFunctionShaderCode(ss.string().c_str());
}
}
} // namespace OCIO_NAMESPACE
<commit_msg>Enforce GL_NEAREST with gpu tetrahedral interpolation, fixing #1676. (#1708)<commit_after>// SPDX-License-Identifier: BSD-3-Clause
// Copyright Contributors to the OpenColorIO Project.
#include <algorithm>
#include <OpenColorIO/OpenColorIO.h>
#include "GpuShaderUtils.h"
#include "MathUtils.h"
#include "ops/lut3d/Lut3DOpGPU.h"
#include "utils/StringUtils.h"
namespace OCIO_NAMESPACE
{
void GetLut3DGPUShaderProgram(GpuShaderCreatorRcPtr & shaderCreator, ConstLut3DOpDataRcPtr & lutData)
{
if (shaderCreator->getLanguage() == LANGUAGE_OSL_1)
{
throw Exception("The Lut3DOp is not yet supported by the 'Open Shading language (OSL)' translation");
}
std::ostringstream resName;
resName << shaderCreator->getResourcePrefix()
<< std::string("_")
<< std::string("lut3d_")
<< shaderCreator->getNextResourceIndex();
// Note: Remove potentially problematic double underscores from GLSL resource names.
std::string name(resName.str());
StringUtils::ReplaceInPlace(name, "__", "_");
Interpolation samplerInterpolation = lutData->getConcreteInterpolation();
// Enforce GL_NEAREST with shader-generated tetrahedral interpolation.
if (samplerInterpolation == INTERP_TETRAHEDRAL)
{
samplerInterpolation = INTERP_NEAREST;
}
// (Using CacheID here to potentially allow reuse of existing textures.)
shaderCreator->add3DTexture(name.c_str(),
GpuShaderText::getSamplerName(name).c_str(),
lutData->getGridSize(),
samplerInterpolation,
&lutData->getArray()[0]);
{
GpuShaderText ss(shaderCreator->getLanguage());
ss.declareTex3D(name);
shaderCreator->addToDeclareShaderCode(ss.string().c_str());
}
const float dim = (float)lutData->getGridSize();
// incr = 1/dim (amount needed to increment one index in the grid)
const float incr = 1.0f / dim;
{
GpuShaderText ss(shaderCreator->getLanguage());
ss.indent();
ss.newLine() << "";
ss.newLine() << "// Add LUT 3D processing for " << name;
ss.newLine() << "";
// Tetrahedral interpolation
// The strategy is to use texture3d lookups with GL_NEAREST to fetch the
// 4 corners of the cube (v1,v2,v3,v4), compute the 4 barycentric weights
// (f1,f2,f3,f4), and then perform the interpolation manually.
// One side benefit of this is that we are not subject to the 8-bit
// quantization of the fractional weights that happens using GL_LINEAR.
if (lutData->getConcreteInterpolation() == INTERP_TETRAHEDRAL)
{
ss.newLine() << "{";
ss.indent();
ss.newLine() << ss.float3Decl("coords") << " = "
<< shaderCreator->getPixelName() << ".rgb * "
<< ss.float3Const(dim - 1) << "; ";
// baseInd is on [0,dim-1]
ss.newLine() << ss.float3Decl("baseInd") << " = floor(coords);";
// frac is on [0,1]
ss.newLine() << ss.float3Decl("frac") << " = coords - baseInd;";
// scale/offset baseInd onto [0,1] as usual for doing texture lookups
// we use zyx to flip the order since blue varies most rapidly
// in the grid array ordering
ss.newLine() << ss.float3Decl("f1, f4") << ";";
ss.newLine() << "baseInd = ( baseInd.zyx + " << ss.float3Const(0.5f) << " ) / " << ss.float3Const(dim) << ";";
ss.newLine() << ss.float3Decl("v1") << " = " << ss.sampleTex3D(name, "baseInd") << ".rgb;";
ss.newLine() << ss.float3Decl("nextInd") << " = baseInd + " << ss.float3Const(incr) << ";";
ss.newLine() << ss.float3Decl("v4") << " = " << ss.sampleTex3D(name, "nextInd") << ".rgb;";
ss.newLine() << "if (frac.r >= frac.g)";
ss.newLine() << "{";
ss.indent();
ss.newLine() << "if (frac.g >= frac.b)"; // R > G > B
ss.newLine() << "{";
ss.indent();
// Note that compared to the CPU version of the algorithm,
// we increment in inverted order since baseInd & nextInd
// are essentially BGR rather than RGB.
ss.newLine() << "nextInd = baseInd + " << ss.float3Const(0.0f, 0.0f, incr) << ";";
ss.newLine() << ss.float3Decl("v2") << " = " << ss.sampleTex3D(name, "nextInd") << ".rgb;";
ss.newLine() << "nextInd = baseInd + " << ss.float3Const(0.0f, incr, incr) << ";";
ss.newLine() << ss.float3Decl("v3") << " = " << ss.sampleTex3D(name, "nextInd") << ".rgb;";
ss.newLine() << "f1 = " << ss.float3Const("1. - frac.r") << ";";
ss.newLine() << "f4 = " << ss.float3Const("frac.b") << ";";
ss.newLine() << ss.float3Decl("f2") << " = " << ss.float3Const("frac.r - frac.g") << ";";
ss.newLine() << ss.float3Decl("f3") << " = " << ss.float3Const("frac.g - frac.b") << ";";
ss.newLine() << shaderCreator->getPixelName() << ".rgb = (f2 * v2) + (f3 * v3);";
ss.dedent();
ss.newLine() << "}";
ss.newLine() << "else if (frac.r >= frac.b)"; // R > B > G
ss.newLine() << "{";
ss.indent();
ss.newLine() << "nextInd = baseInd + " << ss.float3Const(0.0f, 0.0f, incr) << ";";
ss.newLine() << ss.float3Decl("v2") << " = " << ss.sampleTex3D(name, "nextInd") << ".rgb;";
ss.newLine() << "nextInd = baseInd + " << ss.float3Const(incr, 0.0f, incr) << ";";
ss.newLine() << ss.float3Decl("v3") << " = " << ss.sampleTex3D(name, "nextInd") << ".rgb;";
ss.newLine() << "f1 = " << ss.float3Const("1. - frac.r") << ";";
ss.newLine() << "f4 = " << ss.float3Const("frac.g") << ";";
ss.newLine() << ss.float3Decl("f2") << " = " << ss.float3Const("frac.r - frac.b") << ";";
ss.newLine() << ss.float3Decl("f3") << " = " << ss.float3Const("frac.b - frac.g") << ";";
ss.newLine() << shaderCreator->getPixelName() << ".rgb = (f2 * v2) + (f3 * v3);";
ss.dedent();
ss.newLine() << "}";
ss.newLine() << "else"; // B > R > G
ss.newLine() << "{";
ss.indent();
ss.newLine() << "nextInd = baseInd + " << ss.float3Const(incr, 0.0f, 0.0f) << ";";
ss.newLine() << ss.float3Decl("v2") << " = " << ss.sampleTex3D(name, "nextInd") << ".rgb;";
ss.newLine() << "nextInd = baseInd + " << ss.float3Const(incr, 0.0f, incr) << ";";
ss.newLine() << ss.float3Decl("v3") << " = " << ss.sampleTex3D(name, "nextInd") << ".rgb;";
ss.newLine() << "f1 = " << ss.float3Const("1. - frac.b") << ";";
ss.newLine() << "f4 = " << ss.float3Const("frac.g") << ";";
ss.newLine() << ss.float3Decl("f2") << " = " << ss.float3Const("frac.b - frac.r") << ";";
ss.newLine() << ss.float3Decl("f3") << " = " << ss.float3Const("frac.r - frac.g") << ";";
ss.newLine() << shaderCreator->getPixelName() << ".rgb = (f2 * v2) + (f3 * v3);";
ss.dedent();
ss.newLine() << "}";
ss.dedent();
ss.newLine() << "}";
ss.newLine() << "else";
ss.newLine() << "{";
ss.indent();
ss.newLine() << "if (frac.g <= frac.b)"; // B > G > R
ss.newLine() << "{";
ss.indent();
ss.newLine() << "nextInd = baseInd + " << ss.float3Const(incr, 0.0f, 0.0f) << ";";
ss.newLine() << ss.float3Decl("v2") << " = " << ss.sampleTex3D(name, "nextInd") << ".rgb;";
ss.newLine() << "nextInd = baseInd + " << ss.float3Const(incr, incr, 0.0f) << ";";
ss.newLine() << ss.float3Decl("v3") << " = " << ss.sampleTex3D(name, "nextInd") << ".rgb;";
ss.newLine() << "f1 = " << ss.float3Const("1. - frac.b") << ";";
ss.newLine() << "f4 = " << ss.float3Const("frac.r") << ";";
ss.newLine() << ss.float3Decl("f2") << " = " << ss.float3Const("frac.b - frac.g") << ";";
ss.newLine() << ss.float3Decl("f3") << " = " << ss.float3Const("frac.g - frac.r") << ";";
ss.newLine() << shaderCreator->getPixelName() << ".rgb = (f2 * v2) + (f3 * v3);";
ss.dedent();
ss.newLine() << "}";
ss.newLine() << "else if (frac.r >= frac.b)"; // G > R > B
ss.newLine() << "{";
ss.indent();
ss.newLine() << "nextInd = baseInd + " << ss.float3Const(0.0f, incr, 0.0f) << ";";
ss.newLine() << ss.float3Decl("v2") << " = " << ss.sampleTex3D(name, "nextInd") << ".rgb;";
ss.newLine() << "nextInd = baseInd + " << ss.float3Const(0.0f, incr, incr) << ";";
ss.newLine() << ss.float3Decl("v3") << " = " << ss.sampleTex3D(name, "nextInd") << ".rgb;";
ss.newLine() << "f1 = " << ss.float3Const("1. - frac.g") << ";";
ss.newLine() << "f4 = " << ss.float3Const("frac.b") << ";";
ss.newLine() << ss.float3Decl("f2") << " = " << ss.float3Const("frac.g - frac.r") << ";";
ss.newLine() << ss.float3Decl("f3") << " = " << ss.float3Const("frac.r - frac.b") << ";";
ss.newLine() << shaderCreator->getPixelName() << ".rgb = (f2 * v2) + (f3 * v3);";
ss.dedent();
ss.newLine() << "}";
ss.newLine() << "else"; // G > B > R
ss.newLine() << "{";
ss.indent();
ss.newLine() << "nextInd = baseInd + " << ss.float3Const(0.0f, incr, 0.0f) << ";";
ss.newLine() << ss.float3Decl("v2") << " = " << ss.sampleTex3D(name, "nextInd") << ".rgb;";
ss.newLine() << "nextInd = baseInd + " << ss.float3Const(incr, incr, 0.0f) << ";";
ss.newLine() << ss.float3Decl("v3") << " = " << ss.sampleTex3D(name, "nextInd") << ".rgb;";
ss.newLine() << "f1 = " << ss.float3Const("1. - frac.g") << ";";
ss.newLine() << "f4 = " << ss.float3Const("frac.r") << ";";
ss.newLine() << ss.float3Decl("f2") << " = " << ss.float3Const("frac.g - frac.b") << ";";
ss.newLine() << ss.float3Decl("f3") << " = " << ss.float3Const("frac.b - frac.r") << ";";
ss.newLine() << shaderCreator->getPixelName() << ".rgb = (f2 * v2) + (f3 * v3);";
ss.dedent();
ss.newLine() << "}";
ss.dedent();
ss.newLine() << "}";
ss.newLine() << shaderCreator->getPixelName()
<< ".rgb = "
<< shaderCreator->getPixelName()
<< ".rgb + (f1 * v1) + (f4 * v4);";
ss.dedent();
ss.newLine() << "}";
}
else
{
// Trilinear interpolation
// Use texture3d and GL_LINEAR and the GPU's built-in trilinear algorithm.
// Note that the fractional components are quantized to 8-bits on some
// hardware, which introduces significant error with small grid sizes.
ss.newLine() << ss.float3Decl(name + "_coords")
<< " = (" << shaderCreator->getPixelName() << ".zyx * "
<< ss.float3Const(dim - 1) << " + "
<< ss.float3Const(0.5f) + ") / "
<< ss.float3Const(dim) << ";";
ss.newLine() << shaderCreator->getPixelName() << ".rgb = "
<< ss.sampleTex3D(name, name + "_coords") << ".rgb;";
}
shaderCreator->addToFunctionShaderCode(ss.string().c_str());
}
}
} // namespace OCIO_NAMESPACE
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sprophelp.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-07 19:57:33 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _LINGU2_PROPHELP_HXX_
#define _LINGU2_PROPHELP_HXX_
#include <tools/solar.h>
#include <uno/lbnames.h> // CPPU_CURRENT_LANGUAGE_BINDING_NAME macro, which specify the environment type
#include <cppuhelper/implbase2.hxx> // helper for implementations
#ifndef _CPPUHELPER_INTERFACECONTAINER_H_
#include <cppuhelper/interfacecontainer.h>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYCHANGELISTENER_HPP_
#include <com/sun/star/beans/XPropertyChangeListener.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUES_HPP_
#include <com/sun/star/beans/PropertyValues.hpp>
#endif
#include <com/sun/star/linguistic2/XLinguServiceEventBroadcaster.hpp>
namespace com { namespace sun { namespace star { namespace beans {
class XPropertySet;
}}}};
namespace com { namespace sun { namespace star { namespace linguistic2 {
struct LinguServiceEvent;
}}}};
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::linguistic2;
///////////////////////////////////////////////////////////////////////////
// PropertyChgHelper
// virtual base class for all XPropertyChangeListener members of the
// various lingu services.
// Only propertyChange needs to be implemented.
class PropertyChgHelper :
public cppu::WeakImplHelper2
<
XPropertyChangeListener,
XLinguServiceEventBroadcaster
>
{
Sequence< OUString > aPropNames;
Reference< XInterface > xMyEvtObj;
::cppu::OInterfaceContainerHelper aLngSvcEvtListeners;
Reference< XPropertySet > xPropSet;
// disallow use of copy-constructor and assignment-operator
PropertyChgHelper( const PropertyChgHelper & );
PropertyChgHelper & operator = ( const PropertyChgHelper & );
public:
PropertyChgHelper(
const Reference< XInterface > &rxSource,
Reference< XPropertySet > &rxPropSet,
const char *pPropNames[], USHORT nPropCount );
virtual ~PropertyChgHelper();
// XEventListener
virtual void SAL_CALL
disposing( const EventObject& rSource )
throw(RuntimeException);
// XPropertyChangeListener
virtual void SAL_CALL
propertyChange( const PropertyChangeEvent& rEvt )
throw(RuntimeException) = 0;
// XLinguServiceEventBroadcaster
virtual sal_Bool SAL_CALL
addLinguServiceEventListener(
const Reference< XLinguServiceEventListener >& rxListener )
throw(RuntimeException);
virtual sal_Bool SAL_CALL
removeLinguServiceEventListener(
const Reference< XLinguServiceEventListener >& rxListener )
throw(RuntimeException);
// non UNO functions
void AddAsPropListener();
void RemoveAsPropListener();
void LaunchEvent( const LinguServiceEvent& rEvt );
const Sequence< OUString > &
GetPropNames() const { return aPropNames; }
const Reference< XPropertySet > &
GetPropSet() const { return xPropSet; }
const Reference< XInterface > &
GetEvtObj() const { return xMyEvtObj; }
};
///////////////////////////////////////////////////////////////////////////
class PropertyHelper_Spell :
public PropertyChgHelper
{
// default values
BOOL bIsGermanPreReform;
BOOL bIsIgnoreControlCharacters;
BOOL bIsUseDictionaryList;
BOOL bIsSpellUpperCase;
BOOL bIsSpellWithDigits;
BOOL bIsSpellCapitalization;
// return values, will be set to default value or current temporary value
BOOL bResIsGermanPreReform;
BOOL bResIsIgnoreControlCharacters;
BOOL bResIsUseDictionaryList;
BOOL bResIsSpellUpperCase;
BOOL bResIsSpellWithDigits;
BOOL bResIsSpellCapitalization;
// disallow use of copy-constructor and assignment-operator
PropertyHelper_Spell( const PropertyHelper_Spell & );
PropertyHelper_Spell & operator = ( const PropertyHelper_Spell & );
void SetDefault();
public:
PropertyHelper_Spell(
const Reference< XInterface > &rxSource,
Reference< XPropertySet > &rxPropSet );
virtual ~PropertyHelper_Spell();
// XPropertyChangeListener
virtual void SAL_CALL
propertyChange( const PropertyChangeEvent& rEvt )
throw(RuntimeException);
void SetTmpPropVals( const PropertyValues &rPropVals );
BOOL IsGermanPreReform() const { return bResIsGermanPreReform; }
BOOL IsIgnoreControlCharacters() const { return bResIsIgnoreControlCharacters; }
BOOL IsUseDictionaryList() const { return bResIsUseDictionaryList; }
BOOL IsSpellUpperCase() const { return bResIsSpellUpperCase; }
BOOL IsSpellWithDigits() const { return bResIsSpellWithDigits; }
BOOL IsSpellCapitalization() const { return bResIsSpellCapitalization; }
};
///////////////////////////////////////////////////////////////////////////
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.2.114); FILE MERGED 2008/04/01 15:21:28 thb 1.2.114.3: #i85898# Stripping all external header guards 2008/04/01 12:31:47 thb 1.2.114.2: #i85898# Stripping all external header guards 2008/03/31 16:25:39 rt 1.2.114.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: sprophelp.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 _LINGU2_PROPHELP_HXX_
#define _LINGU2_PROPHELP_HXX_
#include <tools/solar.h>
#include <uno/lbnames.h> // CPPU_CURRENT_LANGUAGE_BINDING_NAME macro, which specify the environment type
#include <cppuhelper/implbase2.hxx> // helper for implementations
#include <cppuhelper/interfacecontainer.h>
#include <com/sun/star/beans/XPropertyChangeListener.hpp>
#include <com/sun/star/beans/PropertyValues.hpp>
#include <com/sun/star/linguistic2/XLinguServiceEventBroadcaster.hpp>
namespace com { namespace sun { namespace star { namespace beans {
class XPropertySet;
}}}};
namespace com { namespace sun { namespace star { namespace linguistic2 {
struct LinguServiceEvent;
}}}};
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::linguistic2;
///////////////////////////////////////////////////////////////////////////
// PropertyChgHelper
// virtual base class for all XPropertyChangeListener members of the
// various lingu services.
// Only propertyChange needs to be implemented.
class PropertyChgHelper :
public cppu::WeakImplHelper2
<
XPropertyChangeListener,
XLinguServiceEventBroadcaster
>
{
Sequence< OUString > aPropNames;
Reference< XInterface > xMyEvtObj;
::cppu::OInterfaceContainerHelper aLngSvcEvtListeners;
Reference< XPropertySet > xPropSet;
// disallow use of copy-constructor and assignment-operator
PropertyChgHelper( const PropertyChgHelper & );
PropertyChgHelper & operator = ( const PropertyChgHelper & );
public:
PropertyChgHelper(
const Reference< XInterface > &rxSource,
Reference< XPropertySet > &rxPropSet,
const char *pPropNames[], USHORT nPropCount );
virtual ~PropertyChgHelper();
// XEventListener
virtual void SAL_CALL
disposing( const EventObject& rSource )
throw(RuntimeException);
// XPropertyChangeListener
virtual void SAL_CALL
propertyChange( const PropertyChangeEvent& rEvt )
throw(RuntimeException) = 0;
// XLinguServiceEventBroadcaster
virtual sal_Bool SAL_CALL
addLinguServiceEventListener(
const Reference< XLinguServiceEventListener >& rxListener )
throw(RuntimeException);
virtual sal_Bool SAL_CALL
removeLinguServiceEventListener(
const Reference< XLinguServiceEventListener >& rxListener )
throw(RuntimeException);
// non UNO functions
void AddAsPropListener();
void RemoveAsPropListener();
void LaunchEvent( const LinguServiceEvent& rEvt );
const Sequence< OUString > &
GetPropNames() const { return aPropNames; }
const Reference< XPropertySet > &
GetPropSet() const { return xPropSet; }
const Reference< XInterface > &
GetEvtObj() const { return xMyEvtObj; }
};
///////////////////////////////////////////////////////////////////////////
class PropertyHelper_Spell :
public PropertyChgHelper
{
// default values
BOOL bIsGermanPreReform;
BOOL bIsIgnoreControlCharacters;
BOOL bIsUseDictionaryList;
BOOL bIsSpellUpperCase;
BOOL bIsSpellWithDigits;
BOOL bIsSpellCapitalization;
// return values, will be set to default value or current temporary value
BOOL bResIsGermanPreReform;
BOOL bResIsIgnoreControlCharacters;
BOOL bResIsUseDictionaryList;
BOOL bResIsSpellUpperCase;
BOOL bResIsSpellWithDigits;
BOOL bResIsSpellCapitalization;
// disallow use of copy-constructor and assignment-operator
PropertyHelper_Spell( const PropertyHelper_Spell & );
PropertyHelper_Spell & operator = ( const PropertyHelper_Spell & );
void SetDefault();
public:
PropertyHelper_Spell(
const Reference< XInterface > &rxSource,
Reference< XPropertySet > &rxPropSet );
virtual ~PropertyHelper_Spell();
// XPropertyChangeListener
virtual void SAL_CALL
propertyChange( const PropertyChangeEvent& rEvt )
throw(RuntimeException);
void SetTmpPropVals( const PropertyValues &rPropVals );
BOOL IsGermanPreReform() const { return bResIsGermanPreReform; }
BOOL IsIgnoreControlCharacters() const { return bResIsIgnoreControlCharacters; }
BOOL IsUseDictionaryList() const { return bResIsUseDictionaryList; }
BOOL IsSpellUpperCase() const { return bResIsSpellUpperCase; }
BOOL IsSpellWithDigits() const { return bResIsSpellWithDigits; }
BOOL IsSpellCapitalization() const { return bResIsSpellCapitalization; }
};
///////////////////////////////////////////////////////////////////////////
#endif
<|endoftext|> |
<commit_before>//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2014 Michael Fink
//
/// \file ConnectCameraDlg.hpp Camera connect dialog
//
#pragma once
// includes
#include "ViewManager.hpp"
#include "Instance.hpp"
#include "SourceDevice.hpp"
/// connect to camera dialog
class ConnectCameraDlg :
public CDialogImpl<ConnectCameraDlg>,
public CDialogResize<ConnectCameraDlg>,
public CWinDataExchange<ConnectCameraDlg>
{
public:
/// dtor
ConnectCameraDlg();
/// dialog id
enum { IDD = IDD_CONNECT_CAMERA };
/// returns source device of connected camera
std::shared_ptr<SourceDevice> GetSourceDevice() const;
private:
BEGIN_MSG_MAP(ConnectCameraDlg)
MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
COMMAND_ID_HANDLER(IDOK, OnCloseCmd)
COMMAND_ID_HANDLER(IDCANCEL, OnCloseCmd)
COMMAND_ID_HANDLER(IDC_BUTTON_REFRESH, OnBtnRefresh)
COMMAND_ID_HANDLER(IDC_BUTTON_INFO, OnBtnInfo)
NOTIFY_HANDLER(IDC_LIST_CAMERA, LVN_ITEMCHANGED, OnListCameraItemChanged)
CHAIN_MSG_MAP(CDialogResize<ConnectCameraDlg>)
END_MSG_MAP()
BEGIN_DLGRESIZE_MAP(ConnectCameraDlg)
DLGRESIZE_CONTROL(IDC_LIST_CAMERA, DLSZ_SIZE_X)
DLGRESIZE_CONTROL(IDC_BUTTON_REFRESH, DLSZ_MOVE_X)
DLGRESIZE_CONTROL(IDCANCEL, DLSZ_MOVE_X | DLSZ_MOVE_Y)
DLGRESIZE_CONTROL(IDOK, DLSZ_MOVE_X | DLSZ_MOVE_Y)
END_DLGRESIZE_MAP()
BEGIN_DDX_MAP(ConnectCameraDlg)
DDX_CONTROL_HANDLE(IDC_LIST_CAMERA, m_lcCameras)
END_DDX_MAP()
// Handler prototypes (uncomment arguments if needed):
// LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
// LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
// LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/)
LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
LRESULT OnCloseCmd(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnBtnRefresh(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnBtnInfo(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnListCameraItemChanged(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/);
/// called when camera is added
void OnCameraAdded();
/// refreshes camera list
void RefreshCameraList();
private:
/// CanonControl instance
Instance m_instance;
/// camera list
CListViewCtrl m_lcCameras;
/// icons for camera list
CImageList m_ilIcons;
/// index of selected source device
int m_iSelectedSourceDeviceIndex;
};
<commit_msg>fixed resizing connect dialog<commit_after>//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2014 Michael Fink
//
/// \file ConnectCameraDlg.hpp Camera connect dialog
//
#pragma once
// includes
#include "ViewManager.hpp"
#include "Instance.hpp"
#include "SourceDevice.hpp"
/// connect to camera dialog
class ConnectCameraDlg :
public CDialogImpl<ConnectCameraDlg>,
public CDialogResize<ConnectCameraDlg>,
public CWinDataExchange<ConnectCameraDlg>
{
public:
/// dtor
ConnectCameraDlg();
/// dialog id
enum { IDD = IDD_CONNECT_CAMERA };
/// returns source device of connected camera
std::shared_ptr<SourceDevice> GetSourceDevice() const;
private:
BEGIN_MSG_MAP(ConnectCameraDlg)
MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
COMMAND_ID_HANDLER(IDOK, OnCloseCmd)
COMMAND_ID_HANDLER(IDCANCEL, OnCloseCmd)
COMMAND_ID_HANDLER(IDC_BUTTON_REFRESH, OnBtnRefresh)
COMMAND_ID_HANDLER(IDC_BUTTON_INFO, OnBtnInfo)
NOTIFY_HANDLER(IDC_LIST_CAMERA, LVN_ITEMCHANGED, OnListCameraItemChanged)
CHAIN_MSG_MAP(CDialogResize<ConnectCameraDlg>)
END_MSG_MAP()
BEGIN_DLGRESIZE_MAP(ConnectCameraDlg)
DLGRESIZE_CONTROL(IDC_LIST_CAMERA, DLSZ_SIZE_X | DLSZ_SIZE_Y)
DLGRESIZE_CONTROL(IDC_BUTTON_REFRESH, DLSZ_MOVE_X)
DLGRESIZE_CONTROL(IDC_BUTTON_INFO, DLSZ_MOVE_X)
DLGRESIZE_CONTROL(IDCANCEL, DLSZ_MOVE_X | DLSZ_MOVE_Y)
DLGRESIZE_CONTROL(IDOK, DLSZ_MOVE_X | DLSZ_MOVE_Y)
END_DLGRESIZE_MAP()
BEGIN_DDX_MAP(ConnectCameraDlg)
DDX_CONTROL_HANDLE(IDC_LIST_CAMERA, m_lcCameras)
END_DDX_MAP()
// Handler prototypes (uncomment arguments if needed):
// LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
// LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
// LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/)
LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
LRESULT OnCloseCmd(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnBtnRefresh(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnBtnInfo(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnListCameraItemChanged(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/);
/// called when camera is added
void OnCameraAdded();
/// refreshes camera list
void RefreshCameraList();
private:
/// CanonControl instance
Instance m_instance;
/// camera list
CListViewCtrl m_lcCameras;
/// icons for camera list
CImageList m_ilIcons;
/// index of selected source device
int m_iSelectedSourceDeviceIndex;
};
<|endoftext|> |
<commit_before>// -*- Mode: c++-mode; c-basic-offset: 2; indent-tabs-mode: t; tab-width: 2; -*-
//
// Copyright (C) 2003-2004 Grzegorz Jaskiewicz <gj at pointblue.com.pl>
//
// gadueditaccount.cpp
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
// 02111-1307, USA.
#include "gadueditaccount.h"
#include "gaduaccount.h"
#include "gaduprotocol.h"
#include <qradiobutton.h>
#include <qcombobox.h>
#include <qlabel.h>
#include <qstring.h>
#include <qcheckbox.h>
#include <qlineedit.h>
#include <qbutton.h>
#include <qregexp.h>
#include <qpushbutton.h>
#include <klineedit.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <klocale.h>
GaduEditAccount::GaduEditAccount( GaduProtocol* proto, KopeteAccount* ident, QWidget* parent, const char* name )
: GaduAccountEditUI( parent, name ), KopeteEditAccountWidget( ident ), protocol_( proto ), rcmd( 0 )
{
#ifdef __GG_LIBGADU_HAVE_OPENSSL
isSsl = true;
#else
isSsl = false;
#endif
useTls_->setDisabled( !isSsl );
if ( account() == NULL ) {
useTls_->setCurrentItem( GaduAccount::TLS_no );
registerNew->setEnabled( true );
}
else {
registerNew->setDisabled( true );
loginEdit_->setDisabled( true );
loginEdit_->setText( account()->accountId() );
if ( account()->rememberPassword() ) {
passwordEdit_->setText( account()->password() );
}
else {
passwordEdit_->setText( "" );
}
nickName->setText( account()->myself()->displayName() );
rememberCheck_->setChecked( account()->rememberPassword() );
autoLoginCheck_->setChecked( account()->autoLogin() );
dccCheck_->setChecked( static_cast<GaduAccount*>(account())->dccEnabled() );
useTls_->setCurrentItem( isSsl ? ( static_cast<GaduAccount*> (account()) ->useTls() ) : 2 );
}
QObject::connect( registerNew, SIGNAL( clicked( ) ), SLOT( registerNewAccount( ) ) );
}
void
GaduEditAccount::registerNewAccount()
{
registerNew->setDisabled( true );
regDialog = new GaduRegisterAccount( NULL , "Register account dialog" );
connect( regDialog, SIGNAL( registeredNumber( unsigned int, QString ) ), SLOT( newUin( unsigned int, QString ) ) );
if ( regDialog->exec() != QDialog::Accepted ) {
registerNew->setDisabled( false );
loginEdit_->setText( "" );
rememberCheck_->setChecked( true );
passwordEdit_->setText( "" );
return;
}
}
void
GaduEditAccount::registrationFailed()
{
KMessageBox::sorry( this, i18n( "<b>Registration FAILED.</b>" ), i18n( "Gadu-Gadu" ) );
}
void
GaduEditAccount::newUin( unsigned int uni, QString password )
{
loginEdit_->setText( QString::number( uni ) );
passwordEdit_->setText( password );
}
bool
GaduEditAccount::validateData()
{
if ( loginEdit_->text().isEmpty() ) {
KMessageBox::sorry( this, i18n( "<b>Enter UIN please.</b>" ), i18n( "Gadu-Gadu" ) );
return false;
}
if ( loginEdit_->text().toInt() < 0 || loginEdit_->text().toInt() == 0 ) {
KMessageBox::sorry( this, i18n( "<b>UIN should be a positive number.</b>" ), i18n( "Gadu-Gadu" ) );
return false;
}
if ( passwordEdit_->text().isEmpty() && rememberCheck_->isChecked() ) {
KMessageBox::sorry( this, i18n( "<b>Enter password please.</b>" ), i18n( "Gadu-Gadu" ) );
return false;
}
return true;
}
KopeteAccount*
GaduEditAccount::apply()
{
if ( account() == NULL ) {
setAccount( new GaduAccount( protocol_, loginEdit_->text() ) );
account()->setAccountId( loginEdit_->text() );
}
account()->setAutoLogin( autoLoginCheck_->isChecked() );
if( rememberCheck_->isChecked() && passwordEdit_->text().length() ) {
account()->setPassword( passwordEdit_->text() );
}
else {
account()->setPassword();
}
account()->myself()->rename( nickName->text() );
// this is changed only here, so i won't add any proper handling now
account()->setPluginData( account()->protocol(), QString::fromAscii( "nickName" ), nickName->text() );
account()->setAutoLogin( autoLoginCheck_->isChecked() );
( static_cast<GaduAccount*> (account()) )->setUseTls( (GaduAccount::tlsConnection) useTls_->currentItem() );
if ( static_cast<GaduAccount*>(account())->setDcc( dccCheck_->isChecked() ) == false ) {
KMessageBox::sorry( this, i18n( "<b>Starting DCC listening socket failed; dcc is not working now.</b>" ), i18n( "Gadu-Gadu" ) );
}
return account();
}
#include "gadueditaccount.moc"
<commit_msg>CVS_SILENT revert stupid whitespace changes<commit_after>// -*- Mode: c++-mode; c-basic-offset: 2; indent-tabs-mode: t; tab-width: 2; -*-
//
// Copyright (C) 2003-2004 Grzegorz Jaskiewicz <gj at pointblue.com.pl>
//
// gadueditaccount.cpp
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
// 02111-1307, USA.
#include "gadueditaccount.h"
#include "gaduaccount.h"
#include "gaduprotocol.h"
#include <qradiobutton.h>
#include <qcombobox.h>
#include <qlabel.h>
#include <qstring.h>
#include <qcheckbox.h>
#include <qlineedit.h>
#include <qbutton.h>
#include <qregexp.h>
#include <qpushbutton.h>
#include <klineedit.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <klocale.h>
GaduEditAccount::GaduEditAccount( GaduProtocol* proto, KopeteAccount* ident, QWidget* parent, const char* name )
: GaduAccountEditUI( parent, name ), KopeteEditAccountWidget( ident ), protocol_( proto ), rcmd( 0 )
{
#ifdef __GG_LIBGADU_HAVE_OPENSSL
isSsl = true;
#else
isSsl = false;
#endif
useTls_->setDisabled( !isSsl );
if ( account() == NULL ) {
useTls_->setCurrentItem( GaduAccount::TLS_no );
registerNew->setEnabled( true );
}
else {
registerNew->setDisabled( true );
loginEdit_->setDisabled( true );
loginEdit_->setText( account()->accountId() );
if ( account()->rememberPassword() ) {
passwordEdit_->setText( account()->password() );
}
else {
passwordEdit_->setText( "" );
}
nickName->setText( account()->myself()->displayName() );
rememberCheck_->setChecked( account()->rememberPassword() );
autoLoginCheck_->setChecked( account()->autoLogin() );
dccCheck_->setChecked( static_cast<GaduAccount*>(account())->dccEnabled() );
useTls_->setCurrentItem( isSsl ? ( static_cast<GaduAccount*> (account()) ->useTls() ) : 2 );
}
QObject::connect( registerNew, SIGNAL( clicked( ) ), SLOT( registerNewAccount( ) ) );
}
void
GaduEditAccount::registerNewAccount()
{
registerNew->setDisabled( true );
regDialog = new GaduRegisterAccount( NULL , "Register account dialog" );
connect( regDialog, SIGNAL( registeredNumber( unsigned int, QString ) ), SLOT( newUin( unsigned int, QString ) ) );
if ( regDialog->exec() != QDialog::Accepted ) {
registerNew->setDisabled( false );
loginEdit_->setText( "" );
rememberCheck_->setChecked( true );
passwordEdit_->setText( "" );
return;
}
}
void
GaduEditAccount::registrationFailed()
{
KMessageBox::sorry( this, i18n( "<b>Registration FAILED.</b>" ), i18n( "Gadu-Gadu" ) );
}
void
GaduEditAccount::newUin( unsigned int uni, QString password )
{
loginEdit_->setText( QString::number( uni ) );
passwordEdit_->setText( password );
}
bool
GaduEditAccount::validateData()
{
if ( loginEdit_->text().isEmpty() ) {
KMessageBox::sorry( this, i18n( "<b>Enter UIN please.</b>" ), i18n( "Gadu-Gadu" ) );
return false;
}
if ( loginEdit_->text().toInt() < 0 || loginEdit_->text().toInt() == 0 ) {
KMessageBox::sorry( this, i18n( "<b>UIN should be a positive number.</b>" ), i18n( "Gadu-Gadu" ) );
return false;
}
if ( passwordEdit_->text().isEmpty() && rememberCheck_->isChecked() ) {
KMessageBox::sorry( this, i18n( "<b>Enter password please.</b>" ), i18n( "Gadu-Gadu" ) );
return false;
}
return true;
}
KopeteAccount*
GaduEditAccount::apply()
{
if ( account() == NULL ) {
setAccount( new GaduAccount( protocol_, loginEdit_->text() ) );
account()->setAccountId( loginEdit_->text() );
}
account()->setAutoLogin( autoLoginCheck_->isChecked() );
if( rememberCheck_->isChecked() && passwordEdit_->text().length() ) {
account()->setPassword( passwordEdit_->text() );
}
else {
account()->setPassword();
}
account()->myself()->rename( nickName->text() );
// this is changed only here, so i won't add any proper handling now
account()->setPluginData( account()->protocol(), QString::fromAscii( "nickName" ), nickName->text() );
account()->setAutoLogin( autoLoginCheck_->isChecked() );
( static_cast<GaduAccount*> (account()) )->setUseTls( (GaduAccount::tlsConnection) useTls_->currentItem() );
if ( static_cast<GaduAccount*>(account())->setDcc( dccCheck_->isChecked() ) == false ) {
KMessageBox::sorry( this, i18n( "<b>Starting DCC listening socket failed; dcc is not working now.</b>" ), i18n( "Gadu-Gadu" ) );
}
return account();
}
#include "gadueditaccount.moc"
<|endoftext|> |
<commit_before>#define __UNSAFE__
#include "Socket.h"
#include <stdio.h>
#include "os.h"
#include "Endian.h"
#if defined( __WIN_API__ )
#pragma comment( lib, "Ws2_32.lib" )
#include <WinSock2.h>
#include <WS2tcpip.h>
namespace WinSock {
uint32_t winsockReferenceCount = 0;
WSADATA winSockData;
}
using namespace WinSock;
#elif defined( __POSIX__ )
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#endif
const uint16_t xiSocket::PORT_ANY = 0;
/*
====================
xiSocket::xiSocket
Constructor
If winsock is in use, the Winsock system is started up here
====================
*/
xiSocket::xiSocket() {
nativeHandle = 0; // This is a null socket, it shouldn't do anything
#if defined( __WIN_API__ )
if ( winsockReferenceCount++ == 0 ) {
const int winSockError = WSAStartup( MAKEWORD( 2, 2 ), &winSockData ); // Start winsock
if ( winSockError ) {
if ( --winsockReferenceCount == 0 ) {
WSACleanup(); // Destroy winsock
}
status = STATUS_ERROR;
}
}
#endif
}
/*
====================
xiSocket::~xiSocket
Deconstructor
If winsock is in use, the reference count of Winsock is decremented
When the reference hits 0, winsock is stopped
====================
*/
xiSocket::~xiSocket() {
#if defined( __WIN_API__ )
if ( --winsockReferenceCount == 0 ) {
WSACleanup(); // Destroy winsock
}
#endif
}
/*
====================
xiSocket::ReadInt8
Function for reading a byte from a given buffer
The byte is stored in varptr
====================
*/
byteLen_t xiSocket::ReadInt8( const char * const buffer, void * const varptr ) {
memcpy( varptr, buffer, sizeof( uint8_t ) );
return sizeof( uint8_t );
}
/*
====================
xiSocket::ReadInt16
Function for reading 2 bytes from a given buffer
The bytes are stored in varptr
====================
*/
byteLen_t xiSocket::ReadInt16( const char * const buffer, void * const varptr ) {
const byteLen_t size = sizeof( uint16_t );
uint16_t num = *( uint16_t * )buffer;
num = ( uint16_t )Endian::NetworkToHostUnsigned( num, size );
memcpy( varptr, &num, size );
return size;
}
/*
====================
xiSocket::ReadInt32
Function for reading 4 bytes from a given buffer
The bytes are stored in varptr
====================
*/
byteLen_t xiSocket::ReadInt32( const char * const buffer, void * const varptr ) {
const byteLen_t size = sizeof( uint32_t );
uint32_t num = *( uint32_t * )buffer;
num = ( uint32_t )Endian::NetworkToHostUnsigned( num, size );
memcpy( varptr, &num, size );
return size;
}
/*
====================
xiSocket::ReadInt64
Function for reading 8 bytes from a given buffer
The bytes are stored in varptr
====================
*/
byteLen_t xiSocket::ReadInt64( const char * const buffer, void * const varptr ) {
const byteLen_t size = sizeof( uint64_t );
uint64_t num = *( uint64_t * )buffer;
num = Endian::NetworkToHostUnsigned( num, size );
memcpy( varptr, &num, size );
return size;
}
/*
====================
xiSocket::WriteInt8
Writes 1 byte of varptr into the buffer
====================
*/
byteLen_t xiSocket::WriteInt8( char * const buffer, const void * const varptr ) {
memcpy( buffer, varptr, sizeof( uint8_t ) );
return sizeof( uint8_t );
}
/*
====================
xiSocket::WriteInt16
Writes 2 bytes of varptr into the buffer
====================
*/
byteLen_t xiSocket::WriteInt16( char * const buffer, const void * const varptr ) {
const byteLen_t size = sizeof( uint16_t );
uint16_t num = *( uint16_t * )varptr;
num = ( uint16_t )Endian::HostToNetworkUnsigned( num, size );
memcpy( buffer, &num, size );
return size;
}
/*
====================
xiSocket::WriteInt32
Writes 4 bytes of varptr into the buffer
====================
*/
byteLen_t xiSocket::WriteInt32( char * const buffer, const void * const varptr ) {
const byteLen_t size = sizeof( uint32_t );
uint32_t num = *( uint32_t * )varptr;
num = ( uint32_t )Endian::HostToNetworkUnsigned( num, size );
memcpy( buffer, &num, size );
return size;
}
/*
====================
xiSocket::WriteInt64
Writes 8 bytes of varptr into the buffer
====================
*/
byteLen_t xiSocket::WriteInt64( char * const buffer, const void * const varptr ) {
const byteLen_t size = sizeof( uint64_t );
uint64_t num = *( uint64_t * )varptr;
num = Endian::HostToNetworkUnsigned( num, size );
memcpy( buffer, &num, size );
return size;
}
/*
====================
xiSocket::ReadBytes
Reads byteLen number of bytes from buffer into byteptr
====================
*/
byteLen_t xiSocket::ReadBytes( const char * const buffer, uint8_t * const byteptr, const byteLen_t byteLen ) {
memcpy( &byteptr[0], &buffer[0], ( size_t )byteLen );
return byteLen;
}
/*
====================
xiSocket::WriteBytes
Writes byteLen number of bytes from byteptr into buffer
====================
*/
byteLen_t xiSocket::WriteBytes( char * const buffer, const uint8_t * const byteptr, const byteLen_t byteLen ) {
memcpy( &buffer[0], &byteptr[0], ( size_t )byteLen );
return byteLen;
}
/*
====================
xiSocket::ReadString
Copies buffer into byteptr up to a null-terminator
====================
*/
byteLen_t xiSocket::ReadString( const char * const buffer, char * const byteptr ) {
const char * c = &buffer[0];
while ( *c ) {
c++;
}
const size_t strLen = ( c - &buffer[0] );
memcpy( &byteptr[0], &buffer[0], strLen );
const byteLen_t lenPlusNull = ( byteLen_t )strlen( buffer ) + 1; // Returns the string plus the null terminator
return lenPlusNull;
}
/*
====================
xiSocket::WriteString
Copies byteptr into buffer up to a null-terminator
====================
*/
byteLen_t xiSocket::WriteString( char * const buffer, const char * const byteptr ) {
const char * c = &buffer[0];
while ( *c ) {
c++;
}
const size_t strLen = ( c - &buffer[0] );
memcpy( &buffer[0], &byteptr[0], strLen );
const byteLen_t lenPlusNull = ( byteLen_t )strlen( byteptr ) + 1; // Returns the string plus the null terminator
return lenPlusNull;
}
/*
====================
xiSocket::DomainLookup
Takes a url as a string and performs DNS to return the address information
URL is in the format a://b.c.d:p/d.i
a : optional protocol
b : optional www
c : domain
d : extension
p : optional port
d : ignored filepath
i : ignored file extension
====================
*/
bool xiSocket::DomainLookup( const char * const url, const uint16_t port, xiSocket::addressInfo_s * const info ) {
#if defined( __WIN_API__ )
xiSocket openSocket; // We do this to kick off WinSock if it hasn't yet started
#endif
char portStr[10];
sprintf( portStr, "%u", port );
memset( info, 0, sizeof( *info ) );
info->port = 80;
// So-called "hints" structure detailed in the getaddrinfo() MSDN page.
// I guess it contains information for the DNS lookup.
addrinfo hints;
memset( &hints, 0, sizeof( hints ) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
//Perform DNS lookup
addrinfo * res = nullptr;
const int addInfoState = getaddrinfo( url, portStr, &hints, &res ); // hardcode port number, for now
if ( addInfoState != 0 ) {
return false;
}
for ( addrinfo * ptr = res; ptr != nullptr; ptr = ptr->ai_next ) {
switch( ptr->ai_family ) {
case AF_INET:
const sockaddr_in * const sockData = ( const sockaddr_in * )ptr->ai_addr;//set current address
#if defined( __WIN_API__ )
info->address.protocolV4[0] = sockData->sin_addr.S_un.S_un_b.s_b1;
info->address.protocolV4[1] = sockData->sin_addr.S_un.S_un_b.s_b2;
info->address.protocolV4[2] = sockData->sin_addr.S_un.S_un_b.s_b3;
info->address.protocolV4[3] = sockData->sin_addr.S_un.S_un_b.s_b4;
#elif defined( __POSIX__ )
memcpy( &info->address.protocolV4[0], &sockData->sin_addr.s_addr, sizeof( sockData->sin_addr.s_addr ) );
#endif
break;
}
}
freeaddrinfo( res );
return true;
}<commit_msg>Replaced the switch statement with domain lookup with an if statement to escape the linked-list crawl earlier<commit_after>#define __UNSAFE__
#include "Socket.h"
#include <stdio.h>
#include "os.h"
#include "Endian.h"
#if defined( __WIN_API__ )
#pragma comment( lib, "Ws2_32.lib" )
#include <WinSock2.h>
#include <WS2tcpip.h>
namespace WinSock {
uint32_t winsockReferenceCount = 0;
WSADATA winSockData;
}
using namespace WinSock;
#elif defined( __POSIX__ )
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#endif
const uint16_t xiSocket::PORT_ANY = 0;
/*
====================
xiSocket::xiSocket
Constructor
If winsock is in use, the Winsock system is started up here
====================
*/
xiSocket::xiSocket() {
nativeHandle = 0; // This is a null socket, it shouldn't do anything
#if defined( __WIN_API__ )
if ( winsockReferenceCount++ == 0 ) {
const int winSockError = WSAStartup( MAKEWORD( 2, 2 ), &winSockData ); // Start winsock
if ( winSockError ) {
if ( --winsockReferenceCount == 0 ) {
WSACleanup(); // Destroy winsock
}
status = STATUS_ERROR;
}
}
#endif
}
/*
====================
xiSocket::~xiSocket
Deconstructor
If winsock is in use, the reference count of Winsock is decremented
When the reference hits 0, winsock is stopped
====================
*/
xiSocket::~xiSocket() {
#if defined( __WIN_API__ )
if ( --winsockReferenceCount == 0 ) {
WSACleanup(); // Destroy winsock
}
#endif
}
/*
====================
xiSocket::ReadInt8
Function for reading a byte from a given buffer
The byte is stored in varptr
====================
*/
byteLen_t xiSocket::ReadInt8( const char * const buffer, void * const varptr ) {
memcpy( varptr, buffer, sizeof( uint8_t ) );
return sizeof( uint8_t );
}
/*
====================
xiSocket::ReadInt16
Function for reading 2 bytes from a given buffer
The bytes are stored in varptr
====================
*/
byteLen_t xiSocket::ReadInt16( const char * const buffer, void * const varptr ) {
const byteLen_t size = sizeof( uint16_t );
uint16_t num = *( uint16_t * )buffer;
num = ( uint16_t )Endian::NetworkToHostUnsigned( num, size );
memcpy( varptr, &num, size );
return size;
}
/*
====================
xiSocket::ReadInt32
Function for reading 4 bytes from a given buffer
The bytes are stored in varptr
====================
*/
byteLen_t xiSocket::ReadInt32( const char * const buffer, void * const varptr ) {
const byteLen_t size = sizeof( uint32_t );
uint32_t num = *( uint32_t * )buffer;
num = ( uint32_t )Endian::NetworkToHostUnsigned( num, size );
memcpy( varptr, &num, size );
return size;
}
/*
====================
xiSocket::ReadInt64
Function for reading 8 bytes from a given buffer
The bytes are stored in varptr
====================
*/
byteLen_t xiSocket::ReadInt64( const char * const buffer, void * const varptr ) {
const byteLen_t size = sizeof( uint64_t );
uint64_t num = *( uint64_t * )buffer;
num = Endian::NetworkToHostUnsigned( num, size );
memcpy( varptr, &num, size );
return size;
}
/*
====================
xiSocket::WriteInt8
Writes 1 byte of varptr into the buffer
====================
*/
byteLen_t xiSocket::WriteInt8( char * const buffer, const void * const varptr ) {
memcpy( buffer, varptr, sizeof( uint8_t ) );
return sizeof( uint8_t );
}
/*
====================
xiSocket::WriteInt16
Writes 2 bytes of varptr into the buffer
====================
*/
byteLen_t xiSocket::WriteInt16( char * const buffer, const void * const varptr ) {
const byteLen_t size = sizeof( uint16_t );
uint16_t num = *( uint16_t * )varptr;
num = ( uint16_t )Endian::HostToNetworkUnsigned( num, size );
memcpy( buffer, &num, size );
return size;
}
/*
====================
xiSocket::WriteInt32
Writes 4 bytes of varptr into the buffer
====================
*/
byteLen_t xiSocket::WriteInt32( char * const buffer, const void * const varptr ) {
const byteLen_t size = sizeof( uint32_t );
uint32_t num = *( uint32_t * )varptr;
num = ( uint32_t )Endian::HostToNetworkUnsigned( num, size );
memcpy( buffer, &num, size );
return size;
}
/*
====================
xiSocket::WriteInt64
Writes 8 bytes of varptr into the buffer
====================
*/
byteLen_t xiSocket::WriteInt64( char * const buffer, const void * const varptr ) {
const byteLen_t size = sizeof( uint64_t );
uint64_t num = *( uint64_t * )varptr;
num = Endian::HostToNetworkUnsigned( num, size );
memcpy( buffer, &num, size );
return size;
}
/*
====================
xiSocket::ReadBytes
Reads byteLen number of bytes from buffer into byteptr
====================
*/
byteLen_t xiSocket::ReadBytes( const char * const buffer, uint8_t * const byteptr, const byteLen_t byteLen ) {
memcpy( &byteptr[0], &buffer[0], ( size_t )byteLen );
return byteLen;
}
/*
====================
xiSocket::WriteBytes
Writes byteLen number of bytes from byteptr into buffer
====================
*/
byteLen_t xiSocket::WriteBytes( char * const buffer, const uint8_t * const byteptr, const byteLen_t byteLen ) {
memcpy( &buffer[0], &byteptr[0], ( size_t )byteLen );
return byteLen;
}
/*
====================
xiSocket::ReadString
Copies buffer into byteptr up to a null-terminator
====================
*/
byteLen_t xiSocket::ReadString( const char * const buffer, char * const byteptr ) {
const char * c = &buffer[0];
while ( *c ) {
c++;
}
const size_t strLen = ( c - &buffer[0] );
memcpy( &byteptr[0], &buffer[0], strLen );
const byteLen_t lenPlusNull = ( byteLen_t )strlen( buffer ) + 1; // Returns the string plus the null terminator
return lenPlusNull;
}
/*
====================
xiSocket::WriteString
Copies byteptr into buffer up to a null-terminator
====================
*/
byteLen_t xiSocket::WriteString( char * const buffer, const char * const byteptr ) {
const char * c = &buffer[0];
while ( *c ) {
c++;
}
const size_t strLen = ( c - &buffer[0] );
memcpy( &buffer[0], &byteptr[0], strLen );
const byteLen_t lenPlusNull = ( byteLen_t )strlen( byteptr ) + 1; // Returns the string plus the null terminator
return lenPlusNull;
}
/*
====================
xiSocket::DomainLookup
Takes a url as a string and performs DNS to return the address information
URL is in the format a://b.c.d:p/d.i
a : optional protocol
b : optional www
c : domain
d : extension
p : optional port
d : ignored filepath
i : ignored file extension
====================
*/
bool xiSocket::DomainLookup( const char * const url, const uint16_t port, xiSocket::addressInfo_s * const info ) {
#if defined( __WIN_API__ )
xiSocket openSocket; // We do this to kick off WinSock if it hasn't yet started
#endif
char portStr[10];
sprintf( portStr, "%u", port );
memset( info, 0, sizeof( *info ) );
info->port = 80;
addrinfo hints;
memset( &hints, 0, sizeof( hints ) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Perform DNS lookup
addrinfo * res = nullptr;
const int addInfoState = getaddrinfo( url, portStr, &hints, &res );
if ( addInfoState != 0 ) {
return false;
}
for ( addrinfo * ptr = res; ptr != nullptr; ptr = ptr->ai_next ) {
if ( ptr->ai_family == AF_INET ) {
const sockaddr_in * const sockData = ( const sockaddr_in * )ptr->ai_addr; // Set current address
#if defined( __WIN_API__ )
info->address.protocolV4[0] = sockData->sin_addr.S_un.S_un_b.s_b1;
info->address.protocolV4[1] = sockData->sin_addr.S_un.S_un_b.s_b2;
info->address.protocolV4[2] = sockData->sin_addr.S_un.S_un_b.s_b3;
info->address.protocolV4[3] = sockData->sin_addr.S_un.S_un_b.s_b4;
#elif defined( __POSIX__ )
memcpy( &info->address.protocolV4[0], &sockData->sin_addr.s_addr, sizeof( sockData->sin_addr.s_addr ) );
#endif
break; // Escape the linked list crawl
}
}
freeaddrinfo( res );
return true;
}<|endoftext|> |
<commit_before>#include "../common/dep.hpp"
#include "../../src/container/native/NContainer.inl"
#include <chrono>
using namespace wrd;
using namespace std;
class MyNode : public Node {
WRD_CLASS(MyNode, Node)
public:
MyNode(int num): number(num) {}
int number;
};
/*
TEST(NArrFixture, instantiateTest) {
NArr arr;
}
TEST(NArrFixture, shouldNotCanAddLocalObject) {
NArr arr;
MyNode localObj(5);
ASSERT_EQ(arr.getLen(), 0);
ASSERT_FALSE(arr.add(localObj));
ASSERT_EQ(arr.getLen(), 0);
auto& elem = arr[0];
ASSERT_TRUE(nul(elem));
}
TEST(NArrFixture, simpleAddDelTest) {
NArr arr;
ASSERT_EQ(arr.getLen(), 0);
const int EXPECT_NUMBER = 5;
arr.add(*(new MyNode(EXPECT_NUMBER)));
ASSERT_EQ(arr.getLen(), 1);
auto elem1 = arr[0].cast<MyNode>();
ASSERT_FALSE(nul(elem1));
ASSERT_EQ(elem1.number, EXPECT_NUMBER);
}
TEST(NArrFixture, addDel10Elems) {
NArr arr;
const int cnt = 10;
for(int n=0; n < cnt; n++) {
ASSERT_TRUE(arr.add(*(new MyNode(n))));
}
ASSERT_EQ(arr.getLen(), cnt);
}
void benchMark(int cnt) {
Logger::get().setEnable(false);
vector<Str> vec;
auto start = chrono::steady_clock::now();
for(int n=0; n < cnt; n++) {
vec.push_back(Str(new MyNode(n)));
}
int sz = vec.size();
auto startDeleting = chrono::steady_clock::now();
vec.clear();
auto end = chrono::steady_clock::now();
auto addingElapsed = startDeleting - start;
auto removingElapsed = end - startDeleting;
auto totalElapsed = end - start;
Logger::get().setEnable(true);
WRD_I("[benchMark]: vector took total %d ms for adding(%dms) & removing(%dms) of %d elems.", totalElapsed / chrono::milliseconds(1), addingElapsed / chrono::milliseconds(1), removingElapsed / chrono::milliseconds(1), sz);
Logger::get().setEnable(false);
NArr arr;
start = chrono::steady_clock::now();
for(int n=0; n < cnt; n++) {
arr.add(*(new MyNode(n)));
}
sz = arr.getLen();
startDeleting = chrono::steady_clock::now();
arr.empty();
end = chrono::steady_clock::now();
addingElapsed = startDeleting - start;
removingElapsed = end - startDeleting;
totalElapsed = end - start;
Logger::get().setEnable(true);
WRD_I("[benchMark]: NArr took total %d ms for adding(%dms) & removing(%dms) of %d elems.", totalElapsed / chrono::milliseconds(1), addingElapsed / chrono::milliseconds(1), removingElapsed / chrono::milliseconds(1), sz);
}
TEST(NArrFixture, benchMarkTest) {
benchMark(100);
benchMark(1000);
benchMark(10000);
}
*/
<commit_msg>- [interp] remove dummy files.<commit_after>#include "../common/dep.hpp"
#include "../../src/container/native/NContainer.inl"
#include <chrono>
using namespace wrd;
using namespace std;
class MyNode : public Node {
WRD_CLASS(MyNode, Node)
public:
MyNode(int num): number(num) {}
int number;
};
TEST(NArrFixture, instantiateTest) {
NArr arr;
}
TEST(NArrFixture, shouldNotCanAddLocalObject) {
NArr arr;
MyNode localObj(5);
ASSERT_EQ(arr.getLen(), 0);
ASSERT_FALSE(arr.add(localObj));
ASSERT_EQ(arr.getLen(), 0);
auto& elem = arr[0];
ASSERT_TRUE(nul(elem));
}
TEST(NArrFixture, simpleAddDelTest) {
NArr arr;
ASSERT_EQ(arr.getLen(), 0);
const int EXPECT_NUMBER = 5;
arr.add(*(new MyNode(EXPECT_NUMBER)));
ASSERT_EQ(arr.getLen(), 1);
auto elem1 = arr[0].cast<MyNode>();
ASSERT_FALSE(nul(elem1));
ASSERT_EQ(elem1.number, EXPECT_NUMBER);
}
TEST(NArrFixture, addDel10Elems) {
NArr arr;
const int cnt = 10;
for(int n=0; n < cnt; n++) {
ASSERT_TRUE(arr.add(*(new MyNode(n))));
}
ASSERT_EQ(arr.getLen(), cnt);
}
void benchMark(int cnt) {
Logger::get().setEnable(false);
vector<Str> vec;
auto start = chrono::steady_clock::now();
for(int n=0; n < cnt; n++) {
vec.push_back(Str(new MyNode(n)));
}
int sz = vec.size();
auto startDeleting = chrono::steady_clock::now();
vec.clear();
auto end = chrono::steady_clock::now();
auto addingElapsed = startDeleting - start;
auto removingElapsed = end - startDeleting;
auto totalElapsed = end - start;
Logger::get().setEnable(true);
WRD_I("[benchMark]: vector took total %d ms for adding(%dms) & removing(%dms) of %d elems.", totalElapsed / chrono::milliseconds(1), addingElapsed / chrono::milliseconds(1), removingElapsed / chrono::milliseconds(1), sz);
Logger::get().setEnable(false);
NArr arr;
start = chrono::steady_clock::now();
for(int n=0; n < cnt; n++) {
arr.add(*(new MyNode(n)));
}
sz = arr.getLen();
startDeleting = chrono::steady_clock::now();
arr.empty();
end = chrono::steady_clock::now();
addingElapsed = startDeleting - start;
removingElapsed = end - startDeleting;
totalElapsed = end - start;
Logger::get().setEnable(true);
WRD_I("[benchMark]: NArr took total %d ms for adding(%dms) & removing(%dms) of %d elems.", totalElapsed / chrono::milliseconds(1), addingElapsed / chrono::milliseconds(1), removingElapsed / chrono::milliseconds(1), sz);
}
TEST(NArrFixture, benchMarkTest) {
benchMark(100);
benchMark(1000);
benchMark(10000);
}
class MyMyNode : public MyNode {
WRD_CLASS(MyMyNode, MyNode)
public:
MyMyNode(int num): Super(num) {}
};
TEST(NArrFixture, testContainableAPI) {
NArr* arr = new NArr();
Containable* con = arr;
ASSERT_EQ(con->getLen(), 0);
Iter head = con->head();
ASSERT_TRUE(head.isEnd());
Iter tail = con->tail();
ASSERT_TRUE(tail.isEnd());
ASSERT_TRUE(con->add(head, new MyNode(0)));
ASSERT_TRUE(con->add(tail, new MyMyNode(1)));
ASSERT_EQ(con->getLen(), 2);
int expectVal = 0;
for(Iter e=con->head(); e != con->tail() ;++e) {
MyNode& elem = e->cast<MyNode>();
ASSERT_FALSE(nul(elem));
ASSERT_EQ(elem.number, expectVal++);
}
expectVal = 0;
for(int n=0; n < arr->getLen() ;n++) {
MyNode& elem = arr->get(n).cast<MyNode>();
ASSERT_FALSE(nul(elem));
ASSERT_EQ(elem.number, expectVal++);
}
NArr tray = arr->get<MyNode>([](const MyNode& elem) {
return true;
});
ASSERT_EQ(tray.getLen(), 2);
int cnt = 0;
tray = arr->get<MyNode>([&cnt](const MyNode& elem) {
if(++cnt > 1) return false;
return true;
});
ASSERT_EQ(tray.getLen(), 1);
tray = arr->get<MyMyNode>([](const MyMyNode& elem) {
if(elem.number == 1) return true;
return false;
});
ASSERT_EQ(tray.getLen(), 1);
delete con;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file frame.cc
**/
#include "modules/planning/common/frame.h"
#include <cmath>
#include <string>
#include "modules/common/log.h"
#include "modules/map/pnc_map/pnc_map.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/reference_line/reference_line_smoother.h"
namespace apollo {
namespace planning {
const hdmap::PncMap *Frame::pnc_map_ = nullptr;
void Frame::SetMap(hdmap::PncMap *pnc_map) { pnc_map_ = pnc_map; }
FrameHistory::FrameHistory()
: IndexedQueue<uint32_t, Frame>(FLAGS_max_history_frame_num) {}
Frame::Frame(const uint32_t sequence_num) : sequence_num_(sequence_num) {}
void Frame::SetVehicleInitPose(const localization::Pose &pose) {
init_pose_ = pose;
}
void Frame::SetRoutingResponse(const routing::RoutingResponse &routing) {
routing_result_ = routing;
}
void Frame::SetPlanningStartPoint(const common::TrajectoryPoint &start_point) {
planning_start_point_ = start_point;
}
const hdmap::PncMap *Frame::PncMap() {
DCHECK(pnc_map_) << "map is not setup in frame";
return pnc_map_;
}
const common::TrajectoryPoint &Frame::PlanningStartPoint() const {
return planning_start_point_;
}
void Frame::SetPrediction(const prediction::PredictionObstacles &prediction) {
prediction_ = prediction;
}
void Frame::CreateObstacles(const prediction::PredictionObstacles &prediction) {
std::list<std::unique_ptr<Obstacle> > obstacles;
Obstacle::CreateObstacles(prediction, &obstacles);
for (auto &ptr : obstacles) {
mutable_planning_data()->mutable_decision_data()->AddObstacle(ptr.get());
obstacles_.Add(ptr->Id(), std::move(ptr));
}
}
bool Frame::AddDecision(const std::string &tag, const std::string &object_id,
const ObjectDecisionType &decision) {
auto *path_obstacle = path_obstacles_.Find(object_id);
if (!path_obstacle) {
AERROR << "failed to find obstacle;
return false;
}
path_obstacle->AddDecision(tag, decision);
return true;
}
bool Frame::Init() {
if (!pnc_map_) {
AERROR << "map is null, call SetMap() first";
return false;
}
const auto &point = init_pose_.position();
if (std::isnan(point.x()) || std::isnan(point.y())) {
AERROR << "init point is not set";
return false;
}
if (!CreateReferenceLineFromRouting()) {
AERROR << "Failed to create reference line from position: "
<< init_pose_.DebugString();
return false;
}
if (FLAGS_enable_prediction) {
CreateObstacles(prediction_);
}
return true;
}
uint32_t Frame::sequence_num() const { return sequence_num_; }
const PlanningData &Frame::planning_data() const { return _planning_data; }
PlanningData *Frame::mutable_planning_data() { return &_planning_data; }
void Frame::set_computed_trajectory(const PublishableTrajectory &trajectory) {
_computed_trajectory = trajectory;
}
const PublishableTrajectory &Frame::computed_trajectory() const {
return _computed_trajectory;
}
const ReferenceLine &Frame::reference_line() const { return *reference_line_; }
bool Frame::CreateReferenceLineFromRouting() {
common::PointENU vehicle_position;
vehicle_position.set_x(init_pose_.position().x());
vehicle_position.set_y(init_pose_.position().y());
vehicle_position.set_z(init_pose_.position().z());
if (!pnc_map_->CreatePathFromRouting(
routing_result_, vehicle_position, FLAGS_look_backward_distance,
FLAGS_look_forward_distance, &hdmap_path_)) {
AERROR << "Failed to get path from routing";
return false;
}
if (!SmoothReferenceLine()) {
AERROR << "Failed to smooth reference line";
return false;
}
return true;
}
bool Frame::SmoothReferenceLine() {
std::vector<ReferencePoint> ref_points;
for (const auto &point : hdmap_path_.path_points()) {
if (point.lane_waypoints().empty()) {
AERROR << "path point has no lane_waypoint";
return false;
}
const auto &lane_waypoint = point.lane_waypoints()[0];
ref_points.emplace_back(point, point.heading(), 0.0, 0.0, lane_waypoint);
}
if (ref_points.empty()) {
AERROR << "Found no reference points from map";
return false;
}
std::unique_ptr<ReferenceLine> reference_line(new ReferenceLine(ref_points));
std::vector<ReferencePoint> smoothed_ref_points;
ReferenceLineSmoother smoother;
if (!smoother.Init(FLAGS_reference_line_smoother_config_file)) {
AERROR << "Failed to load file "
<< FLAGS_reference_line_smoother_config_file;
return false;
}
if (!smoother.smooth(*reference_line, &smoothed_ref_points)) {
AERROR << "Fail to smooth a reference line from map";
return false;
}
ADEBUG << "smooth reference points num:" << smoothed_ref_points.size();
reference_line_.reset(new ReferenceLine(smoothed_ref_points));
return true;
}
const Obstacles &Frame::GetObstacles() const { return obstacles_; }
Obstacles *Frame::MutableObstacles() { return &obstacles_; }
std::string Frame::DebugString() const {
return "Frame: " + std::to_string(sequence_num_);
}
} // namespace planning
} // namespace apollo
<commit_msg>added AddDecision function in frame<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file frame.cc
**/
#include "modules/planning/common/frame.h"
#include <cmath>
#include <string>
#include "modules/common/log.h"
#include "modules/map/pnc_map/pnc_map.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/reference_line/reference_line_smoother.h"
namespace apollo {
namespace planning {
const hdmap::PncMap *Frame::pnc_map_ = nullptr;
void Frame::SetMap(hdmap::PncMap *pnc_map) { pnc_map_ = pnc_map; }
FrameHistory::FrameHistory()
: IndexedQueue<uint32_t, Frame>(FLAGS_max_history_frame_num) {}
Frame::Frame(const uint32_t sequence_num) : sequence_num_(sequence_num) {}
void Frame::SetVehicleInitPose(const localization::Pose &pose) {
init_pose_ = pose;
}
void Frame::SetRoutingResponse(const routing::RoutingResponse &routing) {
routing_result_ = routing;
}
void Frame::SetPlanningStartPoint(const common::TrajectoryPoint &start_point) {
planning_start_point_ = start_point;
}
const hdmap::PncMap *Frame::PncMap() {
DCHECK(pnc_map_) << "map is not setup in frame";
return pnc_map_;
}
const common::TrajectoryPoint &Frame::PlanningStartPoint() const {
return planning_start_point_;
}
void Frame::SetPrediction(const prediction::PredictionObstacles &prediction) {
prediction_ = prediction;
}
void Frame::CreateObstacles(const prediction::PredictionObstacles &prediction) {
std::list<std::unique_ptr<Obstacle> > obstacles;
Obstacle::CreateObstacles(prediction, &obstacles);
for (auto &ptr : obstacles) {
mutable_planning_data()->mutable_decision_data()->AddObstacle(ptr.get());
obstacles_.Add(ptr->Id(), std::move(ptr));
}
}
bool Frame::AddDecision(const std::string &tag, const std::string &object_id,
const ObjectDecisionType &decision) {
auto *path_obstacle = path_obstacles_.Find(object_id);
if (!path_obstacle) {
AERROR << "failed to find obstacle";
return false;
}
path_obstacle->AddDecision(tag, decision);
return true;
}
bool Frame::Init() {
if (!pnc_map_) {
AERROR << "map is null, call SetMap() first";
return false;
}
const auto &point = init_pose_.position();
if (std::isnan(point.x()) || std::isnan(point.y())) {
AERROR << "init point is not set";
return false;
}
if (!CreateReferenceLineFromRouting()) {
AERROR << "Failed to create reference line from position: "
<< init_pose_.DebugString();
return false;
}
if (FLAGS_enable_prediction) {
CreateObstacles(prediction_);
}
return true;
}
uint32_t Frame::sequence_num() const { return sequence_num_; }
const PlanningData &Frame::planning_data() const { return _planning_data; }
PlanningData *Frame::mutable_planning_data() { return &_planning_data; }
void Frame::set_computed_trajectory(const PublishableTrajectory &trajectory) {
_computed_trajectory = trajectory;
}
const PublishableTrajectory &Frame::computed_trajectory() const {
return _computed_trajectory;
}
const ReferenceLine &Frame::reference_line() const { return *reference_line_; }
bool Frame::CreateReferenceLineFromRouting() {
common::PointENU vehicle_position;
vehicle_position.set_x(init_pose_.position().x());
vehicle_position.set_y(init_pose_.position().y());
vehicle_position.set_z(init_pose_.position().z());
if (!pnc_map_->CreatePathFromRouting(
routing_result_, vehicle_position, FLAGS_look_backward_distance,
FLAGS_look_forward_distance, &hdmap_path_)) {
AERROR << "Failed to get path from routing";
return false;
}
if (!SmoothReferenceLine()) {
AERROR << "Failed to smooth reference line";
return false;
}
return true;
}
bool Frame::SmoothReferenceLine() {
std::vector<ReferencePoint> ref_points;
for (const auto &point : hdmap_path_.path_points()) {
if (point.lane_waypoints().empty()) {
AERROR << "path point has no lane_waypoint";
return false;
}
const auto &lane_waypoint = point.lane_waypoints()[0];
ref_points.emplace_back(point, point.heading(), 0.0, 0.0, lane_waypoint);
}
if (ref_points.empty()) {
AERROR << "Found no reference points from map";
return false;
}
std::unique_ptr<ReferenceLine> reference_line(new ReferenceLine(ref_points));
std::vector<ReferencePoint> smoothed_ref_points;
ReferenceLineSmoother smoother;
if (!smoother.Init(FLAGS_reference_line_smoother_config_file)) {
AERROR << "Failed to load file "
<< FLAGS_reference_line_smoother_config_file;
return false;
}
if (!smoother.smooth(*reference_line, &smoothed_ref_points)) {
AERROR << "Fail to smooth a reference line from map";
return false;
}
ADEBUG << "smooth reference points num:" << smoothed_ref_points.size();
reference_line_.reset(new ReferenceLine(smoothed_ref_points));
return true;
}
const Obstacles &Frame::GetObstacles() const { return obstacles_; }
Obstacles *Frame::MutableObstacles() { return &obstacles_; }
std::string Frame::DebugString() const {
return "Frame: " + std::to_string(sequence_num_);
}
} // namespace planning
} // namespace apollo
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/prediction/prediction.h"
#include <cmath>
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/util/file.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/container/pose/pose_container.h"
#include "modules/prediction/evaluator/evaluator_manager.h"
#include "modules/prediction/predictor/predictor_manager.h"
#include "modules/prediction/proto/prediction_obstacle.pb.h"
namespace apollo {
namespace prediction {
using ::apollo::common::ErrorCode;
using ::apollo::common::Status;
using ::apollo::common::TrajectoryPoint;
using ::apollo::common::adapter::AdapterConfig;
using ::apollo::common::adapter::AdapterManager;
using ::apollo::localization::LocalizationEstimate;
using ::apollo::perception::PerceptionObstacle;
using ::apollo::perception::PerceptionObstacles;
std::string Prediction::Name() const { return FLAGS_prediction_module_name; }
Status Prediction::Init() {
// Load prediction conf
prediction_conf_.Clear();
if (!common::util::GetProtoFromFile(FLAGS_prediction_conf_file,
&prediction_conf_)) {
return OnError("Unable to load prediction conf file: " +
FLAGS_prediction_conf_file);
} else {
ADEBUG << "Prediction config file is loaded into: "
<< prediction_conf_.ShortDebugString();
}
adapter_conf_.Clear();
if (!common::util::GetProtoFromFile(FLAGS_prediction_adapter_config_filename,
&adapter_conf_)) {
return OnError("Unable to load adapter conf file: " +
FLAGS_prediction_adapter_config_filename);
} else {
ADEBUG << "Adapter config file is loaded into: "
<< adapter_conf_.ShortDebugString();
}
// Initialization of all managers
AdapterManager::Init(adapter_conf_);
ContainerManager::instance()->Init(adapter_conf_);
EvaluatorManager::instance()->Init(prediction_conf_);
PredictorManager::instance()->Init(prediction_conf_);
CHECK(AdapterManager::GetLocalization()) << "Localization is not ready.";
CHECK(AdapterManager::GetPerceptionObstacles()) << "Perception is not ready.";
// Set perception obstacle callback function
AdapterManager::AddPerceptionObstaclesCallback(&Prediction::OnPerception,
this);
// Set localization callback function
AdapterManager::AddLocalizationCallback(&Prediction::OnLocalization, this);
return Status::OK();
}
Status Prediction::Start() { return Status::OK(); }
void Prediction::Stop() {}
void Prediction::OnLocalization(const LocalizationEstimate& localization) {
ObstaclesContainer* obstacles_container = dynamic_cast<ObstaclesContainer*>(
ContainerManager::instance()->GetContainer(
AdapterConfig::PERCEPTION_OBSTACLES));
CHECK_NOTNULL(obstacles_container);
PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
ContainerManager::instance()->GetContainer(AdapterConfig::LOCALIZATION));
CHECK_NOTNULL(pose_container);
pose_container->Insert(localization);
PerceptionObstacle* pose_ptr = pose_container->ToPerceptionObstacle();
if (pose_ptr != nullptr) {
obstacles_container->InsertPerceptionObstacle(
*(pose_ptr), pose_container->GetTimestamp());
} else {
ADEBUG << "Invalid pose found.";
}
// ADEBUG << "Received a localization message ["
// << localization.ShortDebugString() << "].";
}
void Prediction::OnPerception(const PerceptionObstacles& perception_obstacles) {
ObstaclesContainer* obstacles_container = dynamic_cast<ObstaclesContainer*>(
ContainerManager::instance()->GetContainer(
AdapterConfig::PERCEPTION_OBSTACLES));
CHECK_NOTNULL(obstacles_container);
obstacles_container->Insert(perception_obstacles);
EvaluatorManager::instance()->Run(perception_obstacles);
PredictorManager::instance()->Run(perception_obstacles);
auto prediction_obstacles =
PredictorManager::instance()->prediction_obstacles();
AdapterManager::FillPredictionHeader(Name(), &prediction_obstacles);
AdapterManager::PublishPrediction(prediction_obstacles);
for (auto const& prediction_obstacle :
prediction_obstacles.prediction_obstacle()) {
for (auto const& trajectory : prediction_obstacle.trajectory()) {
for (auto const& trajectory_point : trajectory.trajectory_point()) {
CHECK(IsValidTrajectoryPoint(trajectory_point));
}
}
}
}
Status Prediction::OnError(const std::string& error_msg) {
return Status(ErrorCode::PREDICTION_ERROR, error_msg);
}
bool Prediction::IsValidTrajectoryPoint(
const TrajectoryPoint& trajectory_point) {
return (!std::isnan(trajectory_point.path_point().x())) &&
(!std::isnan(trajectory_point.path_point().y())) &&
(!std::isnan(trajectory_point.path_point().theta())) &&
(!std::isnan(trajectory_point.v())) &&
(!std::isnan(trajectory_point.a())) &&
(!std::isnan(trajectory_point.relative_time()));
}
} // namespace prediction
} // namespace apollo
<commit_msg>Prediction: restored debug message printing<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/prediction/prediction.h"
#include <cmath>
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/util/file.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/container/pose/pose_container.h"
#include "modules/prediction/evaluator/evaluator_manager.h"
#include "modules/prediction/predictor/predictor_manager.h"
#include "modules/prediction/proto/prediction_obstacle.pb.h"
namespace apollo {
namespace prediction {
using ::apollo::common::ErrorCode;
using ::apollo::common::Status;
using ::apollo::common::TrajectoryPoint;
using ::apollo::common::adapter::AdapterConfig;
using ::apollo::common::adapter::AdapterManager;
using ::apollo::localization::LocalizationEstimate;
using ::apollo::perception::PerceptionObstacle;
using ::apollo::perception::PerceptionObstacles;
std::string Prediction::Name() const { return FLAGS_prediction_module_name; }
Status Prediction::Init() {
// Load prediction conf
prediction_conf_.Clear();
if (!common::util::GetProtoFromFile(FLAGS_prediction_conf_file,
&prediction_conf_)) {
return OnError("Unable to load prediction conf file: " +
FLAGS_prediction_conf_file);
} else {
ADEBUG << "Prediction config file is loaded into: "
<< prediction_conf_.ShortDebugString();
}
adapter_conf_.Clear();
if (!common::util::GetProtoFromFile(FLAGS_prediction_adapter_config_filename,
&adapter_conf_)) {
return OnError("Unable to load adapter conf file: " +
FLAGS_prediction_adapter_config_filename);
} else {
ADEBUG << "Adapter config file is loaded into: "
<< adapter_conf_.ShortDebugString();
}
// Initialization of all managers
AdapterManager::Init(adapter_conf_);
ContainerManager::instance()->Init(adapter_conf_);
EvaluatorManager::instance()->Init(prediction_conf_);
PredictorManager::instance()->Init(prediction_conf_);
CHECK(AdapterManager::GetLocalization()) << "Localization is not ready.";
CHECK(AdapterManager::GetPerceptionObstacles()) << "Perception is not ready.";
// Set perception obstacle callback function
AdapterManager::AddPerceptionObstaclesCallback(&Prediction::OnPerception,
this);
// Set localization callback function
AdapterManager::AddLocalizationCallback(&Prediction::OnLocalization, this);
return Status::OK();
}
Status Prediction::Start() { return Status::OK(); }
void Prediction::Stop() {}
void Prediction::OnLocalization(const LocalizationEstimate& localization) {
ObstaclesContainer* obstacles_container = dynamic_cast<ObstaclesContainer*>(
ContainerManager::instance()->GetContainer(
AdapterConfig::PERCEPTION_OBSTACLES));
CHECK_NOTNULL(obstacles_container);
PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
ContainerManager::instance()->GetContainer(AdapterConfig::LOCALIZATION));
CHECK_NOTNULL(pose_container);
pose_container->Insert(localization);
PerceptionObstacle* pose_ptr = pose_container->ToPerceptionObstacle();
if (pose_ptr != nullptr) {
obstacles_container->InsertPerceptionObstacle(
*(pose_ptr), pose_container->GetTimestamp());
} else {
ADEBUG << "Invalid pose found.";
}
ADEBUG << "Received a localization message ["
<< localization.ShortDebugString() << "].";
}
void Prediction::OnPerception(const PerceptionObstacles& perception_obstacles) {
ObstaclesContainer* obstacles_container = dynamic_cast<ObstaclesContainer*>(
ContainerManager::instance()->GetContainer(
AdapterConfig::PERCEPTION_OBSTACLES));
CHECK_NOTNULL(obstacles_container);
obstacles_container->Insert(perception_obstacles);
EvaluatorManager::instance()->Run(perception_obstacles);
PredictorManager::instance()->Run(perception_obstacles);
auto prediction_obstacles =
PredictorManager::instance()->prediction_obstacles();
AdapterManager::FillPredictionHeader(Name(), &prediction_obstacles);
AdapterManager::PublishPrediction(prediction_obstacles);
for (auto const& prediction_obstacle :
prediction_obstacles.prediction_obstacle()) {
for (auto const& trajectory : prediction_obstacle.trajectory()) {
for (auto const& trajectory_point : trajectory.trajectory_point()) {
CHECK(IsValidTrajectoryPoint(trajectory_point));
}
}
}
ADEBUG << "Received a perception message ["
<< perception_obstacles.ShortDebugString() << "].";
}
Status Prediction::OnError(const std::string& error_msg) {
return Status(ErrorCode::PREDICTION_ERROR, error_msg);
}
bool Prediction::IsValidTrajectoryPoint(
const TrajectoryPoint& trajectory_point) {
return (!std::isnan(trajectory_point.path_point().x())) &&
(!std::isnan(trajectory_point.path_point().y())) &&
(!std::isnan(trajectory_point.path_point().theta())) &&
(!std::isnan(trajectory_point.v())) &&
(!std::isnan(trajectory_point.a())) &&
(!std::isnan(trajectory_point.relative_time()));
}
} // namespace prediction
} // namespace apollo
<|endoftext|> |
<commit_before>//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
/*++
Module Name:
common.c
Abstract:
Implementation of the common mapping functions.
--*/
#include "pal/palinternal.h"
#include "pal/dbgmsg.h"
#include "common.h"
#include <sys/mman.h>
SET_DEFAULT_DEBUG_CHANNEL(VIRTUAL);
/*****
*
* W32toUnixAccessControl( DWORD ) - Maps Win32 to Unix memory access controls .
*
*/
INT W32toUnixAccessControl( IN DWORD flProtect )
{
INT MemAccessControl = 0;
switch ( flProtect & 0xff )
{
case PAGE_READONLY :
MemAccessControl = PROT_READ;
break;
case PAGE_READWRITE :
MemAccessControl = PROT_READ | PROT_WRITE;
break;
case PAGE_EXECUTE_READWRITE:
MemAccessControl = PROT_EXEC | PROT_READ | PROT_WRITE;
break;
case PAGE_EXECUTE :
MemAccessControl = PROT_EXEC;
break;
case PAGE_EXECUTE_READ :
MemAccessControl = PROT_EXEC | PROT_READ;
break;
case PAGE_NOACCESS :
MemAccessControl = PROT_NONE;
break;
default:
MemAccessControl = 0;
ERROR( "Incorrect or no protection flags specified.\n" );
break;
}
return MemAccessControl;
}
<commit_msg>Fix Segmentation fault on Linux Skylake server<commit_after>//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
/*++
Module Name:
common.c
Abstract:
Implementation of the common mapping functions.
--*/
#include "pal/palinternal.h"
#include "pal/dbgmsg.h"
#include "common.h"
#include <sys/mman.h>
SET_DEFAULT_DEBUG_CHANNEL(VIRTUAL);
/*****
*
* W32toUnixAccessControl( DWORD ) - Maps Win32 to Unix memory access controls .
*
*/
INT W32toUnixAccessControl( IN DWORD flProtect )
{
INT MemAccessControl = 0;
switch ( flProtect & 0xff )
{
case PAGE_READONLY :
MemAccessControl = PROT_READ;
break;
case PAGE_READWRITE :
MemAccessControl = PROT_READ | PROT_WRITE;
break;
case PAGE_EXECUTE_READWRITE:
MemAccessControl = PROT_EXEC | PROT_READ | PROT_WRITE;
break;
case PAGE_EXECUTE :
MemAccessControl = PROT_EXEC | PROT_READ; // WinAPI PAGE_EXECUTE also implies readable
break;
case PAGE_EXECUTE_READ :
MemAccessControl = PROT_EXEC | PROT_READ;
break;
case PAGE_NOACCESS :
MemAccessControl = PROT_NONE;
break;
default:
MemAccessControl = 0;
ERROR( "Incorrect or no protection flags specified.\n" );
break;
}
return MemAccessControl;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>
const int num_of_pages = 1500000; // >= 1483276
int relCount[num_of_pages];
int num_of_rels = 0;
int main(int argc, char *argv[])
{
std::ifstream ifs;
ifs.open("rel.bin");
while(!ifs.eof()){
int fromID, toID;
ifs.read((char *)&fromID, sizeof(int));
ifs.read((char *)&toID, sizeof(int));
//std::cout << fromID << "," << toID << std::endl;
num_of_rels ++;
/*
if(fromID < num_of_pages) relCount[fromID]++;
if(lastFrom != fromID){
std::cout << lastFrom << "\t" << relCount[lastFrom] << std::endl;
lastFrom = fromID;
}
*/
}
std::cout << "ready: " << num_of_rels << std::endl;
/*
while(!ifs.eof()){
int fromID, toID;
ifs.read((char *)&fromID, sizeof(int));
ifs.read((char *)&toID, sizeof(int));
//std::cout << fromID << "," << toID << std::endl;
num_of_rels ++;
if(fromID < num_of_pages) relCount[fromID]++;
if(lastFrom != fromID){
std::cout << lastFrom << "\t" << relCount[lastFrom] << std::endl;
lastFrom = fromID;
}
}
*/
/*
int maxIndex = 0;
for(int i = 0; i <= num_of_pages; i++){
if(relCount[i] >= relCount[maxIndex]) maxIndex = i;
}
std::cout << "max: " << maxIndex << "\t" << relCount[maxIndex] << std::endl;
*/
return 0;
}
<commit_msg>Update binrel.cpp<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>
const int max_pages = 1500000; // >= 1483276
int rels[64 * 1024 * 1024][2]; // [from, to]
int num_of_rels = 0;
std::ifstream ifs_pages;
std::string title[max_pages];
int num_of_pages = 0;
void scanPages()
{
std::cout << "scanPages: begin" << std::endl;
ifs_pages.open("wikipedia_links/pages.txt");
while(!ifs_pages.eof()){
std::string line, token;
std::getline(ifs_pages, line);
std::istringstream stream(line);
std::string id;
getline(stream, id,'\t');
getline(stream, title[num_of_pages++],'\t');
}
std::cout << "scanPages: end" << std::endl;
}
void scanRels()
{
std::ifstream ifs;
ifs.open("rel.bin");
std::cout << "scanRels: begin" << std::endl;
while(!ifs.eof()){
ifs.read((char *)&rels[num_of_rels][0], sizeof(int));
ifs.read((char *)&rels[num_of_rels][1], sizeof(int));
num_of_rels++;
}
std::cout << "scanRels: end" << std::endl;
}
int main(int argc, char *argv[])
{
scanPages();
scanRels();
std::cout << "ready: rels = " << num_of_rels << std::endl;
//
while(1){
int root_index;
std::cout << "Input root index: " << std::endl;
std::cin >> root_index;
if(root_index < 0 || num_of_pages <= root_index){
std::cout << "Out of bound." << std::endl;
break;
}
std::cout << "root: " << root_index << ": " << title[root_index] << std::endl;
//
for(int i = 0; i < num_of_rels; i++){
if(rels[i][0] == root_index){
int to = rels[i][1];
std::cout << "\t" << to << "\t" << title[to] << std::endl;
}
}
}
return 0;
}
<|endoftext|> |
<commit_before>// ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2010, Knut Reinert, FU Berlin
// 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de>
// ==========================================================================
// Tests for the paramChooser.h header.
//
// Currently, we only test the I/O routines from this file.
// ==========================================================================
#undef SEQAN_ENABLE_TESTING
#define SEQAN_ENABLE_TESTING 1
#include <sstream>
#include <seqan/basic.h>
#include <seqan/file.h>
#include "../../../core/apps/splazers/paramChooser.h"
SEQAN_DEFINE_TEST(test_param_chooser_quality_distribution_from_prb_file)
{
seqan::ParamChooserOptions pmOptions;
pmOptions.totalN = 4; // Read length.
pmOptions.verbose = false;
pmOptions.qualityCutoff = 10; // Ignore reads with smaller average quality than threshold.
seqan::String<double> qualDist;
std::stringstream ss;
ss << "40 -40 -40 -40 10 20 30 40 30 30 20 10 10 20 10 10\n"
<< "10 -40 -40 -40 10 10 0 10 9 0 0 0 5 5 5 10\n"
<< "40 -40 -40 -40 10 20 30 40 30 30 20 10 10 20 10 10";
ss.seekg(0);
SEQAN_ASSERT_EQ(qualityDistributionFromPrbFile(ss, qualDist, pmOptions), 0);
SEQAN_ASSERT_EQ(length(qualDist), 4u);
SEQAN_ASSERT_IN_DELTA(qualDist[0], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[1], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[2], 0.000999001, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[3], 0.00990099, 1.0e-07);
}
SEQAN_DEFINE_TEST(test_param_chooser_quality_distribution_from_fastq_file)
{
seqan::ParamChooserOptions pmOptions;
pmOptions.totalN = 4; // Read length.
pmOptions.verbose = false;
pmOptions.qualityCutoff = 10; // Ignore reads with smaller average quality than threshold.
seqan::String<double> qualDist;
std::stringstream ss;
ss << "@1\n"
<< "CGAT\n"
<< "+\n"
<< "II?5\n"
// << "@2\n" // see prb test, but from FASTQ does not kick out bad reads
// << "CGAT\n"
// << "+\n"
// << "+!*+\n"
<< "@3\n"
<< "CGAT\n"
<< "+\n"
<< "II?5";
ss.seekg(0);
SEQAN_ASSERT_EQ(qualityDistributionFromFastQFile(ss, qualDist, pmOptions), 0);
SEQAN_ASSERT_EQ(length(qualDist), 4u);
SEQAN_ASSERT_IN_DELTA(qualDist[0], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[1], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[2], 0.000999001, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[3], 0.00990099, 1.0e-07);
}
SEQAN_DEFINE_TEST(test_param_chooser_quality_distribution_from_fastq_int_file)
{
seqan::ParamChooserOptions pmOptions;
pmOptions.totalN = 4; // Read length.
pmOptions.verbose = false;
pmOptions.qualityCutoff = 10; // Ignore reads with smaller average quality than threshold.
seqan::String<double> qualDist;
std::stringstream ss;
ss << "@1\n"
<< "CGAT\n"
<< "+\n"
<< "40 40 30 20\n"
// << "@2\n" // see prb test, but from FASTQ does not kick out bad reads
// << "CGAT\n"
// << "+\n"
// << "+!*+\n"
<< "@3\n"
<< "CGAT\n"
<< "+\n"
<< "40 40 30 20";
ss.seekg(0);
SEQAN_ASSERT_EQ(qualityDistributionFromFastQIntFile(ss, qualDist, pmOptions), 0);
SEQAN_ASSERT_EQ(length(qualDist), 4u);
SEQAN_ASSERT_IN_DELTA(qualDist[0], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[1], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[2], 0.000999001, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[3], 0.00990099, 1.0e-07);
}
SEQAN_BEGIN_TESTSUITE(test_param_chooser)
{
SEQAN_CALL_TEST(test_param_chooser_quality_distribution_from_prb_file);
SEQAN_CALL_TEST(test_param_chooser_quality_distribution_from_fastq_file);
SEQAN_CALL_TEST(test_param_chooser_quality_distribution_from_fastq_int_file);
}
SEQAN_END_TESTSUITE
<commit_msg>[TEST] Adding test for parseGappedParams in paramChooser.h.<commit_after>// ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2010, Knut Reinert, FU Berlin
// 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de>
// ==========================================================================
// Tests for the paramChooser.h header.
//
// Currently, we only test the I/O routines from this file.
// ==========================================================================
#undef SEQAN_ENABLE_TESTING
#define SEQAN_ENABLE_TESTING 1
#include <sstream>
#include <seqan/basic.h>
#include <seqan/file.h>
#include "../../../core/apps/splazers/paramChooser.h"
SEQAN_DEFINE_TEST(test_param_chooser_quality_distribution_from_prb_file)
{
seqan::ParamChooserOptions pmOptions;
pmOptions.totalN = 4; // Read length.
pmOptions.verbose = false;
pmOptions.qualityCutoff = 10; // Ignore reads with smaller average quality than threshold.
seqan::String<double> qualDist;
std::stringstream ss;
ss << "40 -40 -40 -40 10 20 30 40 30 30 20 10 10 20 10 10\n"
<< "10 -40 -40 -40 10 10 0 10 9 0 0 0 5 5 5 10\n"
<< "40 -40 -40 -40 10 20 30 40 30 30 20 10 10 20 10 10";
ss.seekg(0);
SEQAN_ASSERT_EQ(qualityDistributionFromPrbFile(ss, qualDist, pmOptions), 0);
SEQAN_ASSERT_EQ(length(qualDist), 4u);
SEQAN_ASSERT_IN_DELTA(qualDist[0], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[1], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[2], 0.000999001, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[3], 0.00990099, 1.0e-07);
}
SEQAN_DEFINE_TEST(test_param_chooser_quality_distribution_from_fastq_file)
{
seqan::ParamChooserOptions pmOptions;
pmOptions.totalN = 4; // Read length.
pmOptions.verbose = false;
pmOptions.qualityCutoff = 10; // Ignore reads with smaller average quality than threshold.
seqan::String<double> qualDist;
std::stringstream ss;
ss << "@1\n"
<< "CGAT\n"
<< "+\n"
<< "II?5\n"
// << "@2\n" // see prb test, but from FASTQ does not kick out bad reads
// << "CGAT\n"
// << "+\n"
// << "+!*+\n"
<< "@3\n"
<< "CGAT\n"
<< "+\n"
<< "II?5";
ss.seekg(0);
SEQAN_ASSERT_EQ(qualityDistributionFromFastQFile(ss, qualDist, pmOptions), 0);
SEQAN_ASSERT_EQ(length(qualDist), 4u);
SEQAN_ASSERT_IN_DELTA(qualDist[0], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[1], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[2], 0.000999001, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[3], 0.00990099, 1.0e-07);
}
SEQAN_DEFINE_TEST(test_param_chooser_quality_distribution_from_fastq_int_file)
{
seqan::ParamChooserOptions pmOptions;
pmOptions.totalN = 4; // Read length.
pmOptions.verbose = false;
pmOptions.qualityCutoff = 10; // Ignore reads with smaller average quality than threshold.
seqan::String<double> qualDist;
std::stringstream ss;
ss << "@1\n"
<< "CGAT\n"
<< "+\n"
<< "40 40 30 20\n"
// << "@2\n" // see prb test, but from FASTQ does not kick out bad reads
// << "CGAT\n"
// << "+\n"
// << "+!*+\n"
<< "@3\n"
<< "CGAT\n"
<< "+\n"
<< "40 40 30 20";
ss.seekg(0);
SEQAN_ASSERT_EQ(qualityDistributionFromFastQIntFile(ss, qualDist, pmOptions), 0);
SEQAN_ASSERT_EQ(length(qualDist), 4u);
SEQAN_ASSERT_IN_DELTA(qualDist[0], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[1], 9.999e-05, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[2], 0.000999001, 1.0e-07);
SEQAN_ASSERT_IN_DELTA(qualDist[3], 0.00990099, 1.0e-07);
}
SEQAN_DEFINE_TEST(test_param_chooser_parse_read_gapped_params)
{
seqan::ParamChooserOptions pmOptions;
pmOptions.totalN = 4; // Read length.
pmOptions.verbose = false;
pmOptions.chooseOneGappedOnly = false;
pmOptions.chooseUngappedOnly = false;
pmOptions.minThreshold = 3;
pmOptions.optionLossRate = 0.01;
seqan::RazerSOptions<> rOptions;
std::stringstream ss;
ss << "errors shape t lossrate PM\n"
<< "\n"
<< "0 11000000100100101 3 0 40895\n"
<< "1 11000000100100101 2 0 492286\n"
<< "2 11000000100100101 1 0.0293446 48417798\n"
<< "3 11000000100100101 1 0.195237 48417798\n"
<< "0 1111100001 10 0 40484\n"
<< "1 1111100001 7 0.163535 48622\n"
<< "1 1111100001 6 0.0497708 51290\n"
<< "1 1111100001 5 0 61068\n"
<< "1 1111101 4 0 61068";
ss.seekg(0);
SEQAN_ASSERT(parseGappedParams(rOptions, ss, pmOptions));
SEQAN_ASSERT_EQ(rOptions.shape, "1111100001");
SEQAN_ASSERT_EQ(rOptions.threshold, 10);
pmOptions.chooseOneGappedOnly = true;
ss.clear();
ss.seekg(0);
SEQAN_ASSERT(parseGappedParams(rOptions, ss, pmOptions));
SEQAN_ASSERT_EQ(rOptions.shape, "1111100001");
SEQAN_ASSERT_EQ(rOptions.threshold, 10);
pmOptions.chooseUngappedOnly = true;
ss.clear();
ss.seekg(0);
SEQAN_ASSERT_NOT(parseGappedParams(rOptions, ss, pmOptions));
}
SEQAN_BEGIN_TESTSUITE(test_param_chooser)
{
SEQAN_CALL_TEST(test_param_chooser_quality_distribution_from_prb_file);
SEQAN_CALL_TEST(test_param_chooser_quality_distribution_from_fastq_file);
SEQAN_CALL_TEST(test_param_chooser_quality_distribution_from_fastq_int_file);
SEQAN_CALL_TEST(test_param_chooser_parse_read_gapped_params);
}
SEQAN_END_TESTSUITE
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: popupmenucontrollerbase.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2005-03-01 19:24:35 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef __FRAMEWORK_HELPER_POPUPMENUCONTROLLERBASE_HXX_
#define __FRAMEWORK_HELPER_POPUPMENUCONTROLLERBASE_HXX_
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_
#include <macros/xserviceinfo.hxx>
#endif
#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_
#include <com/sun/star/frame/XDispatch.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_
#include <com/sun/star/frame/XStatusListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XPOPUPMENUCONTROLLER_HPP_
#include <com/sun/star/frame/XPopupMenuController.hpp>
#endif
//_________________________________________________________________________________________________________________
// includes of other projects
//_________________________________________________________________________________________________________________
#ifndef _TOOLKIT_AWT_VCLXMENU_HXX_
#include <toolkit/awt/vclxmenu.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
namespace framework
{
class PopupMenuControllerBase : public com::sun::star::lang::XTypeProvider ,
public com::sun::star::lang::XServiceInfo ,
public ::com::sun::star::frame::XPopupMenuController ,
public com::sun::star::lang::XInitialization ,
public com::sun::star::frame::XStatusListener ,
public com::sun::star::awt::XMenuListener ,
protected ThreadHelpBase , // Struct for right initalization of mutex member! Must be first of baseclasses.
public ::cppu::OWeakObject
{
public:
PopupMenuControllerBase( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );
virtual ~PopupMenuControllerBase();
// XInterface, XTypeProvider, XServiceInfo
DECLARE_XINTERFACE
DECLARE_XTYPEPROVIDER
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException) = 0;
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException) = 0;
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException) = 0;
// XPopupMenuController
virtual void SAL_CALL setPopupMenu( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XPopupMenu >& PopupMenu ) throw (::com::sun::star::uno::RuntimeException) = 0;
virtual void SAL_CALL updatePopupMenu() throw (::com::sun::star::uno::RuntimeException);
// XInitialization
virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
// XStatusListener
virtual void SAL_CALL statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event ) throw ( ::com::sun::star::uno::RuntimeException ) = 0;
// XMenuListener
virtual void SAL_CALL highlight( const ::com::sun::star::awt::MenuEvent& rEvent ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL select( const ::com::sun::star::awt::MenuEvent& rEvent ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL activate( const ::com::sun::star::awt::MenuEvent& rEvent ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL deactivate( const ::com::sun::star::awt::MenuEvent& rEvent ) throw (::com::sun::star::uno::RuntimeException);
// XEventListener
virtual void SAL_CALL disposing( const com::sun::star::lang::EventObject& Source ) throw ( ::com::sun::star::uno::RuntimeException );
protected:
virtual void resetPopupMenu( com::sun::star::uno::Reference< com::sun::star::awt::XPopupMenu >& rPopupMenu );
sal_Bool m_bInitialized;
rtl::OUString m_aCommandURL;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > m_xDispatch;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > m_xFrame;
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceManager;
::com::sun::star::uno::Reference< ::com::sun::star::awt::XPopupMenu > m_xPopupMenu;
};
}
#endif // __FRAMEWORK_HELPER_POPUPMENUCONTROLLERBASE_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.128); FILE MERGED 2005/09/05 13:04:51 rt 1.3.128.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: popupmenucontrollerbase.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 00:18:37 $
*
* 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 __FRAMEWORK_HELPER_POPUPMENUCONTROLLERBASE_HXX_
#define __FRAMEWORK_HELPER_POPUPMENUCONTROLLERBASE_HXX_
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_
#include <macros/xserviceinfo.hxx>
#endif
#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_
#include <com/sun/star/frame/XDispatch.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_
#include <com/sun/star/frame/XStatusListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XPOPUPMENUCONTROLLER_HPP_
#include <com/sun/star/frame/XPopupMenuController.hpp>
#endif
//_________________________________________________________________________________________________________________
// includes of other projects
//_________________________________________________________________________________________________________________
#ifndef _TOOLKIT_AWT_VCLXMENU_HXX_
#include <toolkit/awt/vclxmenu.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
namespace framework
{
class PopupMenuControllerBase : public com::sun::star::lang::XTypeProvider ,
public com::sun::star::lang::XServiceInfo ,
public ::com::sun::star::frame::XPopupMenuController ,
public com::sun::star::lang::XInitialization ,
public com::sun::star::frame::XStatusListener ,
public com::sun::star::awt::XMenuListener ,
protected ThreadHelpBase , // Struct for right initalization of mutex member! Must be first of baseclasses.
public ::cppu::OWeakObject
{
public:
PopupMenuControllerBase( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );
virtual ~PopupMenuControllerBase();
// XInterface, XTypeProvider, XServiceInfo
DECLARE_XINTERFACE
DECLARE_XTYPEPROVIDER
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException) = 0;
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException) = 0;
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException) = 0;
// XPopupMenuController
virtual void SAL_CALL setPopupMenu( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XPopupMenu >& PopupMenu ) throw (::com::sun::star::uno::RuntimeException) = 0;
virtual void SAL_CALL updatePopupMenu() throw (::com::sun::star::uno::RuntimeException);
// XInitialization
virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
// XStatusListener
virtual void SAL_CALL statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event ) throw ( ::com::sun::star::uno::RuntimeException ) = 0;
// XMenuListener
virtual void SAL_CALL highlight( const ::com::sun::star::awt::MenuEvent& rEvent ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL select( const ::com::sun::star::awt::MenuEvent& rEvent ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL activate( const ::com::sun::star::awt::MenuEvent& rEvent ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL deactivate( const ::com::sun::star::awt::MenuEvent& rEvent ) throw (::com::sun::star::uno::RuntimeException);
// XEventListener
virtual void SAL_CALL disposing( const com::sun::star::lang::EventObject& Source ) throw ( ::com::sun::star::uno::RuntimeException );
protected:
virtual void resetPopupMenu( com::sun::star::uno::Reference< com::sun::star::awt::XPopupMenu >& rPopupMenu );
sal_Bool m_bInitialized;
rtl::OUString m_aCommandURL;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > m_xDispatch;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > m_xFrame;
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceManager;
::com::sun::star::uno::Reference< ::com::sun::star::awt::XPopupMenu > m_xPopupMenu;
};
}
#endif // __FRAMEWORK_HELPER_POPUPMENUCONTROLLERBASE_HXX_
<|endoftext|> |
<commit_before>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org>
* Copyright (c) 2010 Ruslan Kabatsayev <b7.10110111@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or(at your option ) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include <gtk/gtk.h>
#include "oxygeninnershadowdata.h"
#include "../oxygengtkutils.h"
#include "../config.h"
#include "../oxygencairocontext.h"
#include "oxygenanimations.h"
#include "../oxygenstyle.h"
#include "../oxygenmetrics.h"
#include <stdlib.h>
#include <cassert>
#include <iostream>
namespace Oxygen
{
//_____________________________________________
void InnerShadowData::connect( GtkWidget* widget )
{
assert( GTK_IS_SCROLLED_WINDOW( widget ) );
assert( !_target );
// store target
_target = widget;
if( gdk_display_supports_composite( gtk_widget_get_display( widget ) ) && G_OBJECT_TYPE_NAME(widget) != std::string("GtkPizza") )
{
_compositeEnabled = true;
_exposeId.connect( G_OBJECT(_target), "expose-event", G_CALLBACK( targetExposeEvent ), this, true );
}
// check child
GtkWidget* child( gtk_bin_get_child( GTK_BIN( widget ) ) );
if( !child ) return;
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::InnerShadowData::connect -"
<< " widget: " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< " child: " << child << " (" << G_OBJECT_TYPE_NAME( child ) << ")"
<< std::endl;
#endif
registerChild( child );
}
//_____________________________________________
void InnerShadowData::disconnect( GtkWidget* )
{
_target = 0;
for( ChildDataMap::reverse_iterator iter = _childrenData.rbegin(); iter != _childrenData.rend(); ++iter )
{ iter->second.disconnect( iter->first ); }
// disconnect signals
_exposeId.disconnect();
// clear child data
_childrenData.clear();
}
//_____________________________________________
void InnerShadowData::registerChild( GtkWidget* widget )
{
#if ENABLE_INNER_SHADOWS_HACK
// make sure widget is not already in map
if( _childrenData.find( widget ) != _childrenData.end() ) return;
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::InnerShadowData::registerChild -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
GdkWindow* window(gtk_widget_get_window(widget));
if(
// check window
window &&
gdk_window_get_window_type( window ) == GDK_WINDOW_CHILD &&
// check compositing
gdk_display_supports_composite( gtk_widget_get_display( widget ) ) &&
// check widget type (might move to blacklist method)
( G_OBJECT_TYPE_NAME(widget) != std::string("GtkPizza") ) &&
// make sure widget is scrollable
GTK_WIDGET_GET_CLASS( widget )->set_scroll_adjustments_signal )
{
ChildData data;
data._unrealizeId.connect( G_OBJECT(widget), "unrealize", G_CALLBACK( childUnrealizeNotifyEvent ), this );
data._initiallyComposited = gdk_window_get_composited(window);
gdk_window_set_composited(window,TRUE);
_childrenData.insert( std::make_pair( widget, data ) );
}
#endif
}
//________________________________________________________________________________
void InnerShadowData::unregisterChild( GtkWidget* widget )
{
ChildDataMap::iterator iter( _childrenData.find( widget ) );
if( iter == _childrenData.end() ) return;
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::InnerShadowData::unregisterChild -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
iter->second.disconnect( widget );
_childrenData.erase( iter );
}
//________________________________________________________________________________
void InnerShadowData::ChildData::disconnect( GtkWidget* widget )
{
// disconnect signals
_unrealizeId.disconnect();
// remove compositing flag
GdkWindow* window( gtk_widget_get_window( widget ) );
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::InnerShadowData::ChildData::disconnect -"
<< " widget: " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< " window: " << window
<< std::endl;
#endif
// restore compositing if different from initial state
if( GDK_IS_WINDOW( window ) && !gdk_window_is_destroyed(window) && gdk_window_get_composited( window ) != _initiallyComposited )
{ gdk_window_set_composited( window, _initiallyComposited ); }
}
//____________________________________________________________________________________________
gboolean InnerShadowData::childUnrealizeNotifyEvent( GtkWidget* widget, gpointer data )
{
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::InnerShadowData::childUnrealizeNotifyEvent -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
static_cast<InnerShadowData*>(data)->unregisterChild( widget );
return FALSE;
}
//_________________________________________________________________________________________
gboolean InnerShadowData::targetExposeEvent( GtkWidget* widget, GdkEventExpose* event, gpointer )
{
#if ENABLE_INNER_SHADOWS_HACK
GtkWidget* child=gtk_bin_get_child(GTK_BIN(widget));
GdkWindow* window=gtk_widget_get_window(child);
#if OXYGEN_DEBUG
std::cerr << "Oxygen::InnerShadowData::targetExposeEvent -"
<< " widget: " << widget << " (" << G_OBJECT_TYPE_NAME(widget) << ")"
<< " child: " << child << " (" << G_OBJECT_TYPE_NAME(widget) << ")"
<< " path: " << Gtk::gtk_widget_path( child )
<< " area: " << event->area
<< std::endl;
#endif
if(!gdk_window_get_composited(window))
{
#if OXYGEN_DEBUG
std::cerr << "Oxygen::InnerShadowData::targetExposeEvent - Window isn't composite. Doing nohing\n";
#endif
return FALSE;
}
// make sure the child window doesn't contain garbage
gdk_window_process_updates(window,TRUE);
// get window geometry
GtkAllocation allocation( Gtk::gdk_rectangle() );
gdk_window_get_geometry( window, &allocation.x, &allocation.y, &allocation.width, &allocation.height, 0L );
// create context with clipping
Cairo::Context context(gtk_widget_get_window(widget), &allocation );
// add event region
gdk_cairo_region(context,event->region);
cairo_clip(context);
// draw child
gdk_cairo_set_source_window( context, window, allocation.x, allocation.y );
cairo_paint(context);
#if OXYGEN_DEBUG_INNERSHADOWS
// Show updated parts in random color
cairo_rectangle(context,allocation.x,allocation.y,allocation.width,allocation.height);
double red=((double)rand())/RAND_MAX;
double green=((double)rand())/RAND_MAX;
double blue=((double)rand())/RAND_MAX;
cairo_set_source_rgba(context,red,green,blue,0.5);
cairo_fill(context);
#endif
// draw the shadow
/*
TODO: here child widget's allocation is used instead of window geometry.
I think this is the correct thing to do (unlike above), but this is to be double check
*/
allocation = Gtk::gtk_widget_get_allocation( child );
int basicOffset=2;
// we only draw SHADOW_IN here
if(gtk_scrolled_window_get_shadow_type(GTK_SCROLLED_WINDOW(widget)) != GTK_SHADOW_IN )
{
if( GTK_IS_VIEWPORT(child) && gtk_viewport_get_shadow_type(GTK_VIEWPORT(child)) == GTK_SHADOW_IN )
{
basicOffset=0;
} else {
// FIXME: do we need this special case?
// special_case {
// we still want to draw shadow on GtkFrames with shadow containing GtkScrolledWindow without shadow
GtkWidget* box=gtk_widget_get_parent(widget);
GtkWidget* frame=0;
if(GTK_IS_BOX(box) && GTK_IS_FRAME(frame=gtk_widget_get_parent(box)) &&
gtk_frame_get_shadow_type(GTK_FRAME(frame))==GTK_SHADOW_IN)
{
#if OXYGEN_DEBUG
std::cerr << "Oxygen::InnerShadowData::targetExposeEvent: Box children: " << GTK_CONTAINER(box) << std::endl;
#endif
// make sure GtkScrolledWindow is the only visible child
GList* children=gtk_container_get_children(GTK_CONTAINER(box));
for(GList* child=g_list_first(children); child; child=g_list_next(child))
{
GtkWidget* childWidget(GTK_WIDGET(child->data));
if(gtk_widget_get_visible(childWidget) && !GTK_IS_SCROLLED_WINDOW(childWidget))
{
g_list_free(children);
return FALSE;
}
}
int frameX, frameY;
GtkAllocation frameAlloc;
if(gtk_widget_translate_coordinates(frame,widget,0,0,&frameX,&frameY))
{
#if OXYGEN_DEBUG
std::cerr << "coords translation: x=" << frameX << "; y=" << frameY << std::endl;
#endif
gtk_widget_get_allocation(frame,&frameAlloc);
allocation.x+=frameX;
allocation.y+=frameY;
allocation.width=frameAlloc.width;
allocation.height=frameAlloc.height;
basicOffset=0;
}
} else {
#if OXYGEN_DEBUG
std::cerr << "Oxygen::InnerShadowData::targetExposeEvent - Shadow type isn't GTK_SHADOW_IN, so not drawing the shadow in expose-event handler\n";
#endif
return FALSE;
}
}
}
StyleOptions options(widget,gtk_widget_get_state(widget));
options|=NoFill;
options &= ~(Hover|Focus);
if( Style::instance().animations().scrolledWindowEngine().contains( widget ) )
{
if( Style::instance().animations().scrolledWindowEngine().focused( widget ) ) options |= Focus;
if( Style::instance().animations().scrolledWindowEngine().hovered( widget ) ) options |= Hover;
}
const AnimationData data( Style::instance().animations().widgetStateEngine().get( widget, options, AnimationHover|AnimationFocus, AnimationFocus ) );
int offsetX=basicOffset+Entry_SideMargin;
int offsetY=basicOffset;
// clipRect
GdkRectangle clipRect( allocation );
// hole background
Style::instance().renderHoleBackground(
gtk_widget_get_window(widget), widget, &clipRect,
allocation.x-offsetX, allocation.y-offsetY, allocation.width+offsetX*2, allocation.height+offsetY*2 );
// adjust offset and render hole
offsetX -= Entry_SideMargin;
Style::instance().renderHole(
gtk_widget_get_window(widget), &clipRect,
allocation.x-offsetX, allocation.y-offsetY, allocation.width+offsetX*2, allocation.height+offsetY*2,
options, data );
#endif // enable inner shadows hack
// let the event propagate
return FALSE;
}
}
<commit_msg>Make sure gdk_window_get_composited() and anything related doesn't get into the way on too old GTK versions<commit_after>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org>
* Copyright (c) 2010 Ruslan Kabatsayev <b7.10110111@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or(at your option ) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include <gtk/gtk.h>
#include "oxygeninnershadowdata.h"
#include "../oxygengtkutils.h"
#include "../config.h"
#include "../oxygencairocontext.h"
#include "oxygenanimations.h"
#include "../oxygenstyle.h"
#include "../oxygenmetrics.h"
#include <stdlib.h>
#include <cassert>
#include <iostream>
namespace Oxygen
{
//_____________________________________________
void InnerShadowData::connect( GtkWidget* widget )
{
assert( GTK_IS_SCROLLED_WINDOW( widget ) );
assert( !_target );
// store target
_target = widget;
if( gdk_display_supports_composite( gtk_widget_get_display( widget ) ) && G_OBJECT_TYPE_NAME(widget) != std::string("GtkPizza") )
{
_compositeEnabled = true;
_exposeId.connect( G_OBJECT(_target), "expose-event", G_CALLBACK( targetExposeEvent ), this, true );
}
// check child
GtkWidget* child( gtk_bin_get_child( GTK_BIN( widget ) ) );
if( !child ) return;
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::InnerShadowData::connect -"
<< " widget: " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< " child: " << child << " (" << G_OBJECT_TYPE_NAME( child ) << ")"
<< std::endl;
#endif
registerChild( child );
}
//_____________________________________________
void InnerShadowData::disconnect( GtkWidget* )
{
_target = 0;
for( ChildDataMap::reverse_iterator iter = _childrenData.rbegin(); iter != _childrenData.rend(); ++iter )
{ iter->second.disconnect( iter->first ); }
// disconnect signals
_exposeId.disconnect();
// clear child data
_childrenData.clear();
}
//_____________________________________________
void InnerShadowData::registerChild( GtkWidget* widget )
{
#if ENABLE_INNER_SHADOWS_HACK
// make sure widget is not already in map
if( _childrenData.find( widget ) != _childrenData.end() ) return;
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::InnerShadowData::registerChild -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
GdkWindow* window(gtk_widget_get_window(widget));
if(
// check window
window &&
gdk_window_get_window_type( window ) == GDK_WINDOW_CHILD &&
// check compositing
gdk_display_supports_composite( gtk_widget_get_display( widget ) ) &&
// check widget type (might move to blacklist method)
( G_OBJECT_TYPE_NAME(widget) != std::string("GtkPizza") ) &&
// make sure widget is scrollable
GTK_WIDGET_GET_CLASS( widget )->set_scroll_adjustments_signal )
{
ChildData data;
data._unrealizeId.connect( G_OBJECT(widget), "unrealize", G_CALLBACK( childUnrealizeNotifyEvent ), this );
data._initiallyComposited = gdk_window_get_composited(window);
gdk_window_set_composited(window,TRUE);
_childrenData.insert( std::make_pair( widget, data ) );
}
#endif
}
//________________________________________________________________________________
void InnerShadowData::unregisterChild( GtkWidget* widget )
{
#if ENABLE_INNER_SHADOWS_HACK
ChildDataMap::iterator iter( _childrenData.find( widget ) );
if( iter == _childrenData.end() ) return;
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::InnerShadowData::unregisterChild -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
iter->second.disconnect( widget );
_childrenData.erase( iter );
#endif
}
//________________________________________________________________________________
void InnerShadowData::ChildData::disconnect( GtkWidget* widget )
{
#if ENABLE_INNER_SHADOWS_HACK
// disconnect signals
_unrealizeId.disconnect();
// remove compositing flag
GdkWindow* window( gtk_widget_get_window( widget ) );
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::InnerShadowData::ChildData::disconnect -"
<< " widget: " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< " window: " << window
<< std::endl;
#endif
// restore compositing if different from initial state
if( GDK_IS_WINDOW( window ) && !gdk_window_is_destroyed(window) && gdk_window_get_composited( window ) != _initiallyComposited )
{ gdk_window_set_composited( window, _initiallyComposited ); }
#endif
}
//____________________________________________________________________________________________
gboolean InnerShadowData::childUnrealizeNotifyEvent( GtkWidget* widget, gpointer data )
{
#if OXYGEN_DEBUG
std::cerr
<< "Oxygen::InnerShadowData::childUnrealizeNotifyEvent -"
<< " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
<< std::endl;
#endif
static_cast<InnerShadowData*>(data)->unregisterChild( widget );
return FALSE;
}
//_________________________________________________________________________________________
gboolean InnerShadowData::targetExposeEvent( GtkWidget* widget, GdkEventExpose* event, gpointer )
{
#if ENABLE_INNER_SHADOWS_HACK
GtkWidget* child=gtk_bin_get_child(GTK_BIN(widget));
GdkWindow* window=gtk_widget_get_window(child);
#if OXYGEN_DEBUG
std::cerr << "Oxygen::InnerShadowData::targetExposeEvent -"
<< " widget: " << widget << " (" << G_OBJECT_TYPE_NAME(widget) << ")"
<< " child: " << child << " (" << G_OBJECT_TYPE_NAME(widget) << ")"
<< " path: " << Gtk::gtk_widget_path( child )
<< " area: " << event->area
<< std::endl;
#endif
if(!gdk_window_get_composited(window))
{
#if OXYGEN_DEBUG
std::cerr << "Oxygen::InnerShadowData::targetExposeEvent - Window isn't composite. Doing nohing\n";
#endif
return FALSE;
}
// make sure the child window doesn't contain garbage
gdk_window_process_updates(window,TRUE);
// get window geometry
GtkAllocation allocation( Gtk::gdk_rectangle() );
gdk_window_get_geometry( window, &allocation.x, &allocation.y, &allocation.width, &allocation.height, 0L );
// create context with clipping
Cairo::Context context(gtk_widget_get_window(widget), &allocation );
// add event region
gdk_cairo_region(context,event->region);
cairo_clip(context);
// draw child
gdk_cairo_set_source_window( context, window, allocation.x, allocation.y );
cairo_paint(context);
#if OXYGEN_DEBUG_INNERSHADOWS
// Show updated parts in random color
cairo_rectangle(context,allocation.x,allocation.y,allocation.width,allocation.height);
double red=((double)rand())/RAND_MAX;
double green=((double)rand())/RAND_MAX;
double blue=((double)rand())/RAND_MAX;
cairo_set_source_rgba(context,red,green,blue,0.5);
cairo_fill(context);
#endif
// draw the shadow
/*
TODO: here child widget's allocation is used instead of window geometry.
I think this is the correct thing to do (unlike above), but this is to be double check
*/
allocation = Gtk::gtk_widget_get_allocation( child );
int basicOffset=2;
// we only draw SHADOW_IN here
if(gtk_scrolled_window_get_shadow_type(GTK_SCROLLED_WINDOW(widget)) != GTK_SHADOW_IN )
{
if( GTK_IS_VIEWPORT(child) && gtk_viewport_get_shadow_type(GTK_VIEWPORT(child)) == GTK_SHADOW_IN )
{
basicOffset=0;
} else {
// FIXME: do we need this special case?
// special_case {
// we still want to draw shadow on GtkFrames with shadow containing GtkScrolledWindow without shadow
GtkWidget* box=gtk_widget_get_parent(widget);
GtkWidget* frame=0;
if(GTK_IS_BOX(box) && GTK_IS_FRAME(frame=gtk_widget_get_parent(box)) &&
gtk_frame_get_shadow_type(GTK_FRAME(frame))==GTK_SHADOW_IN)
{
#if OXYGEN_DEBUG
std::cerr << "Oxygen::InnerShadowData::targetExposeEvent: Box children: " << GTK_CONTAINER(box) << std::endl;
#endif
// make sure GtkScrolledWindow is the only visible child
GList* children=gtk_container_get_children(GTK_CONTAINER(box));
for(GList* child=g_list_first(children); child; child=g_list_next(child))
{
GtkWidget* childWidget(GTK_WIDGET(child->data));
if(gtk_widget_get_visible(childWidget) && !GTK_IS_SCROLLED_WINDOW(childWidget))
{
g_list_free(children);
return FALSE;
}
}
int frameX, frameY;
GtkAllocation frameAlloc;
if(gtk_widget_translate_coordinates(frame,widget,0,0,&frameX,&frameY))
{
#if OXYGEN_DEBUG
std::cerr << "coords translation: x=" << frameX << "; y=" << frameY << std::endl;
#endif
gtk_widget_get_allocation(frame,&frameAlloc);
allocation.x+=frameX;
allocation.y+=frameY;
allocation.width=frameAlloc.width;
allocation.height=frameAlloc.height;
basicOffset=0;
}
} else {
#if OXYGEN_DEBUG
std::cerr << "Oxygen::InnerShadowData::targetExposeEvent - Shadow type isn't GTK_SHADOW_IN, so not drawing the shadow in expose-event handler\n";
#endif
return FALSE;
}
}
}
StyleOptions options(widget,gtk_widget_get_state(widget));
options|=NoFill;
options &= ~(Hover|Focus);
if( Style::instance().animations().scrolledWindowEngine().contains( widget ) )
{
if( Style::instance().animations().scrolledWindowEngine().focused( widget ) ) options |= Focus;
if( Style::instance().animations().scrolledWindowEngine().hovered( widget ) ) options |= Hover;
}
const AnimationData data( Style::instance().animations().widgetStateEngine().get( widget, options, AnimationHover|AnimationFocus, AnimationFocus ) );
int offsetX=basicOffset+Entry_SideMargin;
int offsetY=basicOffset;
// clipRect
GdkRectangle clipRect( allocation );
// hole background
Style::instance().renderHoleBackground(
gtk_widget_get_window(widget), widget, &clipRect,
allocation.x-offsetX, allocation.y-offsetY, allocation.width+offsetX*2, allocation.height+offsetY*2 );
// adjust offset and render hole
offsetX -= Entry_SideMargin;
Style::instance().renderHole(
gtk_widget_get_window(widget), &clipRect,
allocation.x-offsetX, allocation.y-offsetY, allocation.width+offsetX*2, allocation.height+offsetY*2,
options, data );
#endif // enable inner shadows hack
// let the event propagate
return FALSE;
}
}
<|endoftext|> |
<commit_before>//===-- tsan_rtl_thread.cc ------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of ThreadSanitizer (TSan), a race detector.
//
//===----------------------------------------------------------------------===//
#include "sanitizer_common/sanitizer_placement_new.h"
#include "tsan_rtl.h"
#include "tsan_mman.h"
#include "tsan_platform.h"
#include "tsan_report.h"
#include "tsan_sync.h"
namespace __tsan {
// ThreadContext implementation.
ThreadContext::ThreadContext(int tid)
: ThreadContextBase(tid)
, thr()
, sync()
, epoch0()
, epoch1()
, dead_info() {
}
#ifndef TSAN_GO
ThreadContext::~ThreadContext() {
}
#endif
void ThreadContext::OnDead() {
sync.Reset();
}
void ThreadContext::OnJoined(void *arg) {
ThreadState *caller_thr = static_cast<ThreadState *>(arg);
caller_thr->clock.acquire(&sync);
StatInc(caller_thr, StatSyncAcquire);
}
struct OnCreatedArgs {
ThreadState *thr;
uptr pc;
};
void ThreadContext::OnCreated(void *arg) {
thr = 0;
if (tid == 0)
return;
OnCreatedArgs *args = static_cast<OnCreatedArgs *>(arg);
args->thr->fast_state.IncrementEpoch();
// Can't increment epoch w/o writing to the trace as well.
TraceAddEvent(args->thr, args->thr->fast_state, EventTypeMop, 0);
args->thr->clock.set(args->thr->tid, args->thr->fast_state.epoch());
args->thr->fast_synch_epoch = args->thr->fast_state.epoch();
args->thr->clock.release(&sync);
StatInc(args->thr, StatSyncRelease);
#ifdef TSAN_GO
creation_stack.ObtainCurrent(args->thr, args->pc);
#else
creation_stack_id = CurrentStackId(args->thr, args->pc);
#endif
if (reuse_count == 0)
StatInc(args->thr, StatThreadMaxTid);
}
void ThreadContext::OnReset(void *arg) {
OnCreatedArgs *args = static_cast<OnCreatedArgs *>(arg);
StatInc(args->thr, StatThreadReuse);
sync.Reset();
DestroyAndFree(dead_info);
}
struct OnStartedArgs {
ThreadState *thr;
uptr stk_addr;
uptr stk_size;
uptr tls_addr;
uptr tls_size;
};
void ThreadContext::OnStarted(void *arg) {
OnStartedArgs *args = static_cast<OnStartedArgs*>(arg);
thr = args->thr;
// RoundUp so that one trace part does not contain events
// from different threads.
epoch0 = RoundUp(epoch1 + 1, kTracePartSize);
epoch1 = (u64)-1;
new(thr) ThreadState(CTX(), tid, unique_id,
epoch0, args->stk_addr, args->stk_size, args->tls_addr, args->tls_size);
#ifdef TSAN_GO
// Setup dynamic shadow stack.
const int kInitStackSize = 8;
args->thr->shadow_stack = (uptr*)internal_alloc(MBlockShadowStack,
kInitStackSize * sizeof(uptr));
args->thr->shadow_stack_pos = thr->shadow_stack;
args->thr->shadow_stack_end = thr->shadow_stack + kInitStackSize;
#endif
#ifndef TSAN_GO
AllocatorThreadStart(args->thr);
#endif
thr = args->thr;
thr->fast_synch_epoch = epoch0;
thr->clock.set(tid, epoch0);
thr->clock.acquire(&sync);
thr->fast_state.SetHistorySize(flags()->history_size);
const uptr trace = (epoch0 / kTracePartSize) % TraceParts();
thr->trace.headers[trace].epoch0 = epoch0;
StatInc(thr, StatSyncAcquire);
DPrintf("#%d: ThreadStart epoch=%zu stk_addr=%zx stk_size=%zx "
"tls_addr=%zx tls_size=%zx\n",
tid, (uptr)epoch0, args->stk_addr, args->stk_size,
args->tls_addr, args->tls_size);
thr->is_alive = true;
}
void ThreadContext::OnFinished() {
if (!detached) {
thr->fast_state.IncrementEpoch();
// Can't increment epoch w/o writing to the trace as well.
TraceAddEvent(thr, thr->fast_state, EventTypeMop, 0);
thr->clock.set(thr->tid, thr->fast_state.epoch());
thr->fast_synch_epoch = thr->fast_state.epoch();
thr->clock.release(&sync);
StatInc(thr, StatSyncRelease);
}
// Save from info about the thread.
dead_info = new(internal_alloc(MBlockDeadInfo, sizeof(ThreadDeadInfo)))
ThreadDeadInfo();
for (uptr i = 0; i < TraceParts(); i++) {
dead_info->trace.headers[i].epoch0 = thr->trace.headers[i].epoch0;
dead_info->trace.headers[i].stack0.CopyFrom(
thr->trace.headers[i].stack0);
}
epoch1 = thr->fast_state.epoch();
#ifndef TSAN_GO
AllocatorThreadFinish(thr);
#endif
thr->~ThreadState();
StatAggregate(CTX()->stat, thr->stat);
thr = 0;
}
static void MaybeReportThreadLeak(ThreadContextBase *tctx_base, void *unused) {
ThreadContext *tctx = static_cast<ThreadContext*>(tctx_base);
if (tctx->detached)
return;
if (tctx->status != ThreadStatusCreated
&& tctx->status != ThreadStatusRunning
&& tctx->status != ThreadStatusFinished)
return;
ScopedReport rep(ReportTypeThreadLeak);
rep.AddThread(tctx);
OutputReport(CTX(), rep);
}
void ThreadFinalize(ThreadState *thr) {
CHECK_GT(thr->in_rtl, 0);
if (!flags()->report_thread_leaks)
return;
ThreadRegistryLock l(CTX()->thread_registry);
CTX()->thread_registry->RunCallbackForEachThreadLocked(
MaybeReportThreadLeak, 0);
}
int ThreadCount(ThreadState *thr) {
CHECK_GT(thr->in_rtl, 0);
Context *ctx = CTX();
uptr result;
ctx->thread_registry->GetNumberOfThreads(0, 0, &result);
return (int)result;
}
int ThreadCreate(ThreadState *thr, uptr pc, uptr uid, bool detached) {
CHECK_GT(thr->in_rtl, 0);
StatInc(thr, StatThreadCreate);
Context *ctx = CTX();
OnCreatedArgs args = { thr, pc };
int tid = ctx->thread_registry->CreateThread(uid, detached, thr->tid, &args);
DPrintf("#%d: ThreadCreate tid=%d uid=%zu\n", thr->tid, tid, uid);
StatSet(thr, StatThreadMaxAlive, ctx->thread_registry->GetMaxAliveThreads());
return tid;
}
void ThreadStart(ThreadState *thr, int tid, uptr os_id) {
CHECK_GT(thr->in_rtl, 0);
uptr stk_addr = 0;
uptr stk_size = 0;
uptr tls_addr = 0;
uptr tls_size = 0;
GetThreadStackAndTls(tid == 0, &stk_addr, &stk_size, &tls_addr, &tls_size);
if (tid) {
if (stk_addr && stk_size)
MemoryRangeImitateWrite(thr, /*pc=*/ 1, stk_addr, stk_size);
if (tls_addr && tls_size) {
// Check that the thr object is in tls;
const uptr thr_beg = (uptr)thr;
const uptr thr_end = (uptr)thr + sizeof(*thr);
CHECK_GE(thr_beg, tls_addr);
CHECK_LE(thr_beg, tls_addr + tls_size);
CHECK_GE(thr_end, tls_addr);
CHECK_LE(thr_end, tls_addr + tls_size);
// Since the thr object is huge, skip it.
MemoryRangeImitateWrite(thr, /*pc=*/ 2, tls_addr, thr_beg - tls_addr);
MemoryRangeImitateWrite(thr, /*pc=*/ 2,
thr_end, tls_addr + tls_size - thr_end);
}
}
OnStartedArgs args = { thr, stk_addr, stk_size, tls_addr, tls_size };
CTX()->thread_registry->StartThread(tid, os_id, &args);
}
void ThreadFinish(ThreadState *thr) {
CHECK_GT(thr->in_rtl, 0);
StatInc(thr, StatThreadFinish);
if (thr->stk_addr && thr->stk_size)
DontNeedShadowFor(thr->stk_addr, thr->stk_size);
if (thr->tls_addr && thr->tls_size)
DontNeedShadowFor(thr->tls_addr, thr->tls_size);
thr->is_alive = false;
Context *ctx = CTX();
ctx->thread_registry->FinishThread(thr->tid);
}
static bool FindThreadByUid(ThreadContextBase *tctx, void *arg) {
uptr uid = (uptr)arg;
if (tctx->user_id == uid && tctx->status != ThreadStatusInvalid) {
tctx->user_id = 0;
return true;
}
return false;
}
int ThreadTid(ThreadState *thr, uptr pc, uptr uid) {
CHECK_GT(thr->in_rtl, 0);
Context *ctx = CTX();
int res = ctx->thread_registry->FindThread(FindThreadByUid, (void*)uid);
DPrintf("#%d: ThreadTid uid=%zu tid=%d\n", thr->tid, uid, res);
return res;
}
void ThreadJoin(ThreadState *thr, uptr pc, int tid) {
CHECK_GT(thr->in_rtl, 0);
CHECK_GT(tid, 0);
CHECK_LT(tid, kMaxTid);
DPrintf("#%d: ThreadJoin tid=%d\n", thr->tid, tid);
Context *ctx = CTX();
ctx->thread_registry->JoinThread(tid, thr);
}
void ThreadDetach(ThreadState *thr, uptr pc, int tid) {
CHECK_GT(thr->in_rtl, 0);
CHECK_GT(tid, 0);
CHECK_LT(tid, kMaxTid);
Context *ctx = CTX();
ctx->thread_registry->DetachThread(tid);
}
void ThreadSetName(ThreadState *thr, const char *name) {
CHECK_GT(thr->in_rtl, 0);
CTX()->thread_registry->SetThreadName(thr->tid, name);
}
void MemoryAccessRange(ThreadState *thr, uptr pc, uptr addr,
uptr size, bool is_write) {
if (size == 0)
return;
u64 *shadow_mem = (u64*)MemToShadow(addr);
DPrintf2("#%d: MemoryAccessRange: @%p %p size=%d is_write=%d\n",
thr->tid, (void*)pc, (void*)addr,
(int)size, is_write);
#if TSAN_DEBUG
if (!IsAppMem(addr)) {
Printf("Access to non app mem %zx\n", addr);
DCHECK(IsAppMem(addr));
}
if (!IsAppMem(addr + size - 1)) {
Printf("Access to non app mem %zx\n", addr + size - 1);
DCHECK(IsAppMem(addr + size - 1));
}
if (!IsShadowMem((uptr)shadow_mem)) {
Printf("Bad shadow addr %p (%zx)\n", shadow_mem, addr);
DCHECK(IsShadowMem((uptr)shadow_mem));
}
if (!IsShadowMem((uptr)(shadow_mem + size * kShadowCnt / 8 - 1))) {
Printf("Bad shadow addr %p (%zx)\n",
shadow_mem + size * kShadowCnt / 8 - 1, addr + size - 1);
DCHECK(IsShadowMem((uptr)(shadow_mem + size * kShadowCnt / 8 - 1)));
}
#endif
StatInc(thr, StatMopRange);
FastState fast_state = thr->fast_state;
if (fast_state.GetIgnoreBit())
return;
fast_state.IncrementEpoch();
thr->fast_state = fast_state;
TraceAddEvent(thr, fast_state, EventTypeMop, pc);
bool unaligned = (addr % kShadowCell) != 0;
// Handle unaligned beginning, if any.
for (; addr % kShadowCell && size; addr++, size--) {
int const kAccessSizeLog = 0;
Shadow cur(fast_state);
cur.SetWrite(is_write);
cur.SetAddr0AndSizeLog(addr & (kShadowCell - 1), kAccessSizeLog);
MemoryAccessImpl(thr, addr, kAccessSizeLog, is_write, false,
shadow_mem, cur);
}
if (unaligned)
shadow_mem += kShadowCnt;
// Handle middle part, if any.
for (; size >= kShadowCell; addr += kShadowCell, size -= kShadowCell) {
int const kAccessSizeLog = 3;
Shadow cur(fast_state);
cur.SetWrite(is_write);
cur.SetAddr0AndSizeLog(0, kAccessSizeLog);
MemoryAccessImpl(thr, addr, kAccessSizeLog, is_write, false,
shadow_mem, cur);
shadow_mem += kShadowCnt;
}
// Handle ending, if any.
for (; size; addr++, size--) {
int const kAccessSizeLog = 0;
Shadow cur(fast_state);
cur.SetWrite(is_write);
cur.SetAddr0AndSizeLog(addr & (kShadowCell - 1), kAccessSizeLog);
MemoryAccessImpl(thr, addr, kAccessSizeLog, is_write, false,
shadow_mem, cur);
}
}
void MemoryAccessRangeStep(ThreadState *thr, uptr pc, uptr addr,
uptr size, uptr step, bool is_write) {
if (size == 0)
return;
FastState fast_state = thr->fast_state;
if (fast_state.GetIgnoreBit())
return;
StatInc(thr, StatMopRange);
fast_state.IncrementEpoch();
thr->fast_state = fast_state;
TraceAddEvent(thr, fast_state, EventTypeMop, pc);
for (uptr addr_end = addr + size; addr < addr_end; addr += step) {
u64 *shadow_mem = (u64*)MemToShadow(addr);
Shadow cur(fast_state);
cur.SetWrite(is_write);
cur.SetAddr0AndSizeLog(addr & (kShadowCell - 1), kSizeLog1);
MemoryAccessImpl(thr, addr, kSizeLog1, is_write, false,
shadow_mem, cur);
}
}
} // namespace __tsan
<commit_msg>tsan: fix memory leak<commit_after>//===-- tsan_rtl_thread.cc ------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of ThreadSanitizer (TSan), a race detector.
//
//===----------------------------------------------------------------------===//
#include "sanitizer_common/sanitizer_placement_new.h"
#include "tsan_rtl.h"
#include "tsan_mman.h"
#include "tsan_platform.h"
#include "tsan_report.h"
#include "tsan_sync.h"
namespace __tsan {
// ThreadContext implementation.
ThreadContext::ThreadContext(int tid)
: ThreadContextBase(tid)
, thr()
, sync()
, epoch0()
, epoch1()
, dead_info() {
}
#ifndef TSAN_GO
ThreadContext::~ThreadContext() {
}
#endif
void ThreadContext::OnDead() {
sync.Reset();
}
void ThreadContext::OnJoined(void *arg) {
ThreadState *caller_thr = static_cast<ThreadState *>(arg);
caller_thr->clock.acquire(&sync);
StatInc(caller_thr, StatSyncAcquire);
sync.Reset();
}
struct OnCreatedArgs {
ThreadState *thr;
uptr pc;
};
void ThreadContext::OnCreated(void *arg) {
thr = 0;
if (tid == 0)
return;
OnCreatedArgs *args = static_cast<OnCreatedArgs *>(arg);
args->thr->fast_state.IncrementEpoch();
// Can't increment epoch w/o writing to the trace as well.
TraceAddEvent(args->thr, args->thr->fast_state, EventTypeMop, 0);
args->thr->clock.set(args->thr->tid, args->thr->fast_state.epoch());
args->thr->fast_synch_epoch = args->thr->fast_state.epoch();
args->thr->clock.release(&sync);
StatInc(args->thr, StatSyncRelease);
#ifdef TSAN_GO
creation_stack.ObtainCurrent(args->thr, args->pc);
#else
creation_stack_id = CurrentStackId(args->thr, args->pc);
#endif
if (reuse_count == 0)
StatInc(args->thr, StatThreadMaxTid);
}
void ThreadContext::OnReset(void *arg) {
OnCreatedArgs *args = static_cast<OnCreatedArgs *>(arg);
StatInc(args->thr, StatThreadReuse);
sync.Reset();
DestroyAndFree(dead_info);
}
struct OnStartedArgs {
ThreadState *thr;
uptr stk_addr;
uptr stk_size;
uptr tls_addr;
uptr tls_size;
};
void ThreadContext::OnStarted(void *arg) {
OnStartedArgs *args = static_cast<OnStartedArgs*>(arg);
thr = args->thr;
// RoundUp so that one trace part does not contain events
// from different threads.
epoch0 = RoundUp(epoch1 + 1, kTracePartSize);
epoch1 = (u64)-1;
new(thr) ThreadState(CTX(), tid, unique_id,
epoch0, args->stk_addr, args->stk_size, args->tls_addr, args->tls_size);
#ifdef TSAN_GO
// Setup dynamic shadow stack.
const int kInitStackSize = 8;
args->thr->shadow_stack = (uptr*)internal_alloc(MBlockShadowStack,
kInitStackSize * sizeof(uptr));
args->thr->shadow_stack_pos = thr->shadow_stack;
args->thr->shadow_stack_end = thr->shadow_stack + kInitStackSize;
#endif
#ifndef TSAN_GO
AllocatorThreadStart(args->thr);
#endif
thr = args->thr;
thr->fast_synch_epoch = epoch0;
thr->clock.set(tid, epoch0);
thr->clock.acquire(&sync);
thr->fast_state.SetHistorySize(flags()->history_size);
const uptr trace = (epoch0 / kTracePartSize) % TraceParts();
thr->trace.headers[trace].epoch0 = epoch0;
StatInc(thr, StatSyncAcquire);
DPrintf("#%d: ThreadStart epoch=%zu stk_addr=%zx stk_size=%zx "
"tls_addr=%zx tls_size=%zx\n",
tid, (uptr)epoch0, args->stk_addr, args->stk_size,
args->tls_addr, args->tls_size);
thr->is_alive = true;
}
void ThreadContext::OnFinished() {
if (!detached) {
thr->fast_state.IncrementEpoch();
// Can't increment epoch w/o writing to the trace as well.
TraceAddEvent(thr, thr->fast_state, EventTypeMop, 0);
thr->clock.set(thr->tid, thr->fast_state.epoch());
thr->fast_synch_epoch = thr->fast_state.epoch();
thr->clock.release(&sync);
StatInc(thr, StatSyncRelease);
}
// Save from info about the thread.
dead_info = new(internal_alloc(MBlockDeadInfo, sizeof(ThreadDeadInfo)))
ThreadDeadInfo();
for (uptr i = 0; i < TraceParts(); i++) {
dead_info->trace.headers[i].epoch0 = thr->trace.headers[i].epoch0;
dead_info->trace.headers[i].stack0.CopyFrom(
thr->trace.headers[i].stack0);
}
epoch1 = thr->fast_state.epoch();
#ifndef TSAN_GO
AllocatorThreadFinish(thr);
#endif
thr->~ThreadState();
StatAggregate(CTX()->stat, thr->stat);
thr = 0;
}
static void MaybeReportThreadLeak(ThreadContextBase *tctx_base, void *unused) {
ThreadContext *tctx = static_cast<ThreadContext*>(tctx_base);
if (tctx->detached)
return;
if (tctx->status != ThreadStatusCreated
&& tctx->status != ThreadStatusRunning
&& tctx->status != ThreadStatusFinished)
return;
ScopedReport rep(ReportTypeThreadLeak);
rep.AddThread(tctx);
OutputReport(CTX(), rep);
}
void ThreadFinalize(ThreadState *thr) {
CHECK_GT(thr->in_rtl, 0);
if (!flags()->report_thread_leaks)
return;
ThreadRegistryLock l(CTX()->thread_registry);
CTX()->thread_registry->RunCallbackForEachThreadLocked(
MaybeReportThreadLeak, 0);
}
int ThreadCount(ThreadState *thr) {
CHECK_GT(thr->in_rtl, 0);
Context *ctx = CTX();
uptr result;
ctx->thread_registry->GetNumberOfThreads(0, 0, &result);
return (int)result;
}
int ThreadCreate(ThreadState *thr, uptr pc, uptr uid, bool detached) {
CHECK_GT(thr->in_rtl, 0);
StatInc(thr, StatThreadCreate);
Context *ctx = CTX();
OnCreatedArgs args = { thr, pc };
int tid = ctx->thread_registry->CreateThread(uid, detached, thr->tid, &args);
DPrintf("#%d: ThreadCreate tid=%d uid=%zu\n", thr->tid, tid, uid);
StatSet(thr, StatThreadMaxAlive, ctx->thread_registry->GetMaxAliveThreads());
return tid;
}
void ThreadStart(ThreadState *thr, int tid, uptr os_id) {
CHECK_GT(thr->in_rtl, 0);
uptr stk_addr = 0;
uptr stk_size = 0;
uptr tls_addr = 0;
uptr tls_size = 0;
GetThreadStackAndTls(tid == 0, &stk_addr, &stk_size, &tls_addr, &tls_size);
if (tid) {
if (stk_addr && stk_size)
MemoryRangeImitateWrite(thr, /*pc=*/ 1, stk_addr, stk_size);
if (tls_addr && tls_size) {
// Check that the thr object is in tls;
const uptr thr_beg = (uptr)thr;
const uptr thr_end = (uptr)thr + sizeof(*thr);
CHECK_GE(thr_beg, tls_addr);
CHECK_LE(thr_beg, tls_addr + tls_size);
CHECK_GE(thr_end, tls_addr);
CHECK_LE(thr_end, tls_addr + tls_size);
// Since the thr object is huge, skip it.
MemoryRangeImitateWrite(thr, /*pc=*/ 2, tls_addr, thr_beg - tls_addr);
MemoryRangeImitateWrite(thr, /*pc=*/ 2,
thr_end, tls_addr + tls_size - thr_end);
}
}
OnStartedArgs args = { thr, stk_addr, stk_size, tls_addr, tls_size };
CTX()->thread_registry->StartThread(tid, os_id, &args);
}
void ThreadFinish(ThreadState *thr) {
CHECK_GT(thr->in_rtl, 0);
StatInc(thr, StatThreadFinish);
if (thr->stk_addr && thr->stk_size)
DontNeedShadowFor(thr->stk_addr, thr->stk_size);
if (thr->tls_addr && thr->tls_size)
DontNeedShadowFor(thr->tls_addr, thr->tls_size);
thr->is_alive = false;
Context *ctx = CTX();
ctx->thread_registry->FinishThread(thr->tid);
}
static bool FindThreadByUid(ThreadContextBase *tctx, void *arg) {
uptr uid = (uptr)arg;
if (tctx->user_id == uid && tctx->status != ThreadStatusInvalid) {
tctx->user_id = 0;
return true;
}
return false;
}
int ThreadTid(ThreadState *thr, uptr pc, uptr uid) {
CHECK_GT(thr->in_rtl, 0);
Context *ctx = CTX();
int res = ctx->thread_registry->FindThread(FindThreadByUid, (void*)uid);
DPrintf("#%d: ThreadTid uid=%zu tid=%d\n", thr->tid, uid, res);
return res;
}
void ThreadJoin(ThreadState *thr, uptr pc, int tid) {
CHECK_GT(thr->in_rtl, 0);
CHECK_GT(tid, 0);
CHECK_LT(tid, kMaxTid);
DPrintf("#%d: ThreadJoin tid=%d\n", thr->tid, tid);
Context *ctx = CTX();
ctx->thread_registry->JoinThread(tid, thr);
}
void ThreadDetach(ThreadState *thr, uptr pc, int tid) {
CHECK_GT(thr->in_rtl, 0);
CHECK_GT(tid, 0);
CHECK_LT(tid, kMaxTid);
Context *ctx = CTX();
ctx->thread_registry->DetachThread(tid);
}
void ThreadSetName(ThreadState *thr, const char *name) {
CHECK_GT(thr->in_rtl, 0);
CTX()->thread_registry->SetThreadName(thr->tid, name);
}
void MemoryAccessRange(ThreadState *thr, uptr pc, uptr addr,
uptr size, bool is_write) {
if (size == 0)
return;
u64 *shadow_mem = (u64*)MemToShadow(addr);
DPrintf2("#%d: MemoryAccessRange: @%p %p size=%d is_write=%d\n",
thr->tid, (void*)pc, (void*)addr,
(int)size, is_write);
#if TSAN_DEBUG
if (!IsAppMem(addr)) {
Printf("Access to non app mem %zx\n", addr);
DCHECK(IsAppMem(addr));
}
if (!IsAppMem(addr + size - 1)) {
Printf("Access to non app mem %zx\n", addr + size - 1);
DCHECK(IsAppMem(addr + size - 1));
}
if (!IsShadowMem((uptr)shadow_mem)) {
Printf("Bad shadow addr %p (%zx)\n", shadow_mem, addr);
DCHECK(IsShadowMem((uptr)shadow_mem));
}
if (!IsShadowMem((uptr)(shadow_mem + size * kShadowCnt / 8 - 1))) {
Printf("Bad shadow addr %p (%zx)\n",
shadow_mem + size * kShadowCnt / 8 - 1, addr + size - 1);
DCHECK(IsShadowMem((uptr)(shadow_mem + size * kShadowCnt / 8 - 1)));
}
#endif
StatInc(thr, StatMopRange);
FastState fast_state = thr->fast_state;
if (fast_state.GetIgnoreBit())
return;
fast_state.IncrementEpoch();
thr->fast_state = fast_state;
TraceAddEvent(thr, fast_state, EventTypeMop, pc);
bool unaligned = (addr % kShadowCell) != 0;
// Handle unaligned beginning, if any.
for (; addr % kShadowCell && size; addr++, size--) {
int const kAccessSizeLog = 0;
Shadow cur(fast_state);
cur.SetWrite(is_write);
cur.SetAddr0AndSizeLog(addr & (kShadowCell - 1), kAccessSizeLog);
MemoryAccessImpl(thr, addr, kAccessSizeLog, is_write, false,
shadow_mem, cur);
}
if (unaligned)
shadow_mem += kShadowCnt;
// Handle middle part, if any.
for (; size >= kShadowCell; addr += kShadowCell, size -= kShadowCell) {
int const kAccessSizeLog = 3;
Shadow cur(fast_state);
cur.SetWrite(is_write);
cur.SetAddr0AndSizeLog(0, kAccessSizeLog);
MemoryAccessImpl(thr, addr, kAccessSizeLog, is_write, false,
shadow_mem, cur);
shadow_mem += kShadowCnt;
}
// Handle ending, if any.
for (; size; addr++, size--) {
int const kAccessSizeLog = 0;
Shadow cur(fast_state);
cur.SetWrite(is_write);
cur.SetAddr0AndSizeLog(addr & (kShadowCell - 1), kAccessSizeLog);
MemoryAccessImpl(thr, addr, kAccessSizeLog, is_write, false,
shadow_mem, cur);
}
}
void MemoryAccessRangeStep(ThreadState *thr, uptr pc, uptr addr,
uptr size, uptr step, bool is_write) {
if (size == 0)
return;
FastState fast_state = thr->fast_state;
if (fast_state.GetIgnoreBit())
return;
StatInc(thr, StatMopRange);
fast_state.IncrementEpoch();
thr->fast_state = fast_state;
TraceAddEvent(thr, fast_state, EventTypeMop, pc);
for (uptr addr_end = addr + size; addr < addr_end; addr += step) {
u64 *shadow_mem = (u64*)MemToShadow(addr);
Shadow cur(fast_state);
cur.SetWrite(is_write);
cur.SetAddr0AndSizeLog(addr & (kShadowCell - 1), kSizeLog1);
MemoryAccessImpl(thr, addr, kSizeLog1, is_write, false,
shadow_mem, cur);
}
}
} // namespace __tsan
<|endoftext|> |
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include <iostream>
#include <SurgSim/Graphics/OsgLog.h>
#include <SurgSim/Graphics/UnitTests/MockOsgObjects.h>
TEST(OsgLogTests, ConstructorTest)
{
EXPECT_EQ(osg::NOTICE, osg::getNotifyLevel());
auto mockOsgLog = new MockOsgLog;
EXPECT_EQ(osg::DEBUG_FP, osg::getNotifyLevel());
}
TEST(OsgLogTests, MessageTest)
{
osg::NotifyHandler* pOsgLog = new MockOsgLog;
osg::setNotifyHandler(pOsgLog);
EXPECT_EQ("", dynamic_cast<MockOsgLog*>(pOsgLog)->getMessage());
osg::notify(osg::ALWAYS) << "osg::ALWAYS Test" << std::endl;
EXPECT_EQ("CRITICAL osg::ALWAYS Test\n", dynamic_cast<MockOsgLog*>(pOsgLog)->getMessage());
osg::notify(osg::FATAL) << "osg::FATAL Test" << std::endl;
EXPECT_EQ("CRITICAL osg::FATAL Test\n", dynamic_cast<MockOsgLog*>(pOsgLog)->getMessage());
osg::notify(osg::WARN) << "osg::WARN Test" << std::endl;
EXPECT_EQ("WARNING osg::WARN Test\n", dynamic_cast<MockOsgLog*>(pOsgLog)->getMessage());
osg::notify(osg::NOTICE) << "osg::NOTICE Test" << std::endl;
EXPECT_EQ("INFO osg::NOTICE Test\n", dynamic_cast<MockOsgLog*>(pOsgLog)->getMessage());
osg::notify(osg::INFO) << "osg::INFO Test" << std::endl;
EXPECT_EQ("INFO osg::INFO Test\n", dynamic_cast<MockOsgLog*>(pOsgLog)->getMessage());
osg::notify(osg::DEBUG_INFO) << "osg::DEBUG_INFO Test" << std::endl;
EXPECT_EQ("DEBUG osg::DEBUG_INFO Test\n", dynamic_cast<MockOsgLog*>(pOsgLog)->getMessage());
osg::notify(osg::DEBUG_FP) << "osg::DEBUG_FP Test" << std::endl;
EXPECT_EQ("DEBUG osg::DEBUG_FP Test\n", dynamic_cast<MockOsgLog*>(pOsgLog)->getMessage());
osg::notify(osg::DEBUG_FP) << "osg::DEBUG_FP Test" << std::endl;
EXPECT_EQ("DEBUG osg::DEBUG_FP Test\n", dynamic_cast<MockOsgLog*>(pOsgLog)->getMessage());
}
<commit_msg>Take out ConstructorTest in OsgLogTests (Unit Tests).<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include <iostream>
#include <SurgSim/Graphics/OsgLog.h>
#include <SurgSim/Graphics/UnitTests/MockOsgObjects.h>
TEST(OsgLogTests, MessageTest)
{
osg::NotifyHandler* pOsgLog = new MockOsgLog;
osg::setNotifyHandler(pOsgLog);
EXPECT_EQ("", dynamic_cast<MockOsgLog*>(pOsgLog)->getMessage());
osg::notify(osg::ALWAYS) << "osg::ALWAYS Test" << std::endl;
EXPECT_EQ("CRITICAL osg::ALWAYS Test\n", dynamic_cast<MockOsgLog*>(pOsgLog)->getMessage());
osg::notify(osg::FATAL) << "osg::FATAL Test" << std::endl;
EXPECT_EQ("CRITICAL osg::FATAL Test\n", dynamic_cast<MockOsgLog*>(pOsgLog)->getMessage());
osg::notify(osg::WARN) << "osg::WARN Test" << std::endl;
EXPECT_EQ("WARNING osg::WARN Test\n", dynamic_cast<MockOsgLog*>(pOsgLog)->getMessage());
osg::notify(osg::NOTICE) << "osg::NOTICE Test" << std::endl;
EXPECT_EQ("INFO osg::NOTICE Test\n", dynamic_cast<MockOsgLog*>(pOsgLog)->getMessage());
osg::notify(osg::INFO) << "osg::INFO Test" << std::endl;
EXPECT_EQ("INFO osg::INFO Test\n", dynamic_cast<MockOsgLog*>(pOsgLog)->getMessage());
osg::notify(osg::DEBUG_INFO) << "osg::DEBUG_INFO Test" << std::endl;
EXPECT_EQ("DEBUG osg::DEBUG_INFO Test\n", dynamic_cast<MockOsgLog*>(pOsgLog)->getMessage());
osg::notify(osg::DEBUG_FP) << "osg::DEBUG_FP Test" << std::endl;
EXPECT_EQ("DEBUG osg::DEBUG_FP Test\n", dynamic_cast<MockOsgLog*>(pOsgLog)->getMessage());
osg::notify(osg::DEBUG_FP) << "osg::DEBUG_FP Test" << std::endl;
EXPECT_EQ("DEBUG osg::DEBUG_FP Test\n", dynamic_cast<MockOsgLog*>(pOsgLog)->getMessage());
}
<|endoftext|> |
<commit_before>// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/lib/ui/painting/engine_layer.h"
#include "flutter/flow/layers/container_layer.h"
#include "third_party/tonic/converter/dart_converter.h"
#include "third_party/tonic/dart_args.h"
#include "third_party/tonic/dart_binding_macros.h"
#include "third_party/tonic/dart_library_natives.h"
using tonic::ToDart;
namespace flutter {
EngineLayer::EngineLayer(std::shared_ptr<flutter::ContainerLayer> layer)
: layer_(layer) {}
EngineLayer::~EngineLayer() = default;
size_t EngineLayer::GetAllocationSize() {
// Provide an approximation of the total memory impact of this object to the
// Dart GC. The ContainerLayer may hold references to a tree of other layers,
// which in turn may contain Skia objects.
// TODO(https://github.com/flutter/flutter/issues/31498): calculate the cost
// of the layer more accurately.
return 200000;
};
IMPLEMENT_WRAPPERTYPEINFO(ui, EngineLayer);
#define FOR_EACH_BINDING(V) // nothing to bind
DART_BIND_ALL(EngineLayer, FOR_EACH_BINDING)
} // namespace flutter
<commit_msg>Revert "Increase the memory usage estimate for EngineLayer (#8700)" (#8738)<commit_after>// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/lib/ui/painting/engine_layer.h"
#include "flutter/flow/layers/container_layer.h"
#include "third_party/tonic/converter/dart_converter.h"
#include "third_party/tonic/dart_args.h"
#include "third_party/tonic/dart_binding_macros.h"
#include "third_party/tonic/dart_library_natives.h"
using tonic::ToDart;
namespace flutter {
EngineLayer::EngineLayer(std::shared_ptr<flutter::ContainerLayer> layer)
: layer_(layer) {}
EngineLayer::~EngineLayer() = default;
size_t EngineLayer::GetAllocationSize() {
// Provide an approximation of the total memory impact of this object to the
// Dart GC. The ContainerLayer may hold references to a tree of other layers,
// which in turn may contain Skia objects.
return 3000;
};
IMPLEMENT_WRAPPERTYPEINFO(ui, EngineLayer);
#define FOR_EACH_BINDING(V) // nothing to bind
DART_BIND_ALL(EngineLayer, FOR_EACH_BINDING)
} // namespace flutter
<|endoftext|> |
<commit_before>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include <backendsCommon/test/EndToEndTestImpl.hpp>
#include <backendsCommon/test/ArithmeticTestImpl.hpp>
#include <backendsCommon/test/ConcatTestImpl.hpp>
#include <backendsCommon/test/DequantizeEndToEndTestImpl.hpp>
#include <backendsCommon/test/SpaceToDepthEndToEndTestImpl.hpp>
#include <backendsCommon/test/SplitterEndToEndTestImpl.hpp>
#include <backendsCommon/test/TransposeConvolution2dEndToEndTestImpl.hpp>
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE(ClEndToEnd)
std::vector<armnn::BackendId> defaultBackends = {armnn::Compute::GpuAcc};
BOOST_AUTO_TEST_CASE(ConstantUsage_Cl_Float32)
{
ConstantUsageFloat32Test(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClConcatEndToEndDim0Test)
{
ConcatDim0EndToEnd<armnn::DataType::Float32>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClConcatEndToEndDim0Uint8Test)
{
ConcatDim0EndToEnd<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClConcatEndToEndDim1Test)
{
ConcatDim1EndToEnd<armnn::DataType::Float32>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClConcatEndToEndDim1Uint8Test)
{
ConcatDim1EndToEnd<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClConcatEndToEndDim3Test)
{
ConcatDim3EndToEnd<armnn::DataType::Float32>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClConcatEndToEndDim3Uint8Test)
{
ConcatDim3EndToEnd<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(DequantizeEndToEndSimpleTest)
{
DequantizeEndToEndSimple<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(DequantizeEndToEndOffsetTest)
{
DequantizeEndToEndOffset<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClGreaterSimpleEndToEndTest)
{
const std::vector<uint8_t> expectedOutput({ 0, 0, 0, 0, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0 });
ArithmeticSimpleEndToEnd<armnn::DataType::Float32, armnn::DataType::Boolean>(defaultBackends,
LayerType::Greater,
expectedOutput);
}
BOOST_AUTO_TEST_CASE(ClGreaterSimpleEndToEndUint8Test)
{
const std::vector<uint8_t> expectedOutput({ 0, 0, 0, 0, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0 });
ArithmeticSimpleEndToEnd<armnn::DataType::QuantisedAsymm8, armnn::DataType::Boolean>(defaultBackends,
LayerType::Greater,
expectedOutput);
}
BOOST_AUTO_TEST_CASE(ClGreaterBroadcastEndToEndTest)
{
const std::vector<uint8_t> expectedOutput({ 0, 1, 0, 0, 0, 1,
1, 1, 1, 1, 1, 1 });
ArithmeticBroadcastEndToEnd<armnn::DataType::Float32, armnn::DataType::Boolean>(defaultBackends,
LayerType::Greater,
expectedOutput);
}
BOOST_AUTO_TEST_CASE(ClGreaterBroadcastEndToEndUint8Test)
{
const std::vector<uint8_t> expectedOutput({ 0, 1, 0, 0, 0, 1,
1, 1, 1, 1, 1, 1 });
ArithmeticBroadcastEndToEnd<armnn::DataType::QuantisedAsymm8, armnn::DataType::Boolean>(defaultBackends,
LayerType::Greater,
expectedOutput);
}
BOOST_AUTO_TEST_CASE(ClSpaceToDepthNHWCEndToEndTest1)
{
SpaceToDepthNHWCEndToEndTest1(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSpaceToDepthNCHWEndToEndTest1)
{
SpaceToDepthNCHWEndToEndTest1(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSpaceToDepthNHWCEndToEndTest2)
{
SpaceToDepthNHWCEndToEndTest2(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSpaceToDepthNCHWEndToEndTest2)
{
SpaceToDepthNCHWEndToEndTest2(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter1dEndToEndTest)
{
Splitter1dEndToEnd<armnn::DataType::Float32>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter1dEndToEndUint8Test)
{
Splitter1dEndToEnd<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter2dDim0EndToEndTest)
{
Splitter2dDim0EndToEnd<armnn::DataType::Float32>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter2dDim1EndToEndTest)
{
Splitter2dDim1EndToEnd<armnn::DataType::Float32>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter2dDim0EndToEndUint8Test)
{
Splitter2dDim0EndToEnd<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter2dDim1EndToEndUint8Test)
{
Splitter2dDim1EndToEnd<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter3dDim0EndToEndTest)
{
Splitter3dDim0EndToEnd<armnn::DataType::Float32>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter3dDim1EndToEndTest)
{
Splitter3dDim1EndToEnd<armnn::DataType::Float32>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter3dDim2EndToEndTest)
{
Splitter3dDim2EndToEnd<armnn::DataType::Float32>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter3dDim0EndToEndUint8Test)
{
Splitter3dDim0EndToEnd<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter3dDim1EndToEndUint8Test)
{
Splitter3dDim1EndToEnd<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter3dDim2EndToEndUint8Test)
{
Splitter3dDim2EndToEnd<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter4dDim0EndToEndTest)
{
Splitter4dDim0EndToEnd<armnn::DataType::Float32>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter4dDim1EndToEndTest)
{
Splitter4dDim1EndToEnd<armnn::DataType::Float32>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter4dDim2EndToEndTest)
{
Splitter4dDim2EndToEnd<armnn::DataType::Float32>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter4dDim3EndToEndTest)
{
Splitter4dDim3EndToEnd<armnn::DataType::Float32>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter4dDim0EndToEndUint8Test)
{
Splitter4dDim0EndToEnd<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter4dDim1EndToEndUint8Test)
{
Splitter4dDim1EndToEnd<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter4dDim2EndToEndUint8Test)
{
Splitter4dDim2EndToEnd<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter4dDim3EndToEndUint8Test)
{
Splitter4dDim3EndToEnd<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
// TransposeConvolution2d
BOOST_AUTO_TEST_CASE(ClTransposeConvolution2dEndToEndFloatNchwTest)
{
TransposeConvolution2dEndToEnd<armnn::DataType::Float32, armnn::DataType::Float32>(
defaultBackends, armnn::DataLayout::NCHW);
}
BOOST_AUTO_TEST_CASE(ClTransposeConvolution2dEndToEndUint8NchwTest)
{
TransposeConvolution2dEndToEnd<armnn::DataType::QuantisedAsymm8, armnn::DataType::Signed32>(
defaultBackends, armnn::DataLayout::NCHW);
}
BOOST_AUTO_TEST_CASE(ClTransposeConvolution2dEndToEndFloatNhwcTest)
{
TransposeConvolution2dEndToEnd<armnn::DataType::Float32, armnn::DataType::Float32>(
defaultBackends, armnn::DataLayout::NHWC);
}
BOOST_AUTO_TEST_CASE(ClTransposeConvolution2dEndToEndUint8NhwcTest)
{
TransposeConvolution2dEndToEnd<armnn::DataType::QuantisedAsymm8, armnn::DataType::Signed32>(
defaultBackends, armnn::DataLayout::NHWC);
}
BOOST_AUTO_TEST_SUITE_END()<commit_msg>IVGCVSW-3480 Add End to End test for Prelu in the CL backend<commit_after>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include <backendsCommon/test/EndToEndTestImpl.hpp>
#include <backendsCommon/test/ArithmeticTestImpl.hpp>
#include <backendsCommon/test/ConcatTestImpl.hpp>
#include <backendsCommon/test/DequantizeEndToEndTestImpl.hpp>
#include <backendsCommon/test/PreluEndToEndTestImpl.hpp>
#include <backendsCommon/test/SpaceToDepthEndToEndTestImpl.hpp>
#include <backendsCommon/test/SplitterEndToEndTestImpl.hpp>
#include <backendsCommon/test/TransposeConvolution2dEndToEndTestImpl.hpp>
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE(ClEndToEnd)
std::vector<armnn::BackendId> defaultBackends = {armnn::Compute::GpuAcc};
BOOST_AUTO_TEST_CASE(ConstantUsage_Cl_Float32)
{
ConstantUsageFloat32Test(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClConcatEndToEndDim0Test)
{
ConcatDim0EndToEnd<armnn::DataType::Float32>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClConcatEndToEndDim0Uint8Test)
{
ConcatDim0EndToEnd<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClConcatEndToEndDim1Test)
{
ConcatDim1EndToEnd<armnn::DataType::Float32>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClConcatEndToEndDim1Uint8Test)
{
ConcatDim1EndToEnd<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClConcatEndToEndDim3Test)
{
ConcatDim3EndToEnd<armnn::DataType::Float32>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClConcatEndToEndDim3Uint8Test)
{
ConcatDim3EndToEnd<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(DequantizeEndToEndSimpleTest)
{
DequantizeEndToEndSimple<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(DequantizeEndToEndOffsetTest)
{
DequantizeEndToEndOffset<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClGreaterSimpleEndToEndTest)
{
const std::vector<uint8_t> expectedOutput({ 0, 0, 0, 0, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0 });
ArithmeticSimpleEndToEnd<armnn::DataType::Float32, armnn::DataType::Boolean>(defaultBackends,
LayerType::Greater,
expectedOutput);
}
BOOST_AUTO_TEST_CASE(ClGreaterSimpleEndToEndUint8Test)
{
const std::vector<uint8_t> expectedOutput({ 0, 0, 0, 0, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0 });
ArithmeticSimpleEndToEnd<armnn::DataType::QuantisedAsymm8, armnn::DataType::Boolean>(defaultBackends,
LayerType::Greater,
expectedOutput);
}
BOOST_AUTO_TEST_CASE(ClGreaterBroadcastEndToEndTest)
{
const std::vector<uint8_t> expectedOutput({ 0, 1, 0, 0, 0, 1,
1, 1, 1, 1, 1, 1 });
ArithmeticBroadcastEndToEnd<armnn::DataType::Float32, armnn::DataType::Boolean>(defaultBackends,
LayerType::Greater,
expectedOutput);
}
BOOST_AUTO_TEST_CASE(ClGreaterBroadcastEndToEndUint8Test)
{
const std::vector<uint8_t> expectedOutput({ 0, 1, 0, 0, 0, 1,
1, 1, 1, 1, 1, 1 });
ArithmeticBroadcastEndToEnd<armnn::DataType::QuantisedAsymm8, armnn::DataType::Boolean>(defaultBackends,
LayerType::Greater,
expectedOutput);
}
BOOST_AUTO_TEST_CASE(ClPreluEndToEndFloat32Test)
{
PreluEndToEndNegativeTest<armnn::DataType::Float32>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClPreluEndToEndTestUint8)
{
PreluEndToEndPositiveTest<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSpaceToDepthNHWCEndToEndTest1)
{
SpaceToDepthNHWCEndToEndTest1(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSpaceToDepthNCHWEndToEndTest1)
{
SpaceToDepthNCHWEndToEndTest1(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSpaceToDepthNHWCEndToEndTest2)
{
SpaceToDepthNHWCEndToEndTest2(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSpaceToDepthNCHWEndToEndTest2)
{
SpaceToDepthNCHWEndToEndTest2(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter1dEndToEndTest)
{
Splitter1dEndToEnd<armnn::DataType::Float32>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter1dEndToEndUint8Test)
{
Splitter1dEndToEnd<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter2dDim0EndToEndTest)
{
Splitter2dDim0EndToEnd<armnn::DataType::Float32>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter2dDim1EndToEndTest)
{
Splitter2dDim1EndToEnd<armnn::DataType::Float32>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter2dDim0EndToEndUint8Test)
{
Splitter2dDim0EndToEnd<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter2dDim1EndToEndUint8Test)
{
Splitter2dDim1EndToEnd<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter3dDim0EndToEndTest)
{
Splitter3dDim0EndToEnd<armnn::DataType::Float32>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter3dDim1EndToEndTest)
{
Splitter3dDim1EndToEnd<armnn::DataType::Float32>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter3dDim2EndToEndTest)
{
Splitter3dDim2EndToEnd<armnn::DataType::Float32>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter3dDim0EndToEndUint8Test)
{
Splitter3dDim0EndToEnd<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter3dDim1EndToEndUint8Test)
{
Splitter3dDim1EndToEnd<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter3dDim2EndToEndUint8Test)
{
Splitter3dDim2EndToEnd<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter4dDim0EndToEndTest)
{
Splitter4dDim0EndToEnd<armnn::DataType::Float32>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter4dDim1EndToEndTest)
{
Splitter4dDim1EndToEnd<armnn::DataType::Float32>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter4dDim2EndToEndTest)
{
Splitter4dDim2EndToEnd<armnn::DataType::Float32>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter4dDim3EndToEndTest)
{
Splitter4dDim3EndToEnd<armnn::DataType::Float32>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter4dDim0EndToEndUint8Test)
{
Splitter4dDim0EndToEnd<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter4dDim1EndToEndUint8Test)
{
Splitter4dDim1EndToEnd<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter4dDim2EndToEndUint8Test)
{
Splitter4dDim2EndToEnd<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
BOOST_AUTO_TEST_CASE(ClSplitter4dDim3EndToEndUint8Test)
{
Splitter4dDim3EndToEnd<armnn::DataType::QuantisedAsymm8>(defaultBackends);
}
// TransposeConvolution2d
BOOST_AUTO_TEST_CASE(ClTransposeConvolution2dEndToEndFloatNchwTest)
{
TransposeConvolution2dEndToEnd<armnn::DataType::Float32, armnn::DataType::Float32>(
defaultBackends, armnn::DataLayout::NCHW);
}
BOOST_AUTO_TEST_CASE(ClTransposeConvolution2dEndToEndUint8NchwTest)
{
TransposeConvolution2dEndToEnd<armnn::DataType::QuantisedAsymm8, armnn::DataType::Signed32>(
defaultBackends, armnn::DataLayout::NCHW);
}
BOOST_AUTO_TEST_CASE(ClTransposeConvolution2dEndToEndFloatNhwcTest)
{
TransposeConvolution2dEndToEnd<armnn::DataType::Float32, armnn::DataType::Float32>(
defaultBackends, armnn::DataLayout::NHWC);
}
BOOST_AUTO_TEST_CASE(ClTransposeConvolution2dEndToEndUint8NhwcTest)
{
TransposeConvolution2dEndToEnd<armnn::DataType::QuantisedAsymm8, armnn::DataType::Signed32>(
defaultBackends, armnn::DataLayout::NHWC);
}
BOOST_AUTO_TEST_SUITE_END()<|endoftext|> |
<commit_before>#include "camera.h"
#include "qtcamera.h"
#include "qtcamdevice.h"
#include "qtcammode.h"
#include "qtcamimagemode.h"
#include "qtcamvideomode.h"
#include "qtcamgraphicsviewfinder.h"
Camera::Camera(QDeclarativeItem *parent) :
QDeclarativeItem(parent),
m_cam(new QtCamera(this)),
m_dev(0),
m_vf(new QtCamGraphicsViewfinder(m_cam->config(), this)),
m_mode(Camera::ImageMode) {
// TODO:
}
Camera::~Camera() {
// TODO:
}
void Camera::componentComplete() {
QDeclarativeItem::componentComplete();
if (m_id.isValid()) {
QVariant oldId = m_id;
m_id = QVariant();
setDeviceId(oldId);
}
emit deviceCountChanged();
}
int Camera::deviceCount() const {
return m_cam ? m_cam->devices().size() : 0;
}
QString Camera::deviceName(int index) const {
return m_cam->devices().at(index).first;
}
QVariant Camera::deviceId(int index) const {
return m_cam->devices().at(index).second;
}
void Camera::setDeviceId(const QVariant& id) {
if (id == m_id) {
return;
}
if (!isComponentComplete()) {
m_id = id;
emit deviceIdChanged();
return;
}
if (m_dev) {
QObject::disconnect(m_dev, SIGNAL(runningStateChanged(bool)),
this, SIGNAL(runningStateChanged()));
QObject::disconnect(m_dev, SIGNAL(idleStateChanged(bool)), this, SIGNAL(idleStateChanged()));
}
if (m_dev && m_dev->stop()) {
delete m_dev;
}
else if (m_dev) {
qWarning() << "Failed to stop device";
return;
}
m_dev = m_cam->device(id, this);
m_id = id;
m_vf->setDevice(m_dev);
if (m_mode == Camera::VideoMode) {
m_dev->videoMode()->activate();
}
else {
m_dev->imageMode()->activate();
}
QObject::connect(m_dev, SIGNAL(runningStateChanged(bool)),
this, SIGNAL(runningStateChanged()));
QObject::connect(m_dev, SIGNAL(idleStateChanged(bool)), this, SIGNAL(idleStateChanged()));
emit deviceIdChanged();
emit deviceChanged();
}
QVariant Camera::deviceId() const {
return m_id;
}
void Camera::geometryChanged(const QRectF& newGeometry, const QRectF& oldGeometry) {
QDeclarativeItem::geometryChanged(newGeometry, oldGeometry);
m_vf->setGeometry(newGeometry);
}
QtCamDevice *Camera::device() const {
return m_dev;
}
void Camera::setMode(const Camera::CameraMode& mode) {
m_mode = mode;
if (!m_dev) {
return;
}
Camera::CameraMode current = m_dev->activeMode() == m_dev->videoMode() ?
Camera::VideoMode : Camera::ImageMode;
if (current == mode) {
return;
}
if (mode == Camera::VideoMode) {
m_dev->videoMode()->activate();
}
else {
m_dev->imageMode()->activate();
}
emit modeChanged();
}
Camera::CameraMode Camera::mode() {
return m_mode;
}
bool Camera::start() {
return m_dev ? m_dev->start() : false;
}
void Camera::stop() {
if (m_dev) {
m_dev->stop();
}
}
bool Camera::isIdle() {
return m_dev ? m_dev->isIdle() : true;
}
bool Camera::isRunning() {
return m_dev ? m_dev->isRunning() : false;
}
<commit_msg>Don't disconnect the signals before stopping the device because stopping might fail.<commit_after>#include "camera.h"
#include "qtcamera.h"
#include "qtcamdevice.h"
#include "qtcammode.h"
#include "qtcamimagemode.h"
#include "qtcamvideomode.h"
#include "qtcamgraphicsviewfinder.h"
Camera::Camera(QDeclarativeItem *parent) :
QDeclarativeItem(parent),
m_cam(new QtCamera(this)),
m_dev(0),
m_vf(new QtCamGraphicsViewfinder(m_cam->config(), this)),
m_mode(Camera::ImageMode) {
// TODO:
}
Camera::~Camera() {
// TODO:
}
void Camera::componentComplete() {
QDeclarativeItem::componentComplete();
if (m_id.isValid()) {
QVariant oldId = m_id;
m_id = QVariant();
setDeviceId(oldId);
}
emit deviceCountChanged();
}
int Camera::deviceCount() const {
return m_cam ? m_cam->devices().size() : 0;
}
QString Camera::deviceName(int index) const {
return m_cam->devices().at(index).first;
}
QVariant Camera::deviceId(int index) const {
return m_cam->devices().at(index).second;
}
void Camera::setDeviceId(const QVariant& id) {
if (id == m_id) {
return;
}
if (!isComponentComplete()) {
m_id = id;
emit deviceIdChanged();
return;
}
if (m_dev && m_dev->stop()) {
delete m_dev;
}
else if (m_dev) {
qWarning() << "Failed to stop device";
return;
}
m_dev = m_cam->device(id, this);
m_id = id;
m_vf->setDevice(m_dev);
if (m_mode == Camera::VideoMode) {
m_dev->videoMode()->activate();
}
else {
m_dev->imageMode()->activate();
}
QObject::connect(m_dev, SIGNAL(runningStateChanged(bool)),
this, SIGNAL(runningStateChanged()));
QObject::connect(m_dev, SIGNAL(idleStateChanged(bool)), this, SIGNAL(idleStateChanged()));
emit deviceIdChanged();
emit deviceChanged();
}
QVariant Camera::deviceId() const {
return m_id;
}
void Camera::geometryChanged(const QRectF& newGeometry, const QRectF& oldGeometry) {
QDeclarativeItem::geometryChanged(newGeometry, oldGeometry);
m_vf->setGeometry(newGeometry);
}
QtCamDevice *Camera::device() const {
return m_dev;
}
void Camera::setMode(const Camera::CameraMode& mode) {
m_mode = mode;
if (!m_dev) {
return;
}
Camera::CameraMode current = m_dev->activeMode() == m_dev->videoMode() ?
Camera::VideoMode : Camera::ImageMode;
if (current == mode) {
return;
}
if (mode == Camera::VideoMode) {
m_dev->videoMode()->activate();
}
else {
m_dev->imageMode()->activate();
}
emit modeChanged();
}
Camera::CameraMode Camera::mode() {
return m_mode;
}
bool Camera::start() {
return m_dev ? m_dev->start() : false;
}
void Camera::stop() {
if (m_dev) {
m_dev->stop();
}
}
bool Camera::isIdle() {
return m_dev ? m_dev->isIdle() : true;
}
bool Camera::isRunning() {
return m_dev ? m_dev->isRunning() : false;
}
<|endoftext|> |
<commit_before>#include <sys/mount.h>
#include <v8.h>
#include <node.h>
#include <errno.h>
#include <string.h>
#include <iostream>
//Uses an example of kkaefer's node addon tutorials for an async worker
//
//Link for the used template:
//https://github.com/kkaefer/node-cpp-modules/blob/master/05_threadpool/modulename.cpp#L88
using namespace v8;
Handle<Value> Mount(const Arguments &args);
void AsyncMount(uv_work_t* req);
void AsyncUmount(uv_work_t *req);
void AsyncAfter(uv_work_t* req);
struct Mounty {
Persistent<Function> callback;
//All values excpect target are only used by mount
std::string devFile;
std::string fsType;
std::string target; //used by umount
std::string data;
int flags;
int error;
};
// 0 1 2 3 4
//mount(devFile, target, fsType, options, data)
Handle<Value> Mount(const Arguments &args) {
HandleScope scope;
int argsLength = args.Length();
if (argsLength <= 2) {
return ThrowException(Exception::Error(String::New("mount needs at least 3 parameters")));
}
Local<Function> cb;
Handle<Array> options = Array::New(0);
Local<Value> data = String::New("");
if(!args[0]->IsString() || !args[1]->IsString() || !args[2]->IsString()){
return ThrowException(Exception::Error(String::New("Invalid arguments")));
}
//Check and set options array (ignores all non-array values)
if(argsLength >= 3) {
if (args[3]->IsArray()) {
options = Handle<Array>::Cast(args[3]);
}
}
if(argsLength == 6) {
if (args[4]->IsString()) {
data = args[4];
}
}
//Set callback, if provided as last argument
if(args[argsLength - 1]->IsFunction()){
cb = Local<Function>::Cast(args[argsLength - 1]);
}
else{
cb = FunctionTemplate::New()->GetFunction();
}
int flags = 0;
for (unsigned int i = 0; i < options->Length(); i++) {
String::Utf8Value str(options->Get(i)->ToString());
if(!strcmp(*str, "bind")) {
flags |= MS_BIND;
} else if(!strcmp(*str, "readonly")) {
flags |= MS_RDONLY;
} else if(!strcmp(*str, "remount")) {
flags |= MS_REMOUNT;
} else if(!strcmp(*str, "noexec")){
flags |= MS_NOEXEC;
} else{
//return ThrowException(Exception::Error(String::New(strcat("Invalid option: ", *str))));
return ThrowException(Exception::Error(String::New("Invalid option")));
}
}
String::Utf8Value devFile(args[0]->ToString());
String::Utf8Value target(args[1]->ToString());
String::Utf8Value fsType(args[2]->ToString());
String::Utf8Value dataStr(data->ToString());
//Prepare data for the async work
Mounty* mounty = new Mounty();
mounty->callback = Persistent<Function>::New(cb);
mounty->devFile = std::string(*devFile);
mounty->target = std::string(*target);
mounty->fsType = std::string(*fsType);
mounty->data = std::string(*dataStr);
mounty->flags = flags;
//Create the Async work and set the prepared data
uv_work_t *req = new uv_work_t();
req->data = mounty;
int status = uv_queue_work(uv_default_loop(), req, AsyncMount, (uv_after_work_cb)AsyncAfter);
assert(status == 0);
return scope.Close(Undefined());
}
void AsyncMount(uv_work_t* req){
Mounty* mounty = static_cast<Mounty*>(req->data);
int ret = mount(mounty->devFile.c_str(),
mounty->target.c_str(),
mounty->fsType.c_str(),
mounty->flags,
mounty->data.c_str());
//Save error-code
if(ret == -1){
mounty->error = errno;
}
}
//Used for both, mount and umount since they have the same callback interface
void AsyncAfter(uv_work_t* req){
HandleScope scope;
Mounty* mounty = static_cast<Mounty*>(req->data);
const unsigned argc = 1;
Local<Value> argv[argc];
//Call error-callback, if error... otherwise send result
if(mounty->error > 0){
Local<Value> err = node::ErrnoException(mounty->error);
//char *errStr = strerror(mounty->error);
//Local<String> s = String::New(errStr);
//Local<Object> err = Exception::Error(s)->ToObject();
//err->Set(String::NewSymbol("code"), String::New(strerror(mounty->error)));
//err->Set(String::NewSymbol("errno"), Integer::New((int32_t)mounty->error));
//const unsigned argc = 1;
argv[0] = err;
//TryCatch tc;
//mounty->callback->Call(Context::GetCurrent()->Global(), argc, argv);
//if(tc.HasCaught()){
//node::FatalException(tc);
//}
} else {
//const unsigned argc = 1;
argv[0] = Local<Value>::New(Null());
//TryCatch tc;
//mounty->callback->Call(Context::GetCurrent()->Global(), argc, argv);
//if(tc.HasCaught()){
//node::FatalException(tc);
//}
}
TryCatch tc;
mounty->callback->Call(Context::GetCurrent()->Global(), argc, argv);
if(tc.HasCaught()){
node::FatalException(tc);
}
mounty->callback.Dispose();
delete mounty;
delete req;
}
Handle<Value> Umount(const Arguments &args) {
HandleScope scope;
if (args.Length() < 1) {
return ThrowException(String::New("Missing argument 'target'"));
}
Local<Function> cb;
if(args.Length() == 2 && args[1]->IsFunction()) {
cb = Local<Function>::Cast(args[1]);
}
else{
cb = FunctionTemplate::New()->GetFunction();
}
String::Utf8Value target(args[0]->ToString());
//Prepare data for the async work
Mounty* mounty = new Mounty();
mounty->callback = Persistent<Function>::New(cb);
mounty->target = std::string(*target);
//Create the Async work and set the prepared data
uv_work_t *req = new uv_work_t();
req->data = mounty;
int status = uv_queue_work(uv_default_loop(), req, AsyncUmount, (uv_after_work_cb)AsyncAfter);
assert(status == 0);
return scope.Close(Undefined());
}
void AsyncUmount(uv_work_t *req){
Mounty* mounty = static_cast<Mounty*>(req->data);
int ret = umount(mounty->target.c_str());
//Save error-code
if(ret == -1){
mounty->error = errno;
}
}
void init (Handle<Object> exports, Handle<Object> module) {
exports->Set(String::NewSymbol("mount"), FunctionTemplate::New(Mount)->GetFunction());
exports->Set(String::NewSymbol("umount"), FunctionTemplate::New(Umount)->GetFunction());
}
NODE_MODULE(mount, init)
<commit_msg>Cleanup<commit_after>#include <sys/mount.h>
#include <v8.h>
#include <node.h>
#include <errno.h>
#include <string.h>
#include <iostream>
//Uses an example of kkaefer's node addon tutorials for an async worker
//
//Link for the used template:
//https://github.com/kkaefer/node-cpp-modules/blob/master/05_threadpool/modulename.cpp#L88
using namespace v8;
Handle<Value> Mount(const Arguments &args);
void AsyncMount(uv_work_t* req);
void AsyncUmount(uv_work_t *req);
void AsyncAfter(uv_work_t* req);
struct Mounty {
Persistent<Function> callback;
//All values excpect target are only used by mount
std::string devFile;
std::string fsType;
std::string target; //used by umount
std::string data;
int flags;
int error;
};
// 0 1 2 3 4
//mount(devFile, target, fsType, options, data)
Handle<Value> Mount(const Arguments &args) {
HandleScope scope;
int argsLength = args.Length();
if (argsLength <= 2) {
return ThrowException(Exception::Error(String::New("mount needs at least 3 parameters")));
}
Local<Function> cb;
Handle<Array> options = Array::New(0);
Local<Value> data = String::New("");
if(!args[0]->IsString() || !args[1]->IsString() || !args[2]->IsString()){
return ThrowException(Exception::Error(String::New("Invalid arguments")));
}
//Check and set options array (ignores all non-array values)
if(argsLength >= 3) {
if (args[3]->IsArray()) {
options = Handle<Array>::Cast(args[3]);
}
}
if(argsLength == 6) {
if (args[4]->IsString()) {
data = args[4];
}
}
//Set callback, if provided as last argument
if(args[argsLength - 1]->IsFunction()){
cb = Local<Function>::Cast(args[argsLength - 1]);
}
else{
cb = FunctionTemplate::New()->GetFunction();
}
int flags = 0;
for (unsigned int i = 0; i < options->Length(); i++) {
String::Utf8Value str(options->Get(i)->ToString());
if(!strcmp(*str, "bind")) {
flags |= MS_BIND;
} else if(!strcmp(*str, "readonly")) {
flags |= MS_RDONLY;
} else if(!strcmp(*str, "remount")) {
flags |= MS_REMOUNT;
} else if(!strcmp(*str, "noexec")){
flags |= MS_NOEXEC;
} else{
//return ThrowException(Exception::Error(String::New(strcat("Invalid option: ", *str))));
return ThrowException(Exception::Error(String::New("Invalid option")));
}
}
String::Utf8Value devFile(args[0]->ToString());
String::Utf8Value target(args[1]->ToString());
String::Utf8Value fsType(args[2]->ToString());
String::Utf8Value dataStr(data->ToString());
//Prepare data for the async work
Mounty* mounty = new Mounty();
mounty->callback = Persistent<Function>::New(cb);
mounty->devFile = std::string(*devFile);
mounty->target = std::string(*target);
mounty->fsType = std::string(*fsType);
mounty->data = std::string(*dataStr);
mounty->flags = flags;
//Create the Async work and set the prepared data
uv_work_t *req = new uv_work_t();
req->data = mounty;
int status = uv_queue_work(uv_default_loop(), req, AsyncMount, (uv_after_work_cb)AsyncAfter);
assert(status == 0);
return scope.Close(Undefined());
}
void AsyncMount(uv_work_t* req){
Mounty* mounty = static_cast<Mounty*>(req->data);
int ret = mount(mounty->devFile.c_str(),
mounty->target.c_str(),
mounty->fsType.c_str(),
mounty->flags,
mounty->data.c_str());
//Save error-code
if(ret == -1){
mounty->error = errno;
}
}
//Used for both, mount and umount since they have the same callback interface
void AsyncAfter(uv_work_t* req){
HandleScope scope;
Mounty* mounty = static_cast<Mounty*>(req->data);
const unsigned argc = 1;
Local<Value> argv[argc];
//Call error-callback, if error... otherwise send result
if(mounty->error > 0){
Local<Value> err = node::ErrnoException(mounty->error);
argv[0] = err;
} else {
argv[0] = Local<Value>::New(Null());
}
TryCatch tc;
mounty->callback->Call(Context::GetCurrent()->Global(), argc, argv);
if(tc.HasCaught()){
node::FatalException(tc);
}
mounty->callback.Dispose();
delete mounty;
delete req;
}
Handle<Value> Umount(const Arguments &args) {
HandleScope scope;
if (args.Length() < 1) {
return ThrowException(String::New("Missing argument 'target'"));
}
Local<Function> cb;
if(args.Length() == 2 && args[1]->IsFunction()) {
cb = Local<Function>::Cast(args[1]);
}
else{
cb = FunctionTemplate::New()->GetFunction();
}
String::Utf8Value target(args[0]->ToString());
//Prepare data for the async work
Mounty* mounty = new Mounty();
mounty->callback = Persistent<Function>::New(cb);
mounty->target = std::string(*target);
//Create the Async work and set the prepared data
uv_work_t *req = new uv_work_t();
req->data = mounty;
int status = uv_queue_work(uv_default_loop(), req, AsyncUmount, (uv_after_work_cb)AsyncAfter);
assert(status == 0);
return scope.Close(Undefined());
}
void AsyncUmount(uv_work_t *req){
Mounty* mounty = static_cast<Mounty*>(req->data);
int ret = umount(mounty->target.c_str());
//Save error-code
if(ret == -1){
mounty->error = errno;
}
}
void init (Handle<Object> exports, Handle<Object> module) {
exports->Set(String::NewSymbol("mount"), FunctionTemplate::New(Mount)->GetFunction());
exports->Set(String::NewSymbol("umount"), FunctionTemplate::New(Umount)->GetFunction());
}
NODE_MODULE(mount, init)
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2018, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* 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 "mbed.h"
#include "UDPSocket.h"
#include "EventFlags.h"
#include "greentea-client/test_env.h"
#include "unity/unity.h"
#include "utest.h"
#include "udp_tests.h"
using namespace utest::v1;
namespace {
static const int SIGNAL_SIGIO_RX = 0x1;
static const int SIGNAL_SIGIO_TX = 0x2;
static const int SIGIO_TIMEOUT = 5000; //[ms]
static const int RETRIES = 2;
static const double EXPECTED_LOSS_RATIO = 0.0;
static const double TOLERATED_LOSS_RATIO = 0.3;
UDPSocket *sock;
EventFlags signals;
static const int BUFF_SIZE = 1200;
char rx_buffer[BUFF_SIZE] = {0};
char tx_buffer[BUFF_SIZE] = {0};
static const int PKTS = 22;
static const int pkt_sizes[PKTS] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, \
100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, \
1100, 1200
};
static bool pkt_received[PKTS] = {false, false, false, false, false, false, false, false, false, false, \
false, false, false, false, false, false, false, false, false, false, \
false, false
};
Timer tc_exec_time;
int time_allotted;
}
static void _sigio_handler()
{
signals.set(SIGNAL_SIGIO_RX | SIGNAL_SIGIO_TX);
}
void UDPSOCKET_ECHOTEST()
{
SocketAddress udp_addr;
NetworkInterface::get_default_instance()->gethostbyname(ECHO_SERVER_ADDR, &udp_addr);
udp_addr.set_port(ECHO_SERVER_PORT);
UDPSocket sock;
TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.open(NetworkInterface::get_default_instance()));
int recvd;
int sent;
int packets_sent = 0;
int packets_recv = 0;
bool received_duplicate_packet = false;
for (unsigned int s_idx = 0; s_idx < sizeof(pkt_sizes) / sizeof(*pkt_sizes); ++s_idx) {
int pkt_s = pkt_sizes[s_idx];
fill_tx_buffer_ascii(tx_buffer, BUFF_SIZE);
int packets_sent_prev = packets_sent;
for (int retry_cnt = 0; retry_cnt <= 2; retry_cnt++) {
memset(rx_buffer, 0, BUFF_SIZE);
sent = sock.sendto(udp_addr, tx_buffer, pkt_s);
if (check_oversized_packets(sent, pkt_s)) {
TEST_IGNORE_MESSAGE("This device does not handle oversized packets");
} else if (sent == pkt_s) {
packets_sent++;
} else {
printf("[Round#%02d - Sender] error, returned %d\n", s_idx, sent);
continue;
}
do {
received_duplicate_packet = false;
recvd = sock.recvfrom(NULL, rx_buffer, pkt_s);
//Check if received duplicated packet
for (unsigned int d_idx = 0; d_idx < PKTS; ++d_idx) {
if (pkt_received[d_idx] && d_idx != s_idx && recvd == pkt_sizes[d_idx]) {
printf("[Round#%02d - Receiver] info, received duplicate packet %d\n", s_idx, d_idx);
received_duplicate_packet = true;
break;
}
}
} while (received_duplicate_packet);
if (recvd == pkt_s) {
break;
} else {
printf("[Round#%02d - Receiver] error, returned %d\n", s_idx, recvd);
}
}
if (memcmp(tx_buffer, rx_buffer, pkt_s) == 0) {
packets_recv++;
pkt_received[s_idx] = true;
}
// Make sure that at least one packet of every size was sent.
TEST_ASSERT_TRUE(packets_sent > packets_sent_prev);
}
// Packet loss up to 30% tolerated
if (packets_sent > 0) {
double loss_ratio = 1 - ((double)packets_recv / (double)packets_sent);
printf("Packets sent: %d, packets received %d, loss ratio %.2lf\r\n", packets_sent, packets_recv, loss_ratio);
TEST_ASSERT_DOUBLE_WITHIN(TOLERATED_LOSS_RATIO, EXPECTED_LOSS_RATIO, loss_ratio);
}
TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.close());
}
void UDPSOCKET_ECHOTEST_NONBLOCK()
{
tc_exec_time.start();
time_allotted = split2half_rmng_udp_test_time(); // [s]
SocketAddress udp_addr;
NetworkInterface::get_default_instance()->gethostbyname(ECHO_SERVER_ADDR, &udp_addr);
udp_addr.set_port(ECHO_SERVER_PORT);
sock = new UDPSocket();
if (sock == NULL) {
TEST_FAIL_MESSAGE("UDPSocket not created");
return;
}
TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock->open(NetworkInterface::get_default_instance()));
sock->set_blocking(false);
sock->sigio(callback(_sigio_handler));
int sent;
int packets_sent = 0;
int packets_recv = 0;
for (unsigned int s_idx = 0; s_idx < sizeof(pkt_sizes) / sizeof(*pkt_sizes); ++s_idx) {
int pkt_s = pkt_sizes[s_idx];
int packets_sent_prev = packets_sent;
for (int retry_cnt = 0; retry_cnt <= RETRIES; retry_cnt++) {
fill_tx_buffer_ascii(tx_buffer, pkt_s);
sent = sock->sendto(udp_addr, tx_buffer, pkt_s);
if (sent == pkt_s) {
packets_sent++;
} else if (sent == NSAPI_ERROR_WOULD_BLOCK) {
if (tc_exec_time.read() >= time_allotted ||
signals.wait_all(SIGNAL_SIGIO_TX, SIGIO_TIMEOUT) == osFlagsErrorTimeout) {
continue;
}
--retry_cnt;
} else {
printf("[Round#%02d - Sender] error, returned %d\n", s_idx, sent);
continue;
}
int recvd;
for (int retry_recv = 0; retry_recv <= RETRIES; retry_recv++) {
recvd = sock->recvfrom(NULL, rx_buffer, pkt_s);
if (recvd == NSAPI_ERROR_WOULD_BLOCK) {
if (tc_exec_time.read() >= time_allotted) {
break;
}
signals.wait_all(SIGNAL_SIGIO_RX, SIGIO_TIMEOUT);
--retry_recv;
continue;
} else if (recvd < 0) {
printf("sock.recvfrom returned %d\n", recvd);
TEST_FAIL();
break;
} else if (recvd == pkt_s) {
break;
}
}
if (recvd == pkt_s) {
break;
}
}
// Make sure that at least one packet of every size was sent.
TEST_ASSERT_TRUE(packets_sent > packets_sent_prev);
if (memcmp(tx_buffer, rx_buffer, pkt_s) == 0) {
packets_recv++;
}
}
// Packet loss up to 30% tolerated
if (packets_sent > 0) {
double loss_ratio = 1 - ((double)packets_recv / (double)packets_sent);
printf("Packets sent: %d, packets received %d, loss ratio %.2lf\r\n", packets_sent, packets_recv, loss_ratio);
TEST_ASSERT_DOUBLE_WITHIN(TOLERATED_LOSS_RATIO, EXPECTED_LOSS_RATIO, loss_ratio);
#if MBED_CONF_NSAPI_SOCKET_STATS_ENABLED
int count = fetch_stats();
int j = 0;
for (; j < count; j++) {
if ((NSAPI_UDP == udp_stats[j].proto) && (SOCK_OPEN == udp_stats[j].state)) {
TEST_ASSERT(udp_stats[j].sent_bytes != 0);
TEST_ASSERT(udp_stats[j].recv_bytes != 0);
break;
}
}
loss_ratio = 1 - ((double)udp_stats[j].recv_bytes / (double)udp_stats[j].sent_bytes);
printf("Bytes sent: %d, bytes received %d, loss ratio %.2lf\r\n", udp_stats[j].sent_bytes, udp_stats[j].recv_bytes, loss_ratio);
TEST_ASSERT_DOUBLE_WITHIN(TOLERATED_LOSS_RATIO, EXPECTED_LOSS_RATIO, loss_ratio);
#endif
}
TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock->close());
delete sock;
tc_exec_time.stop();
}
<commit_msg>Add sender address and port verification to UDPSOCKET_ECHOTEST<commit_after>/*
* Copyright (c) 2018, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* 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 "mbed.h"
#include "UDPSocket.h"
#include "EventFlags.h"
#include "greentea-client/test_env.h"
#include "unity/unity.h"
#include "utest.h"
#include "udp_tests.h"
using namespace utest::v1;
namespace {
static const int SIGNAL_SIGIO_RX = 0x1;
static const int SIGNAL_SIGIO_TX = 0x2;
static const int SIGIO_TIMEOUT = 5000; //[ms]
static const int RETRIES = 2;
static const double EXPECTED_LOSS_RATIO = 0.0;
static const double TOLERATED_LOSS_RATIO = 0.3;
UDPSocket *sock;
EventFlags signals;
static const int BUFF_SIZE = 1200;
char rx_buffer[BUFF_SIZE] = {0};
char tx_buffer[BUFF_SIZE] = {0};
static const int PKTS = 22;
static const int pkt_sizes[PKTS] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, \
100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, \
1100, 1200
};
static bool pkt_received[PKTS] = {false, false, false, false, false, false, false, false, false, false, \
false, false, false, false, false, false, false, false, false, false, \
false, false
};
Timer tc_exec_time;
int time_allotted;
}
static void _sigio_handler()
{
signals.set(SIGNAL_SIGIO_RX | SIGNAL_SIGIO_TX);
}
void UDPSOCKET_ECHOTEST()
{
SocketAddress udp_addr;
SocketAddress recv_addr;
NetworkInterface::get_default_instance()->gethostbyname(ECHO_SERVER_ADDR, &udp_addr);
udp_addr.set_port(ECHO_SERVER_PORT);
UDPSocket sock;
TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.open(NetworkInterface::get_default_instance()));
int recvd;
int sent;
int packets_sent = 0;
int packets_recv = 0;
bool received_duplicate_packet = false;
for (unsigned int s_idx = 0; s_idx < sizeof(pkt_sizes) / sizeof(*pkt_sizes); ++s_idx) {
int pkt_s = pkt_sizes[s_idx];
fill_tx_buffer_ascii(tx_buffer, BUFF_SIZE);
int packets_sent_prev = packets_sent;
for (int retry_cnt = 0; retry_cnt <= 2; retry_cnt++) {
memset(rx_buffer, 0, BUFF_SIZE);
sent = sock.sendto(udp_addr, tx_buffer, pkt_s);
if (check_oversized_packets(sent, pkt_s)) {
TEST_IGNORE_MESSAGE("This device does not handle oversized packets");
} else if (sent == pkt_s) {
packets_sent++;
} else {
printf("[Round#%02d - Sender] error, returned %d\n", s_idx, sent);
continue;
}
do {
received_duplicate_packet = false;
recvd = sock.recvfrom(&recv_addr, rx_buffer, pkt_s);
//Check if received duplicated packet
for (unsigned int d_idx = 0; d_idx < PKTS; ++d_idx) {
if (pkt_received[d_idx] && d_idx != s_idx && recvd == pkt_sizes[d_idx]) {
printf("[Round#%02d - Receiver] info, received duplicate packet %d\n", s_idx, d_idx);
received_duplicate_packet = true;
break;
}
}
} while (received_duplicate_packet);
if (recvd == pkt_s) {
break;
} else {
printf("[Round#%02d - Receiver] error, returned %d\n", s_idx, recvd);
}
}
// Verify received address is correct
TEST_ASSERT(udp_addr == recv_addr);
TEST_ASSERT_EQUAL(udp_addr.get_port(), recv_addr.get_port());
if (memcmp(tx_buffer, rx_buffer, pkt_s) == 0) {
packets_recv++;
pkt_received[s_idx] = true;
}
// Make sure that at least one packet of every size was sent.
TEST_ASSERT_TRUE(packets_sent > packets_sent_prev);
}
// Packet loss up to 30% tolerated
if (packets_sent > 0) {
double loss_ratio = 1 - ((double)packets_recv / (double)packets_sent);
printf("Packets sent: %d, packets received %d, loss ratio %.2lf\r\n", packets_sent, packets_recv, loss_ratio);
TEST_ASSERT_DOUBLE_WITHIN(TOLERATED_LOSS_RATIO, EXPECTED_LOSS_RATIO, loss_ratio);
}
TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.close());
}
void UDPSOCKET_ECHOTEST_NONBLOCK()
{
tc_exec_time.start();
time_allotted = split2half_rmng_udp_test_time(); // [s]
SocketAddress udp_addr;
NetworkInterface::get_default_instance()->gethostbyname(ECHO_SERVER_ADDR, &udp_addr);
udp_addr.set_port(ECHO_SERVER_PORT);
sock = new UDPSocket();
if (sock == NULL) {
TEST_FAIL_MESSAGE("UDPSocket not created");
return;
}
TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock->open(NetworkInterface::get_default_instance()));
sock->set_blocking(false);
sock->sigio(callback(_sigio_handler));
int sent;
int packets_sent = 0;
int packets_recv = 0;
for (unsigned int s_idx = 0; s_idx < sizeof(pkt_sizes) / sizeof(*pkt_sizes); ++s_idx) {
int pkt_s = pkt_sizes[s_idx];
int packets_sent_prev = packets_sent;
for (int retry_cnt = 0; retry_cnt <= RETRIES; retry_cnt++) {
fill_tx_buffer_ascii(tx_buffer, pkt_s);
sent = sock->sendto(udp_addr, tx_buffer, pkt_s);
if (sent == pkt_s) {
packets_sent++;
} else if (sent == NSAPI_ERROR_WOULD_BLOCK) {
if (tc_exec_time.read() >= time_allotted ||
signals.wait_all(SIGNAL_SIGIO_TX, SIGIO_TIMEOUT) == osFlagsErrorTimeout) {
continue;
}
--retry_cnt;
} else {
printf("[Round#%02d - Sender] error, returned %d\n", s_idx, sent);
continue;
}
int recvd;
for (int retry_recv = 0; retry_recv <= RETRIES; retry_recv++) {
recvd = sock->recvfrom(NULL, rx_buffer, pkt_s);
if (recvd == NSAPI_ERROR_WOULD_BLOCK) {
if (tc_exec_time.read() >= time_allotted) {
break;
}
signals.wait_all(SIGNAL_SIGIO_RX, SIGIO_TIMEOUT);
--retry_recv;
continue;
} else if (recvd < 0) {
printf("sock.recvfrom returned %d\n", recvd);
TEST_FAIL();
break;
} else if (recvd == pkt_s) {
break;
}
}
if (recvd == pkt_s) {
break;
}
}
// Make sure that at least one packet of every size was sent.
TEST_ASSERT_TRUE(packets_sent > packets_sent_prev);
if (memcmp(tx_buffer, rx_buffer, pkt_s) == 0) {
packets_recv++;
}
}
// Packet loss up to 30% tolerated
if (packets_sent > 0) {
double loss_ratio = 1 - ((double)packets_recv / (double)packets_sent);
printf("Packets sent: %d, packets received %d, loss ratio %.2lf\r\n", packets_sent, packets_recv, loss_ratio);
TEST_ASSERT_DOUBLE_WITHIN(TOLERATED_LOSS_RATIO, EXPECTED_LOSS_RATIO, loss_ratio);
#if MBED_CONF_NSAPI_SOCKET_STATS_ENABLED
int count = fetch_stats();
int j = 0;
for (; j < count; j++) {
if ((NSAPI_UDP == udp_stats[j].proto) && (SOCK_OPEN == udp_stats[j].state)) {
TEST_ASSERT(udp_stats[j].sent_bytes != 0);
TEST_ASSERT(udp_stats[j].recv_bytes != 0);
break;
}
}
loss_ratio = 1 - ((double)udp_stats[j].recv_bytes / (double)udp_stats[j].sent_bytes);
printf("Bytes sent: %d, bytes received %d, loss ratio %.2lf\r\n", udp_stats[j].sent_bytes, udp_stats[j].recv_bytes, loss_ratio);
TEST_ASSERT_DOUBLE_WITHIN(TOLERATED_LOSS_RATIO, EXPECTED_LOSS_RATIO, loss_ratio);
#endif
}
TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock->close());
delete sock;
tc_exec_time.stop();
}
<|endoftext|> |
<commit_before>/* ************************************************
* GEANT4 VCGLIB/CAD INTERFACE
*
* File: CADMesh.hh
*
* Author: Christopher M Poole,
* Email: mail@christopherpoole.net
*
* Date: 7th March, 2011
**************************************************/
#ifndef CADMesh_HH
#define CADMesh_HH
// GEANT4 //
#include "G4String.hh"
#include "G4ThreeVector.hh"
#include "G4TessellatedSolid.hh"
#include "G4AssemblyVolume.hh"
#ifndef NOVCGLIB
// VCGLIB //
#include "vcg/simplex/vertex/base.h"
#include "vcg/simplex/vertex/component.h"
#include "vcg/simplex/face/base.h"
#include "vcg/simplex/face/component.h"
#include "vcg/complex/complex.h"
#endif
// TETGEN //
#ifndef NOTET
#include "tetgen.h"
#endif
#ifndef NOVCGLIB
class CADVertex;
class CADFace;
class CADUsedTypes: public vcg::UsedTypes< vcg::Use<CADVertex>::AsVertexType, vcg::Use<CADFace>::AsFaceType>{};
class CADVertex : public vcg::Vertex<CADUsedTypes, vcg::vertex::Coord3d, vcg::vertex::Normal3f> {};
class CADFace : public vcg::Face<CADUsedTypes, vcg::face::VertexRef> {};
class CADTriMesh : public vcg::tri::TriMesh< std::vector<CADVertex>, std::vector<CADFace> > {};
#endif
class CADMesh
{
// METHODS //
public:
CADMesh(char * file, char * type, double units, G4ThreeVector offset, G4bool reverse);
CADMesh(char * file, char * type, G4Material * material, double quality);
CADMesh(char * file, char * type, G4Material * material, double quality, G4ThreeVector offset);
CADMesh(char * file, char * type);
CADMesh(char * file, char * type, G4Material * material);
~CADMesh();
#ifndef NOTET
public:
G4AssemblyVolume * TetrahedralMesh();
G4AssemblyVolume * GetAssembly() { return assembly; };
int get_input_point_count() { return in.numberofpoints; };
int get_output_point_count() { return out.numberofpoints; };
int get_tetrahedron_count() { return out.numberoftetrahedra; };
#endif
#ifndef NOVCGLIB
public:
G4VSolid* TessellatedMesh();
G4TessellatedSolid * GetSolid() { return volume_solid; };
G4String MeshName(){ return file_name_; };
int MeshVertexNumber(){ return m.VertexNumber(); };
float MeshVolume(){ return m.Volume(); };
void SetVerbose(int v){ verbose_ = v; };
#endif
private:
G4ThreeVector GetTetPoint(G4int index_offset);
// VARS //
private:
#ifndef NOVCGLIB
CADTriMesh m;
#endif
#ifndef NOTET
tetgenio in, out;
G4AssemblyVolume * assembly;
#endif
G4TessellatedSolid * volume_solid;
G4int verbose_;
G4bool has_mesh_;
G4bool has_solid_;
G4String name_;
G4double units_;
G4ThreeVector offset_;
G4bool reverse_;
G4double quality_;
G4Material * material_;
char * file_name_;
G4String file_type_;
};
#endif // CADMesh_HH
<commit_msg>Removed volume calc function referencing vcglib equivalent<commit_after>/* ************************************************
* GEANT4 VCGLIB/CAD INTERFACE
*
* File: CADMesh.hh
*
* Author: Christopher M Poole,
* Email: mail@christopherpoole.net
*
* Date: 7th March, 2011
**************************************************/
#ifndef CADMesh_HH
#define CADMesh_HH
// GEANT4 //
#include "G4String.hh"
#include "G4ThreeVector.hh"
#include "G4TessellatedSolid.hh"
#include "G4AssemblyVolume.hh"
#ifndef NOVCGLIB
// VCGLIB //
#include "vcg/simplex/vertex/base.h"
#include "vcg/simplex/vertex/component.h"
#include "vcg/simplex/face/base.h"
#include "vcg/simplex/face/component.h"
#include "vcg/complex/complex.h"
#endif
// TETGEN //
#ifndef NOTET
#include "tetgen.h"
#endif
#ifndef NOVCGLIB
class CADVertex;
class CADFace;
class CADUsedTypes: public vcg::UsedTypes< vcg::Use<CADVertex>::AsVertexType, vcg::Use<CADFace>::AsFaceType>{};
class CADVertex : public vcg::Vertex<CADUsedTypes, vcg::vertex::Coord3d, vcg::vertex::Normal3f> {};
class CADFace : public vcg::Face<CADUsedTypes, vcg::face::VertexRef> {};
class CADTriMesh : public vcg::tri::TriMesh< std::vector<CADVertex>, std::vector<CADFace> > {};
#endif
class CADMesh
{
// METHODS //
public:
CADMesh(char * file, char * type, double units, G4ThreeVector offset, G4bool reverse);
CADMesh(char * file, char * type, G4Material * material, double quality);
CADMesh(char * file, char * type, G4Material * material, double quality, G4ThreeVector offset);
CADMesh(char * file, char * type);
CADMesh(char * file, char * type, G4Material * material);
~CADMesh();
#ifndef NOTET
public:
G4AssemblyVolume * TetrahedralMesh();
G4AssemblyVolume * GetAssembly() { return assembly; };
int get_input_point_count() { return in.numberofpoints; };
int get_output_point_count() { return out.numberofpoints; };
int get_tetrahedron_count() { return out.numberoftetrahedra; };
#endif
#ifndef NOVCGLIB
public:
G4VSolid* TessellatedMesh();
G4TessellatedSolid * GetSolid() { return volume_solid; };
G4String MeshName(){ return file_name_; };
int MeshVertexNumber(){ return m.VertexNumber(); };
//float MeshVolume(){ return m.Volume(); };
void SetVerbose(int v){ verbose_ = v; };
#endif
private:
G4ThreeVector GetTetPoint(G4int index_offset);
// VARS //
private:
#ifndef NOVCGLIB
CADTriMesh m;
#endif
#ifndef NOTET
tetgenio in, out;
G4AssemblyVolume * assembly;
#endif
G4TessellatedSolid * volume_solid;
G4int verbose_;
G4bool has_mesh_;
G4bool has_solid_;
G4String name_;
G4double units_;
G4ThreeVector offset_;
G4bool reverse_;
G4double quality_;
G4Material * material_;
char * file_name_;
G4String file_type_;
};
#endif // CADMesh_HH
<|endoftext|> |
<commit_before>#ifndef WHAM_RANDOM_H_
#define WHAM_RANDOM_H_
#include<iostream>
#include<iomanip>
#include<limits>
#include<cmath>
#include<vector>
#include<time.h>
#ifdef USE_MPI
#include<mpi.h>
#endif
// A basic 32-bit LinearCongruential random number generator
class LinearCongruential32
{
public:
typedef unsigned long INT32; // long is at least 32 bits
typedef unsigned long long INT64; // long long is at least 64 bits
static bool test_bits() { int bits32 = 8*sizeof(INT32); int bits64=8*sizeof(INT64); return (bits32==32) && (bits64>=(2*bits32)); }
public:
LinearCongruential32(INT32 s=123456789) : a(1664525), c(1013904223) { seed(s); }
void set_state(INT32 multiplier, INT32 increment) { a=multiplier; c=increment; }
void seed(INT32 s) { x=s; }
float operator()() { x = (a*x+c); return static_cast<float>(x)/static_cast<float>(std::numeric_limits<INT32>::max()); }
float details()
{
//This gives output of intermediate results, specifically to look x_i as two 32-bit numbers (hi and lo)
//The normal implementation just ignores the "carry" into hi
//INT64 xi = a*x+c;
//INT32 hi = hi = (xi>>32);
//INT32 lo = static_cast<INT32>(lo);
//float f = static_cast<float>(x)/static_cast<float>(0xFFFFFFFFUL);
std::cout << "LC32: max=" << std::hex << std::numeric_limits<INT32>::max() << std::endl;
std::cout << " x_i= " << std::dec << x << std::endl;
INT64 xi = a*x+c;
std::cout << "x_i++= " << std::hex << xi << "\t" << std::dec << xi << std::endl;
INT32 hi = (xi>>32); // static_cast<INT32>(xi/0x100000000ULL);
INT32 lo = static_cast<INT32>(xi);
std::cout << " = " << std::hex << hi << " " << lo << std::dec << std::endl;
x = lo;
std::cout << "x_i++= " << std::hex << x << std::dec << std::endl;
float f = static_cast<float>(x)/static_cast<float>(0xFFFFFFFFUL);
std::cout << " f= " << f << std::endl;
return f;
}
private:
INT32 x;
INT64 a; // If a mod 8 is 1 or 5 and c is odd, the resulting base 232 congruential sequence will have period 232.
INT32 c;
};
// A lag-r multiply-with-carry random number generator, following en.wikipedia.org/wiki/Multiply-with-carry
// Includes as set of r+1 seed values x_0, x_1, x_2, ... x_r-1, and carry c_n-1.
// The sequence is x_n = (a*x_n-r + c_n-1) mod b
// c_n = floor[ ( a*x_n-r + c_n-1 ) / b ]
template<short r>
class MultiplyWithCarry
{
public:
typedef unsigned long INT32; // long is at least 32 bits
typedef unsigned long long INT64; // long long is at least 64 bits
MultiplyWithCarry(INT32 s=1234566789) : a(18782) { this->seed(s); }
void seed(INT32 s)
{
// initial carry
x[0] = 362436 % a;
// LinearCongruential32
INT32 xi = s;
for(i=1; i<=r; i++) x[i] = (xi = 1664525*xi + 101390422);
i=1;
}
void set_state(INT32 multiplier) { a=multiplier; x[0] = x[0] % a; }
float operator()()
{
INT64 y = a*x[i] + x[0];
x[0] = (y>>32); // The carry
# if 0
x[i] = static_cast<INT32>(y);
# else
x[i] = ~static_cast<INT32>(y); // The compliment makes it easier to calculate period
# endif
float f = static_cast<float>(x[i])/static_cast<float>(std::numeric_limits<INT32>::max());
(i=(i%r))++; // 1 <= i <= r
return f;
}
void print(std::ostream& out)
{
out << "MultiplyWithCarry<" << r << ">: a=" << a << " x=";
for(int j=0; j<=r; j++) out << " " << x[j];
out << std::endl;
}
private:
short i; // index that treats x as a circular buffer
INT64 a; // the multiplier, needs to be 64-bit to force 64-bit precisionin y=a*x[i]+x[0]
INT32 x[r+1]; // the seeds and the carry
};
void print_sizeof()
{
std::cout << "sizeof(float) =" << sizeof(float) << std::endl;
std::cout << "sizeof(double) =" << sizeof(double) << std::endl;
std::cout << "sizeof(char) =" << sizeof(char) << std::endl;
std::cout << "sizeof(short) =" << sizeof(short) << std::endl;
std::cout << "sizeof(int) =" << sizeof(int) << std::endl;
std::cout << "sizeof(long) =" << sizeof(long) << std::endl;
std::cout << "sizeof(long long)=" << sizeof(long long) << std::endl;
std::cout << "sizeof(u ) =" << sizeof(unsigned int) << std::endl;
std::cout << "sizeof(ul ) =" << sizeof(unsigned long) << std::endl;
std::cout << "sizeof(ull) =" << sizeof(unsigned long long) << std::endl;
}
// Runs simple moment tests of random number generators
template<class RNG>
bool RNGTestMoments(RNG& random, bool verbose, std::ostream& os) {
bool failed = false;
{
const int nsamples = 1000000;
const int max_moment = 5;
//
// collect information about population
//
double momu[max_moment+1];
for(int i=0; i<= max_moment; i++) { momu[i]=0.; }
for(int i=0; i<nsamples; i++) {
float urand = random();
if((urand<0.)||(urand>=1.)) {
failed = true;
os << "RNGTestMoments failed, urand=" << urand << " outside [0,1)\n" << std::flush;
}
for(int j=0; j<= max_moment; j++) {
momu[j]+=std::pow(urand,j);
}
}
//
// analyze the population
//
if(momu[0]<=2) {failed = true; return failed; }
for(int j=0; j<=max_moment; j++) {
double estimate = momu[j]/momu[0];
double theory = 1./static_cast<double>(j+1);
double percentE = (theory>0)? std::abs(estimate-theory)/theory * 100. : 0.;
if(verbose) {
os << " "
<< "moment " << j
<< "\t estimate = " << estimate
<< "\t theory=" << theory
<< "\t %error=" << percentE
<< std::endl << std::flush;
}
if(percentE>10.) {
failed = true;
os << " ***RNGTestMoments failed for moment " << j << std::endl << std::flush;
}
}
}
return failed;
}
// Generate random seed value from system clock.
// This gets the time using an time_t = time(&time_t) and then does some
// scrambling and puts the fastest varying bits first.
long int SeedFromClock() {
// Get time information
time_t rseed;
rseed=time(&rseed);
unsigned long int iraw=rseed;
long int iseed = iraw;
// Scramble that information
long int high = iseed % 1000;
long int low = ( iseed / 1000 ) % 1000000;
low = ( ( low + high ) * 611953 ) % 1000000;
iseed = high * 1000000 + low;
//
if(iseed<0) iseed *= -1;
return iseed;
}
#ifdef USE_C11
#include<random>
#endif
// Give a unique, predictable seed to each processor
long ParallelSeed(long baseSeed)
{
long seed_val = baseSeed;
# ifdef USE_MPI
// Get process id and global seed value
int iproc = 0;
MPI_Comm_rank(MPI_COMM_WORLD,&iproc);
MPI_Bcast(&seed_val,1,MPI_LONG,0,MPI_COMM_WORLD);
// set seed, get iproc-th result as my seed
const int stride = 10;
# ifdef USE_C11
std::mt19937 mrand(seed_val);
std::uniform_int_distribution<long> uint_dist;
for(int icall=0; icall<stride*iproc; icall++)
seed_val = uint_dist(mrand);
# else
LinearCongruential32 urng(seed_val);
for(int icall=0; icall<stride*iproc; icall++)
seed_val = urng()*std::numeric_limits<long>::max();
# endif
# endif
return seed_val;
}
bool RNGTestParallelSeed(bool verbose=false)
{
bool failed = false;
long iseed = 20140806; // A random date
iseed = ParallelSeed(iseed);
int iproc = 0;
int nproc = 1;
std::vector<long> seeds;
# ifdef USE_MPI
MPI_Comm_rank(MPI_COMM_WORLD,&iproc);
MPI_Comm_size(MPI_COMM_WORLD,&nproc);
if(iproc==0) seeds.resize(nproc);
MPI_Gather(&iseed,1,MPI_LONG,&(seeds[0]),1,MPI_LONG,0,MPI_COMM_WORLD);
# else
seeds.resize(1);
seeds[0] = iseed;
# endif
if( verbose && iproc==0 )
{
std::cout << "RNGTestParallelSeed: iproc, seed" << std::endl;
for(int i=0; i<seeds.size(); i++)
std::cout << i << " " << seeds[i] << std::endl;
}
return failed;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Examples of constructing objects and calling tests
////////////////////////////////////////////////////////////////////////////////////////////////////
#if 0
int main(int argc, char* argv[])
{
print_sizeof();
std::cout << std::endl << std::endl;
std::cout << "LinearCongruential32:" << std::endl;
LinearCongruential32 urng_lc32;
std::cout << "32bits = " << urng_lc32.test_bits() << std::endl;
for(int i=0; i<10; i++) std::cout << urng_lc32.details() << std::endl;
for(int i=0; i<10; i++) std::cout << urng_lc32() << std::endl;
RNGTestMoments(urng_lc32,true,std::cout);
std::cout << std::endl << std::endl;
std::cout << "MultiplyWithCarry-1:" << std::endl;
MultiplyWithCarry<1> urng_mwc1;
for(int i=0; i<10; i++) std::cout << urng_mwc1() << std::endl;
RNGTestMoments(urng_mwc1,true,std::cout);
std::cout << std::endl << std::endl;
std::cout << "MultiplyWithCarry-4:" << std::endl;
MultiplyWithCarry<4> urng_mwc4;
for(int i=0; i<10; i++) std::cout << urng_mwc4() << std::endl;
RNGTestMoments(urng_mwc1,true,std::cout);
}
#endif // Omit main
#endif
<commit_msg>Added some MPI safety<commit_after>#ifndef WHAM_RANDOM_H_
#define WHAM_RANDOM_H_
#include<iostream>
#include<iomanip>
#include<limits>
#include<cmath>
#include<vector>
#include<time.h>
#ifdef USE_MPI
#include<mpi.h>
#endif
// A basic 32-bit LinearCongruential random number generator
class LinearCongruential32
{
public:
typedef unsigned long INT32; // long is at least 32 bits
typedef unsigned long long INT64; // long long is at least 64 bits
static bool test_bits() { int bits32 = 8*sizeof(INT32); int bits64=8*sizeof(INT64); return (bits32==32) && (bits64>=(2*bits32)); }
public:
LinearCongruential32(INT32 s=123456789) : a(1664525), c(1013904223) { seed(s); }
void set_state(INT32 multiplier, INT32 increment) { a=multiplier; c=increment; }
void seed(INT32 s) { x=s; }
float operator()() { x = (a*x+c); return static_cast<float>(x)/static_cast<float>(std::numeric_limits<INT32>::max()); }
float details()
{
//This gives output of intermediate results, specifically to look x_i as two 32-bit numbers (hi and lo)
//The normal implementation just ignores the "carry" into hi
//INT64 xi = a*x+c;
//INT32 hi = hi = (xi>>32);
//INT32 lo = static_cast<INT32>(lo);
//float f = static_cast<float>(x)/static_cast<float>(0xFFFFFFFFUL);
std::cout << "LC32: max=" << std::hex << std::numeric_limits<INT32>::max() << std::endl;
std::cout << " x_i= " << std::dec << x << std::endl;
INT64 xi = a*x+c;
std::cout << "x_i++= " << std::hex << xi << "\t" << std::dec << xi << std::endl;
INT32 hi = (xi>>32); // static_cast<INT32>(xi/0x100000000ULL);
INT32 lo = static_cast<INT32>(xi);
std::cout << " = " << std::hex << hi << " " << lo << std::dec << std::endl;
x = lo;
std::cout << "x_i++= " << std::hex << x << std::dec << std::endl;
float f = static_cast<float>(x)/static_cast<float>(0xFFFFFFFFUL);
std::cout << " f= " << f << std::endl;
return f;
}
private:
INT32 x;
INT64 a; // If a mod 8 is 1 or 5 and c is odd, the resulting base 232 congruential sequence will have period 232.
INT32 c;
};
// A lag-r multiply-with-carry random number generator, following en.wikipedia.org/wiki/Multiply-with-carry
// Includes as set of r+1 seed values x_0, x_1, x_2, ... x_r-1, and carry c_n-1.
// The sequence is x_n = (a*x_n-r + c_n-1) mod b
// c_n = floor[ ( a*x_n-r + c_n-1 ) / b ]
template<short r>
class MultiplyWithCarry
{
public:
typedef unsigned long INT32; // long is at least 32 bits
typedef unsigned long long INT64; // long long is at least 64 bits
MultiplyWithCarry(INT32 s=1234566789) : a(18782) { this->seed(s); }
void seed(INT32 s)
{
// initial carry
x[0] = 362436 % a;
// LinearCongruential32
INT32 xi = s;
for(i=1; i<=r; i++) x[i] = (xi = 1664525*xi + 101390422);
i=1;
}
void set_state(INT32 multiplier) { a=multiplier; x[0] = x[0] % a; }
float operator()()
{
INT64 y = a*x[i] + x[0];
x[0] = (y>>32); // The carry
# if 0
x[i] = static_cast<INT32>(y);
# else
x[i] = ~static_cast<INT32>(y); // The compliment makes it easier to calculate period
# endif
float f = static_cast<float>(x[i])/static_cast<float>(std::numeric_limits<INT32>::max());
(i=(i%r))++; // 1 <= i <= r
return f;
}
void print(std::ostream& out)
{
out << "MultiplyWithCarry<" << r << ">: a=" << a << " x=";
for(int j=0; j<=r; j++) out << " " << x[j];
out << std::endl;
}
private:
short i; // index that treats x as a circular buffer
INT64 a; // the multiplier, needs to be 64-bit to force 64-bit precisionin y=a*x[i]+x[0]
INT32 x[r+1]; // the seeds and the carry
};
void print_sizeof()
{
std::cout << "sizeof(float) =" << sizeof(float) << std::endl;
std::cout << "sizeof(double) =" << sizeof(double) << std::endl;
std::cout << "sizeof(char) =" << sizeof(char) << std::endl;
std::cout << "sizeof(short) =" << sizeof(short) << std::endl;
std::cout << "sizeof(int) =" << sizeof(int) << std::endl;
std::cout << "sizeof(long) =" << sizeof(long) << std::endl;
std::cout << "sizeof(long long)=" << sizeof(long long) << std::endl;
std::cout << "sizeof(u ) =" << sizeof(unsigned int) << std::endl;
std::cout << "sizeof(ul ) =" << sizeof(unsigned long) << std::endl;
std::cout << "sizeof(ull) =" << sizeof(unsigned long long) << std::endl;
}
// Runs simple moment tests of random number generators
template<class RNG>
bool RNGTestMoments(RNG& random, bool verbose, std::ostream& os) {
bool failed = false;
{
const int nsamples = 1000000;
const int max_moment = 5;
//
// collect information about population
//
double momu[max_moment+1];
for(int i=0; i<= max_moment; i++) { momu[i]=0.; }
for(int i=0; i<nsamples; i++) {
float urand = random();
if((urand<0.)||(urand>=1.)) {
failed = true;
os << "RNGTestMoments failed, urand=" << urand << " outside [0,1)\n" << std::flush;
}
for(int j=0; j<= max_moment; j++) {
momu[j]+=std::pow(urand,j);
}
}
//
// analyze the population
//
if(momu[0]<=2) {failed = true; return failed; }
for(int j=0; j<=max_moment; j++) {
double estimate = momu[j]/momu[0];
double theory = 1./static_cast<double>(j+1);
double percentE = (theory>0)? std::abs(estimate-theory)/theory * 100. : 0.;
if(verbose) {
os << " "
<< "moment " << j
<< "\t estimate = " << estimate
<< "\t theory=" << theory
<< "\t %error=" << percentE
<< std::endl << std::flush;
}
if(percentE>10.) {
failed = true;
os << " ***RNGTestMoments failed for moment " << j << std::endl << std::flush;
}
}
}
return failed;
}
// Generate random seed value from system clock.
// This gets the time using an time_t = time(&time_t) and then does some
// scrambling and puts the fastest varying bits first.
long int SeedFromClock() {
// Get time information
time_t rseed;
rseed=time(&rseed);
unsigned long int iraw=rseed;
long int iseed = iraw;
// Scramble that information
long int high = iseed % 1000;
long int low = ( iseed / 1000 ) % 1000000;
low = ( ( low + high ) * 611953 ) % 1000000;
iseed = high * 1000000 + low;
//
if(iseed<0) iseed *= -1;
return iseed;
}
#ifdef USE_C11
#include<random>
#endif
// Give a unique, predictable seed to each processor
long ParallelSeed(long baseSeed)
{
long seed_val = baseSeed;
# ifdef USE_MPI
// Get process id and global seed value
int iproc = 0;
int init = false;
MPI_Initialized(&init);
if( init )
{
MPI_Comm_rank(MPI_COMM_WORLD,&iproc);
MPI_Bcast(&seed_val,1,MPI_LONG,0,MPI_COMM_WORLD);
}
// set seed, get iproc-th result as my seed
const int stride = 10;
# ifdef USE_C11
std::mt19937 mrand(seed_val);
std::uniform_int_distribution<long> uint_dist;
for(int icall=0; icall<stride*iproc; icall++)
seed_val = uint_dist(mrand);
# else
LinearCongruential32 urng(seed_val);
for(int icall=0; icall<stride*iproc; icall++)
seed_val = urng()*std::numeric_limits<long>::max();
# endif
# endif
return seed_val;
}
bool RNGTestParallelSeed(bool verbose=false)
{
bool failed = false;
long iseed = 20140806; // A random date
iseed = ParallelSeed(iseed);
int iproc = 0;
int nproc = 1;
std::vector<long> seeds;
# ifdef USE_MPI
MPI_Comm_rank(MPI_COMM_WORLD,&iproc);
MPI_Comm_size(MPI_COMM_WORLD,&nproc);
if(iproc==0) seeds.resize(nproc);
MPI_Gather(&iseed,1,MPI_LONG,&(seeds[0]),1,MPI_LONG,0,MPI_COMM_WORLD);
# else
seeds.resize(1);
seeds[0] = iseed;
# endif
if( verbose && iproc==0 )
{
std::cout << "RNGTestParallelSeed: iproc, seed" << std::endl;
for(int i=0; i<seeds.size(); i++)
std::cout << i << " " << seeds[i] << std::endl;
}
return failed;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Examples of constructing objects and calling tests
////////////////////////////////////////////////////////////////////////////////////////////////////
#if 0
int main(int argc, char* argv[])
{
print_sizeof();
std::cout << std::endl << std::endl;
std::cout << "LinearCongruential32:" << std::endl;
LinearCongruential32 urng_lc32;
std::cout << "32bits = " << urng_lc32.test_bits() << std::endl;
for(int i=0; i<10; i++) std::cout << urng_lc32.details() << std::endl;
for(int i=0; i<10; i++) std::cout << urng_lc32() << std::endl;
RNGTestMoments(urng_lc32,true,std::cout);
std::cout << std::endl << std::endl;
std::cout << "MultiplyWithCarry-1:" << std::endl;
MultiplyWithCarry<1> urng_mwc1;
for(int i=0; i<10; i++) std::cout << urng_mwc1() << std::endl;
RNGTestMoments(urng_mwc1,true,std::cout);
std::cout << std::endl << std::endl;
std::cout << "MultiplyWithCarry-4:" << std::endl;
MultiplyWithCarry<4> urng_mwc4;
for(int i=0; i<10; i++) std::cout << urng_mwc4() << std::endl;
RNGTestMoments(urng_mwc1,true,std::cout);
}
#endif // Omit main
#endif
<|endoftext|> |
<commit_before>///
/// \author John Farrier
///
/// \copyright Copyright 2014 John Farrier
///
/// 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 <celero/Benchmark.h>
#include <celero/TestFixture.h>
#include <celero/PimplImpl.h>
#include <celero/TestVector.h>
#include <celero/Utilities.h>
#include <algorithm>
#include <cassert>
using namespace celero;
class Benchmark::Impl
{
public:
Impl() :
name()
{
}
Impl(const std::string& name) :
name(name)
{
}
Impl(const Benchmark& other) :
name(other.pimpl->name)
{
}
Statistics stats;
/// Group name
std::string name;
std::shared_ptr<Experiment> baseline;
std::vector<std::shared_ptr<Experiment>> experiments;
};
Benchmark::Benchmark() :
pimpl()
{
}
Benchmark::Benchmark(const std::string& name) :
pimpl(name)
{
}
Benchmark::Benchmark(const Benchmark& other) :
pimpl(other)
{
}
Benchmark::~Benchmark()
{
}
std::string Benchmark::getName() const
{
return this->pimpl->name;
}
void Benchmark::setBaseline(std::shared_ptr<Experiment> x)
{
this->pimpl->baseline = x;
}
std::shared_ptr<Experiment> Benchmark::getBaseline() const
{
return this->pimpl->baseline;
}
void Benchmark::addExperiment(std::shared_ptr<Experiment> x)
{
this->pimpl->experiments.push_back(x);
}
std::shared_ptr<Experiment> Benchmark::getExperiment(size_t x)
{
// This is unsafe, but not user code. I'll accept the risk.
return this->pimpl->experiments[x];
}
std::shared_ptr<Experiment> Benchmark::getExperiment(const std::string& x)
{
return *std::find_if(std::begin(this->pimpl->experiments), std::end(this->pimpl->experiments),
[x](decltype(*std::begin(this->pimpl->experiments)) i)->bool
{
return (i->getName() == x);
});
}
size_t Benchmark::getExperimentSize() const
{
return this->pimpl->experiments.size();
}
<commit_msg>#noissue Removed unnecessary header files.<commit_after>///
/// \author John Farrier
///
/// \copyright Copyright 2014 John Farrier
///
/// 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 <celero/Benchmark.h>
#include <celero/PimplImpl.h>
#include <celero/Utilities.h>
#include <algorithm>
#include <cassert>
using namespace celero;
class Benchmark::Impl
{
public:
Impl() :
name()
{
}
Impl(const std::string& name) :
name(name)
{
}
Impl(const Benchmark& other) :
name(other.pimpl->name)
{
}
Statistics stats;
/// Group name
std::string name;
std::shared_ptr<Experiment> baseline;
std::vector<std::shared_ptr<Experiment>> experiments;
};
Benchmark::Benchmark() :
pimpl()
{
}
Benchmark::Benchmark(const std::string& name) :
pimpl(name)
{
}
Benchmark::Benchmark(const Benchmark& other) :
pimpl(other)
{
}
Benchmark::~Benchmark()
{
}
std::string Benchmark::getName() const
{
return this->pimpl->name;
}
void Benchmark::setBaseline(std::shared_ptr<Experiment> x)
{
this->pimpl->baseline = x;
}
std::shared_ptr<Experiment> Benchmark::getBaseline() const
{
return this->pimpl->baseline;
}
void Benchmark::addExperiment(std::shared_ptr<Experiment> x)
{
this->pimpl->experiments.push_back(x);
}
std::shared_ptr<Experiment> Benchmark::getExperiment(size_t x)
{
// This is unsafe, but not user code. I'll accept the risk.
return this->pimpl->experiments[x];
}
std::shared_ptr<Experiment> Benchmark::getExperiment(const std::string& x)
{
return *std::find_if(std::begin(this->pimpl->experiments), std::end(this->pimpl->experiments),
[x](decltype(*std::begin(this->pimpl->experiments)) i)->bool
{
return (i->getName() == x);
});
}
size_t Benchmark::getExperimentSize() const
{
return this->pimpl->experiments.size();
}
<|endoftext|> |
<commit_before>/*
* This file is part of TelepathyQt4
*
* Copyright (C) 2008 Collabora Ltd. <http://www.collabora.co.uk/>
* Copyright (C) 2008 Nokia Corporation
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt4/Client/PendingConnection>
#include "TelepathyQt4/Client/_gen/pending-connection.moc.hpp"
#include "TelepathyQt4/debug-internal.h"
#include <TelepathyQt4/Client/ConnectionManager>
#include <TelepathyQt4/Client/Connection>
#include <QDBusObjectPath>
#include <QDBusPendingCallWatcher>
#include <QDBusPendingReply>
/**
* \addtogroup clientsideproxies Client-side proxies
*
* Proxy objects representing remote service objects accessed via D-Bus.
*
* In addition to providing direct access to methods, signals and properties
* exported by the remote objects, some of these proxies offer features like
* automatic inspection of remote object capabilities, property tracking,
* backwards compatibility helpers for older services and other utilities.
*/
namespace Telepathy
{
namespace Client
{
struct PendingConnection::Private
{
Private(const ConnectionManagerPtr &manager) :
manager(manager)
{
}
ConnectionManagerPtr manager;
ConnectionPtr connection;
QString busName;
QDBusObjectPath objectPath;
};
/**
* \class PendingConnection
* \ingroup clientconnection
* \headerfile <TelepathyQt4/Client/pending-connection.h> <TelepathyQt4/Client/PendingConnection>
*
* Class containing the parameters of and the reply to an asynchronous connection
* request. Instances of this class cannot be constructed directly; the only
* way to get one is via ConnectionManager.
*/
/**
* Construct a PendingConnection object.
*
* \param manager ConnectionManager to use.
* \param protocol Name of the protocol to create the connection for.
* \param parameters Connection parameters.
*/
PendingConnection::PendingConnection(const ConnectionManagerPtr &manager,
const QString &protocol, const QVariantMap ¶meters)
: PendingOperation(manager.data()),
mPriv(new Private(manager))
{
QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(
manager->baseInterface()->RequestConnection(protocol,
parameters), this);
connect(watcher,
SIGNAL(finished(QDBusPendingCallWatcher *)),
SLOT(onCallFinished(QDBusPendingCallWatcher *)));
}
/**
* Class destructor.
*/
PendingConnection::~PendingConnection()
{
delete mPriv;
}
/**
* Return the ConnectionManager object through which the request was made.
*
* \return Connection Manager object.
*/
ConnectionManagerPtr PendingConnection::manager() const
{
return mPriv->manager;
}
/**
* Returns the newly created Connection object.
*
* \return Connection object.
*/
ConnectionPtr PendingConnection::connection() const
{
if (!isFinished()) {
warning() << "PendingConnection::connection called before finished, returning 0";
return ConnectionPtr();
} else if (!isValid()) {
warning() << "PendingConnection::connection called when not valid, returning 0";
return ConnectionPtr();
}
if (!mPriv->connection) {
mPriv->connection = Connection::create(mPriv->manager->dbusConnection(),
mPriv->busName, mPriv->objectPath.path());
}
return mPriv->connection;
}
/**
* Returns the connection's bus name ("service name"), or an empty string on
* error.
*
* This method is useful for creating custom Connection objects: instead
* of using PendingConnection::connection, one could construct a new custom
* connection from the bus name and object path.
*
* \return Connection bus name
* \sa objectPath()
*/
QString PendingConnection::busName() const
{
if (!isFinished()) {
warning() << "PendingConnection::busName called before finished";
} else if (!isValid()) {
warning() << "PendingConnection::busName called when not valid";
}
return mPriv->busName;
}
/**
* Returns the connection's object path or an empty string on error.
*
* This method is useful for creating custom Connection objects: instead
* of using PendingConnection::connection, one could construct a new custom
* connection with the bus name and object path.
*
* \return Connection object path
* \sa busName()
*/
QString PendingConnection::objectPath() const
{
if (!isFinished()) {
warning() << "PendingConnection::connection called before finished";
} else if (!isValid()) {
warning() << "PendingConnection::connection called when not valid";
}
return mPriv->objectPath.path();
}
void PendingConnection::onCallFinished(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<QString, QDBusObjectPath> reply = *watcher;
if (!reply.isError()) {
mPriv->busName = reply.argumentAt<0>();
mPriv->objectPath = reply.argumentAt<1>();
debug() << "Got reply to ConnectionManager.CreateConnection - bus name:" <<
mPriv->busName << "- object path:" << mPriv->objectPath.path();
setFinished();
} else {
debug().nospace() <<
"CreateConnection failed: " <<
reply.error().name() << ": " << reply.error().message();
setFinishedWithError(reply.error());
}
watcher->deleteLater();
}
} // Telepathy::Client
} // Telepathy
<commit_msg>PendingConnection: Hold a weak ref to connection manager.<commit_after>/*
* This file is part of TelepathyQt4
*
* Copyright (C) 2008 Collabora Ltd. <http://www.collabora.co.uk/>
* Copyright (C) 2008 Nokia Corporation
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt4/Client/PendingConnection>
#include "TelepathyQt4/Client/_gen/pending-connection.moc.hpp"
#include "TelepathyQt4/debug-internal.h"
#include <TelepathyQt4/Client/ConnectionManager>
#include <TelepathyQt4/Client/Connection>
#include <QDBusObjectPath>
#include <QDBusPendingCallWatcher>
#include <QDBusPendingReply>
/**
* \addtogroup clientsideproxies Client-side proxies
*
* Proxy objects representing remote service objects accessed via D-Bus.
*
* In addition to providing direct access to methods, signals and properties
* exported by the remote objects, some of these proxies offer features like
* automatic inspection of remote object capabilities, property tracking,
* backwards compatibility helpers for older services and other utilities.
*/
namespace Telepathy
{
namespace Client
{
struct PendingConnection::Private
{
Private(const ConnectionManagerPtr &manager) :
manager(manager)
{
}
WeakPtr<ConnectionManager> manager;
ConnectionPtr connection;
QString busName;
QDBusObjectPath objectPath;
};
/**
* \class PendingConnection
* \ingroup clientconnection
* \headerfile <TelepathyQt4/Client/pending-connection.h> <TelepathyQt4/Client/PendingConnection>
*
* Class containing the parameters of and the reply to an asynchronous connection
* request. Instances of this class cannot be constructed directly; the only
* way to get one is via ConnectionManager.
*/
/**
* Construct a PendingConnection object.
*
* \param manager ConnectionManager to use.
* \param protocol Name of the protocol to create the connection for.
* \param parameters Connection parameters.
*/
PendingConnection::PendingConnection(const ConnectionManagerPtr &manager,
const QString &protocol, const QVariantMap ¶meters)
: PendingOperation(manager.data()),
mPriv(new Private(manager))
{
QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(
manager->baseInterface()->RequestConnection(protocol,
parameters), this);
connect(watcher,
SIGNAL(finished(QDBusPendingCallWatcher *)),
SLOT(onCallFinished(QDBusPendingCallWatcher *)));
}
/**
* Class destructor.
*/
PendingConnection::~PendingConnection()
{
delete mPriv;
}
/**
* Return the ConnectionManager object through which the request was made.
*
* \return Connection Manager object.
*/
ConnectionManagerPtr PendingConnection::manager() const
{
return mPriv->manager;
}
/**
* Returns the newly created Connection object.
*
* \return Connection object.
*/
ConnectionPtr PendingConnection::connection() const
{
if (!isFinished()) {
warning() << "PendingConnection::connection called before finished, returning 0";
return ConnectionPtr();
} else if (!isValid()) {
warning() << "PendingConnection::connection called when not valid, returning 0";
return ConnectionPtr();
}
if (!mPriv->connection) {
ConnectionManagerPtr manager(mPriv->manager);
mPriv->connection = Connection::create(manager->dbusConnection(),
mPriv->busName, mPriv->objectPath.path());
}
return mPriv->connection;
}
/**
* Returns the connection's bus name ("service name"), or an empty string on
* error.
*
* This method is useful for creating custom Connection objects: instead
* of using PendingConnection::connection, one could construct a new custom
* connection from the bus name and object path.
*
* \return Connection bus name
* \sa objectPath()
*/
QString PendingConnection::busName() const
{
if (!isFinished()) {
warning() << "PendingConnection::busName called before finished";
} else if (!isValid()) {
warning() << "PendingConnection::busName called when not valid";
}
return mPriv->busName;
}
/**
* Returns the connection's object path or an empty string on error.
*
* This method is useful for creating custom Connection objects: instead
* of using PendingConnection::connection, one could construct a new custom
* connection with the bus name and object path.
*
* \return Connection object path
* \sa busName()
*/
QString PendingConnection::objectPath() const
{
if (!isFinished()) {
warning() << "PendingConnection::connection called before finished";
} else if (!isValid()) {
warning() << "PendingConnection::connection called when not valid";
}
return mPriv->objectPath.path();
}
void PendingConnection::onCallFinished(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<QString, QDBusObjectPath> reply = *watcher;
if (!reply.isError()) {
mPriv->busName = reply.argumentAt<0>();
mPriv->objectPath = reply.argumentAt<1>();
debug() << "Got reply to ConnectionManager.CreateConnection - bus name:" <<
mPriv->busName << "- object path:" << mPriv->objectPath.path();
setFinished();
} else {
debug().nospace() <<
"CreateConnection failed: " <<
reply.error().name() << ": " << reply.error().message();
setFinishedWithError(reply.error());
}
watcher->deleteLater();
}
} // Telepathy::Client
} // Telepathy
<|endoftext|> |
<commit_before>/**
* @file broker.hpp
* @brief Component Broker
* @author Byunghun Hwang<bhhwang@nsynapse.com>
* @date 2015. 6. 21
* @details
*/
#ifndef _COSSB_BROKER_HPP_
#define _COSSB_BROKER_HPP_
#include <map>
#include <string>
#include "interface/icomponent.hpp"
#include "arch/singleton.hpp"
using namespace std;
namespace cossb {
namespace broker {
//(topic, component name) pair
typedef multimap<string, string> topic_map;
class component_broker : public arch::singleton<component_broker> {
public:
component_broker();
virtual ~component_broker();
/**
*@brief regist component with topic
*/
bool regist(interface::icomponent* component, string topic_name);
private:
static component_broker* _instance;
topic_map _topic_map;
};
#define cossb_component_broker cossb::broker::component_broker::instance()
} /* namespace broker */
} /* namespace cossb */
#endif
<commit_msg>remove instance variable in private, unnecessary<commit_after>/**
* @file broker.hpp
* @brief Component Broker
* @author Byunghun Hwang<bhhwang@nsynapse.com>
* @date 2015. 6. 21
* @details
*/
#ifndef _COSSB_BROKER_HPP_
#define _COSSB_BROKER_HPP_
#include <map>
#include <string>
#include "interface/icomponent.hpp"
#include "arch/singleton.hpp"
using namespace std;
namespace cossb {
namespace broker {
//(topic, component name) pair
typedef multimap<string, string> topic_map;
class component_broker : public arch::singleton<component_broker> {
public:
component_broker();
virtual ~component_broker();
/**
*@brief regist component with topic
*/
bool regist(interface::icomponent* component, string topic_name);
private:
topic_map _topic_map;
};
#define cossb_component_broker cossb::broker::component_broker::instance()
} /* namespace broker */
} /* namespace cossb */
#endif
<|endoftext|> |
<commit_before>/**
* @file broker.hpp
* @brief Component Broker
* @author Byunghun Hwang<bhhwang@nsynapse.com>
* @date 2015. 6. 21
* @details
*/
#ifndef _COSSB_BROKER_HPP_
#define _COSSB_BROKER_HPP_
#include <map>
#include <string>
#include "interface/icomponent.hpp"
#include "arch/singleton.hpp"
#include "manager.hpp"
#include "logger.hpp"
#include "exception.hpp"
using namespace std;
namespace cossb {
namespace broker {
//(topic, component name) pair
typedef multimap<string, string> topic_map;
class component_broker : public arch::singleton<component_broker> {
public:
component_broker() { };
virtual ~component_broker() { };
/**
*@brief regist component with topic
*/
bool regist(interface::icomponent* component, string topic_name) {
_topic_map.insert(topic_map::value_type(topic_name, component->get_name()));
return true;
}
/**
* @brief publish data pack to specific service component
*/
template<typename... Args>
bool publish(interface::icomponent* component, const char* to_topic, const char* api, const Args&... args) {
auto range = _topic_map.equal_range(to_topic);
for(topic_map::iterator itr = range.first; itr!=range.second; ++itr) {
if(itr->second.compare(component->get_name())==0) {
driver::component_driver* _drv = cossb_component_manager->get_driver(itr->second.c_str());
if(_drv) {
_drv->request(api, args...);
}
else
throw broker::exception(cossb::broker::excode::DRIVER_NOT_FOUND);
}
}
return true;
}
private:
topic_map _topic_map;
};
#define cossb_broker cossb::broker::component_broker::instance()
} /* namespace broker */
} /* namespace cossb */
#endif
<commit_msg>publish function returns unsigned int what for times transferred<commit_after>/**
* @file broker.hpp
* @brief Component Broker
* @author Byunghun Hwang<bhhwang@nsynapse.com>
* @date 2015. 6. 21
* @details
*/
#ifndef _COSSB_BROKER_HPP_
#define _COSSB_BROKER_HPP_
#include <map>
#include <string>
#include "interface/icomponent.hpp"
#include "arch/singleton.hpp"
#include "manager.hpp"
#include "logger.hpp"
#include "exception.hpp"
using namespace std;
namespace cossb {
namespace broker {
//(topic, component name) pair
typedef multimap<string, string> topic_map;
class component_broker : public arch::singleton<component_broker> {
public:
component_broker() { };
virtual ~component_broker() { };
/**
*@brief regist component with topic
*/
bool regist(interface::icomponent* component, string topic_name) {
_topic_map.insert(topic_map::value_type(topic_name, component->get_name()));
return true;
}
/**
* @brief publish data pack to specific service component
* @return times published
*/
template<typename... Args>
unsigned int publish(interface::icomponent* component, const char* to_topic, const char* api, const Args&... args) {
auto range = _topic_map.equal_range(to_topic);
unsigned int times = 0;
for(topic_map::iterator itr = range.first; itr!=range.second; ++itr) {
if(itr->second.compare(component->get_name())==0) {
driver::component_driver* _drv = cossb_component_manager->get_driver(itr->second.c_str());
if(_drv) {
_drv->request(api, args...);
times++;
}
else
throw broker::exception(cossb::broker::excode::DRIVER_NOT_FOUND);
}
}
return times;
}
private:
topic_map _topic_map;
};
#define cossb_broker cossb::broker::component_broker::instance()
} /* namespace broker */
} /* namespace cossb */
#endif
<|endoftext|> |
<commit_before>#include "cox.h"
//Register addresses
#define CSS811_void 0x00
#define CSS811_MEAS_MODE 0x01
#define CSS811_ALG_RESULT_DATA 0x02
#define CSS811_RAW_DATA 0x03
#define CSS811_ENV_DATA 0x05
#define CSS811_NTC 0x06
#define CSS811_THRESHOLDS 0x10
#define CSS811_BASELINE 0x11
#define CSS811_HW_ID 0x20
#define CSS811_HW_VERSION 0x21
#define CSS811_FW_BOOT_VERSION 0x23
#define CSS811_FW_APP_VERSION 0x24
#define CSS811_ERROR_ID 0xE0
#define CSS811_APP_START 0xF4
#define CSS811_SW_RESET 0xFF
class CCS811Core{
public:
// Return values
typedef enum{
SENSOR_SUCCESS,
SENSOR_ID_ERROR,
SENSOR_I2C_ERROR,
SENSOR_INTERNAL_ERROR,
SENSOR_GENERIC_ERROR
}status;
CCS811Core(TwoWire &, uint8_t addr);
~CCS811Core() = default;
status beginCore( void );
status readRegister( uint8_t offset, uint8_t* outputPointer);
status multiReadRegister(uint8_t offset, uint8_t *outputPointer, uint8_t length);
status writeRegister(uint8_t offset, uint8_t dataToWrite);
status multiWriteRegister(uint8_t offset, uint8_t *inputPointer, uint8_t length);
protected:
TwoWire &Wire;
uint8_t I2CAddress;
};
class CCS811: public CCS811Core{
public:
CCS811(TwoWire &, uint8_t addr);
status begin( void );
status setDriveMode( uint8_t mode );
status readAlgorithmResults( void );
bool dataAvailable( void );
uint16_t getTVOC( void );
uint16_t getCO2e( void );
private:
TwoWire &Wire;
uint8_t I2CAddress;
float refResistance;
float resistance;
float temperature;
uint16_t tVOC;
uint16_t CO2e;
};
<commit_msg>Removed duplicate variables.<commit_after>#include "cox.h"
//Register addresses
#define CSS811_void 0x00
#define CSS811_MEAS_MODE 0x01
#define CSS811_ALG_RESULT_DATA 0x02
#define CSS811_RAW_DATA 0x03
#define CSS811_ENV_DATA 0x05
#define CSS811_NTC 0x06
#define CSS811_THRESHOLDS 0x10
#define CSS811_BASELINE 0x11
#define CSS811_HW_ID 0x20
#define CSS811_HW_VERSION 0x21
#define CSS811_FW_BOOT_VERSION 0x23
#define CSS811_FW_APP_VERSION 0x24
#define CSS811_ERROR_ID 0xE0
#define CSS811_APP_START 0xF4
#define CSS811_SW_RESET 0xFF
class CCS811Core{
public:
// Return values
typedef enum{
SENSOR_SUCCESS,
SENSOR_ID_ERROR,
SENSOR_I2C_ERROR,
SENSOR_INTERNAL_ERROR,
SENSOR_GENERIC_ERROR
}status;
CCS811Core(TwoWire &, uint8_t addr);
~CCS811Core() = default;
status beginCore( void );
status readRegister( uint8_t offset, uint8_t* outputPointer);
status multiReadRegister(uint8_t offset, uint8_t *outputPointer, uint8_t length);
status writeRegister(uint8_t offset, uint8_t dataToWrite);
status multiWriteRegister(uint8_t offset, uint8_t *inputPointer, uint8_t length);
protected:
TwoWire &Wire;
uint8_t I2CAddress;
};
class CCS811: public CCS811Core{
public:
CCS811(TwoWire &, uint8_t addr);
status begin( void );
status setDriveMode( uint8_t mode );
status readAlgorithmResults( void );
bool dataAvailable( void );
uint16_t getTVOC( void );
uint16_t getCO2e( void );
private:
float refResistance;
float resistance;
float temperature;
uint16_t tVOC;
uint16_t CO2e;
};
<|endoftext|> |
<commit_before>///
/// @file int128.hpp
/// @brief Additional integer types used in primecount:
/// int128_t, uint128_t, intfast64_t, intfast128_t, maxint_t,
/// maxuint_t.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef INTTYPES_HPP
#define INTTYPES_HPP
#include <limits>
#include <stdint.h>
#if __cplusplus >= 201103L
#include <type_traits>
#endif
#if defined(HAVE_INT128_T)
namespace primecount {
typedef int128_t maxint_t;
typedef uint128_t maxuint_t;
}
#elif defined(HAVE___INT128_T)
#define HAVE_INT128_T
#include <ostream>
#include <string>
namespace primecount {
typedef __int128_t int128_t;
typedef __uint128_t uint128_t;
typedef __int128_t maxint_t;
typedef __uint128_t maxuint_t;
inline std::ostream& operator<<(std::ostream& stream, uint128_t n)
{
std::string str;
while (n > 0)
{
str += '0' + n % 10;
n /= 10;
}
if (str.empty())
str = "0";
stream << std::string(str.rbegin(), str.rend());
return stream;
}
inline std::ostream& operator<<(std::ostream& stream, int128_t n)
{
if (n < 0)
{
stream << "-";
n = -n;
}
stream << (uint128_t) n;
return stream;
}
} // namespace
#else /* int128_t not supported */
namespace primecount {
typedef int64_t maxint_t;
typedef int64_t maxuint_t;
}
#endif /* HAVE_INT128_T */
namespace primecount {
/// Fastest 64-bit integer type for division.
/// On most Intel CPUs before 2015 unsigned 64-bit division is about
/// 10 percent faster than signed division. It is likely that in a few
/// years signed and unsigned division will run equally fast.
///
typedef uint64_t intfast64_t;
#if defined(HAVE_INT128_T)
/// Fastest 128-bit integer type for division.
/// On the author's Intel Core-i7 4770 CPU from 2013 using uint128_t
/// instead of int128_t gives 10 percent better performance.
///
typedef uint128_t intfast128_t;
#endif
/// Portable namespace, includes functions which (unlike the versions
/// form the C++ standard library) work with the int128_t and
/// uint128_t types (2014).
///
namespace prt {
#if __cplusplus >= 201103L
#define CONSTEXPR constexpr
#else
#define CONSTEXPR
#endif
template <typename T>
struct numeric_limits
{
static CONSTEXPR T max()
{
return std::numeric_limits<T>::max();
}
};
#if defined(HAVE_INT128_T)
template <>
struct numeric_limits<int128_t>
{
static CONSTEXPR int128_t max()
{
return ~(((int128_t) 1) << 127);
}
};
template <>
struct numeric_limits<uint128_t>
{
static CONSTEXPR uint128_t max()
{
return ~((int128_t) 0);
}
};
#endif
#undef CONSTEXPR
#if __cplusplus >= 201103L
template <typename T>
struct make_signed
{
#ifndef HAVE_INT128_T
typedef typename std::make_signed<T>::type type;
#else
typedef typename std::conditional<std::is_same<T, uint8_t>::value, int8_t,
typename std::conditional<std::is_same<T, uint16_t>::value, int16_t,
typename std::conditional<std::is_same<T, uint32_t>::value, int32_t,
typename std::conditional<std::is_same<T, uint64_t>::value, int64_t,
typename std::conditional<std::is_same<T, uint128_t>::value, int128_t,
T>::type>::type>::type>::type>::type type;
#endif
};
template <typename T>
struct is_integral
{
enum
{
#ifndef HAVE_INT128_T
value = std::is_integral<T>::value
#else
value = std::is_integral<T>::value ||
std::is_same<T, int128_t>::value ||
std::is_same<T, uint128_t>::value
#endif
};
};
#endif /* __cplusplus >= 201103L */
} // namespace prt
} // namespace primecount
#endif /* INTTYPES_HPP */
<commit_msg>Add prt::is_signed<commit_after>///
/// @file int128.hpp
/// @brief Additional integer types used in primecount:
/// int128_t, uint128_t, intfast64_t, intfast128_t, maxint_t,
/// maxuint_t.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef INTTYPES_HPP
#define INTTYPES_HPP
#include <limits>
#include <stdint.h>
#if __cplusplus >= 201103L
#include <type_traits>
#endif
#if defined(HAVE_INT128_T)
namespace primecount {
typedef int128_t maxint_t;
typedef uint128_t maxuint_t;
}
#elif defined(HAVE___INT128_T)
#define HAVE_INT128_T
#include <ostream>
#include <string>
namespace primecount {
typedef __int128_t int128_t;
typedef __uint128_t uint128_t;
typedef __int128_t maxint_t;
typedef __uint128_t maxuint_t;
inline std::ostream& operator<<(std::ostream& stream, uint128_t n)
{
std::string str;
while (n > 0)
{
str += '0' + n % 10;
n /= 10;
}
if (str.empty())
str = "0";
stream << std::string(str.rbegin(), str.rend());
return stream;
}
inline std::ostream& operator<<(std::ostream& stream, int128_t n)
{
if (n < 0)
{
stream << "-";
n = -n;
}
stream << (uint128_t) n;
return stream;
}
} // namespace
#else /* int128_t not supported */
namespace primecount {
typedef int64_t maxint_t;
typedef int64_t maxuint_t;
}
#endif /* HAVE_INT128_T */
namespace primecount {
/// Fastest 64-bit integer type for division.
/// On most Intel CPUs before 2015 unsigned 64-bit division is about
/// 10 percent faster than signed division. It is likely that in a few
/// years signed and unsigned division will run equally fast.
///
typedef uint64_t intfast64_t;
#if defined(HAVE_INT128_T)
/// Fastest 128-bit integer type for division.
/// On the author's Intel Core-i7 4770 CPU from 2013 using uint128_t
/// instead of int128_t gives 10 percent better performance.
///
typedef uint128_t intfast128_t;
#endif
/// Portable namespace, includes functions which (unlike the versions
/// form the C++ standard library) work with the int128_t and
/// uint128_t types (2014).
///
namespace prt {
#if __cplusplus >= 201103L
#define CONSTEXPR constexpr
#else
#define CONSTEXPR
#endif
template <typename T>
struct numeric_limits
{
static CONSTEXPR T max()
{
return std::numeric_limits<T>::max();
}
};
#if defined(HAVE_INT128_T)
template <>
struct numeric_limits<int128_t>
{
static CONSTEXPR int128_t max()
{
return ~(((int128_t) 1) << 127);
}
};
template <>
struct numeric_limits<uint128_t>
{
static CONSTEXPR uint128_t max()
{
return ~((int128_t) 0);
}
};
#endif
#undef CONSTEXPR
#if __cplusplus >= 201103L
template <typename T>
struct make_signed
{
#ifndef HAVE_INT128_T
typedef typename std::make_signed<T>::type type;
#else
typedef typename std::conditional<std::is_same<T, uint8_t>::value, int8_t,
typename std::conditional<std::is_same<T, uint16_t>::value, int16_t,
typename std::conditional<std::is_same<T, uint32_t>::value, int32_t,
typename std::conditional<std::is_same<T, uint64_t>::value, int64_t,
typename std::conditional<std::is_same<T, uint128_t>::value, int128_t,
T>::type>::type>::type>::type>::type type;
#endif
};
template <typename T>
struct is_integral
{
enum
{
#ifndef HAVE_INT128_T
value = std::is_integral<T>::value
#else
value = std::is_integral<T>::value ||
std::is_same<T, int128_t>::value ||
std::is_same<T, uint128_t>::value
#endif
};
};
template <typename T>
struct is_signed
{
enum
{
#ifndef HAVE_INT128_T
value = std::is_signed<T>::value
#else
value = std::is_signed<T>::value ||
std::is_same<T, int128_t>::value
#endif
};
};
#endif /* __cplusplus >= 201103L */
} // namespace prt
} // namespace primecount
#endif /* INTTYPES_HPP */
<|endoftext|> |
<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 <string>
#include <utils.hpp>
#include <Observation.hpp>
#ifndef BEAM_FORMER_HPP
#define BEAM_FORMER_HPP
namespace RadioAstronomy {
// Sequential beam forming algorithm
template< typename T > beamFormer(const AstroData::Observation & observation, const std::vector< T > & samples, std::vector< T > & output, const std::vector< float > & weights);
// OpenCL beam forming algorithm
std::string * getBeamFormerOpenCL(const unsigned int nrSamplesPerBlock, const unsigned int nrBeamsPerBlock, const unsigned int nrSamplesPerThread, const unsigned int nrBeamsPerThread, const std::string & dataType, const AstroData::Observation & observation);
// Implementations
template< typename T > beamFormer(const AstroData::Observation & observation, const std::vector< T > & samples, std::vector< T > & output, const std::vector< float > & weights) {
for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) {
for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {
for ( unsigned int beam = 0; beam < observation.getNrBeams(); beam++ ) {
T beamP0_r = 0;
T beamP0_i = 0;
T beamP1_r = 0;
T beamP1_i = 0;
for ( unsigned int station = 0; station < observation.getNrStations(); station++ ) {
T * samplePointer = &(samples[(channel * observation.getNrStations() * observation.getNrSamplesPerPaddedSecond() * 4) + (station * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4)]);
float * weightPointer = &(weights[(channel * observation.getNrStations() * observation.getNrPaddedBeams() * 2) + (station * observation.getNrPaddedBeams() * 2) + (beam * 2)]);
beamP0_r += (samplePointer[0] * weightPointer[0]) - (samplePointer[1] * weightPointer[1]);
beamP0_i += (samplePointer[0] * weightPointer[1]) + (samplePointer[1] * weightPointer[0]);
beamP1_r += (samplePointer[2] * weightPointer[0]) - (samplePointer[3] * weightPointer[1]);
beamP1_i += (samplePointer[2] * weightPointer[1]) + (samplePointer[3] * weightPointer[0]);
}
beamP0_r /= observation.getNrStations();
beamP0_i /= observation.getNrStations();
beamP1_r /= observation.getNrStations();
beamP1_i /= observation.getNrStations();
output[(beam * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * 4) + (channel * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4)] = beamP0_r;
output[(beam * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * 4) + (channel * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4) + 1] = beamP0_i;
output[(beam * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * 4) + (channel * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4) + 2] = beamP1_r;
output[(beam * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * 4) + (channel * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4) + 3] = beamP1_i;
}
}
}
}
std::string * getBeamFormerOpenCL(const unsigned int nrSamplesPerBlock, const unsigned int nrBeamsPerBlock, const unsigned int nrSamplesPerThread, const unsigned int nrBeamsPerThread, const std::string & dataType, const AstroData::Observation & observation) {
std::string * code = new std::string();
// Begin kernel's template
*code = "__kernel void beamFormer(__global const " + dataType + "4 * restrict const samples, __global " + dataType + "4 * restrict const output, __global const float2 * restrict const weights) {\n"
"const unsigned int channel = get_group_id(2);\n"
"const unsigned int beam = (get_group_id(1) * " + isa::utils::toString(nrBeamsPerBlock * nrBeamsPerThread) + ") + (get_local_id(1) * " + isa::utils::toString(nrBeamsPerThread) + ");\n"
"unsigned int itemGlobal = 0;\n"
"unsigned int itemLocal = 0;\n"
"<%DEF_SAMPLES%>"
"<%DEF_SUMS%>"
+ dataType + "4 sample = (" + dataType + "4)(0);\n"
"__local float2 localWeights[" + isa::utils::toString(nrBeamsPerBlock * nrBeamsPerThread) + "];\n"
"float2 weight = (float2)(0);\n"
"\n"
"for ( unsigned int station = 0; station < " + isa::utils::toString(observation.getNrStations()) + "; station++ ) {\n"
"<%LOAD_COMPUTE%>"
"}\n"
"<%AVERAGE%>"
"<%STORE%>"
"}\n";
std::string defSamplesTemplate = "const unsigned int sample<%SNUM%> = (get_group_id(0) * " + isa::utils::toString(nrSamplesPerBlock * nrSamplesPerThread) + ") + get_local_id(0) + <%OFFSET%>;\n";
std::string defSumsTemplate = dataType + "4 beam<%BNUM%>s<%SNUM%> = (" + dataType + "4)(0);\n";
std::string loadComputeTemplate = "itemGlobal = (channel * " + isa::utils::toString(observation.getNrStations() * observation.getNrPaddedBeams()) + ") + (station * " + isa::utils::toString(observation.getNrPaddedBeams()) + ") + (get_local_id(1) * " + isa::utils::toString(nrSamplesPerBlock) + ") + get_local_id(0);\n"
"itemLocal = get_local_id(0);\n"
"while ( itemLocal < " + isa::utils::toString(nrBeamsPerBlock * nrBeamsPerThread) + ") {\n"
"localWeights[itemLocal] = weights[itemGlobal];\n"
"itemLocal += " + isa::utils::toString(nrSamplesPerBlock * nrBeamsPerBlock) + ";\n"
"itemGlobal += " + isa::utils::toString(nrSamplesPerBlock * nrBeamsPerBlock) + ";\n"
"}\n"
"barrier(CLK_LOCAL_MEM_FENCE);\n"
"sample = samples[(channel * " + isa::utils::toString(observation.getNrStations() * observation.getNrSamplesPerPaddedSecond()) + ") + (station * " + isa::utils::toString(observation.getNrSamplesPerPaddedSecond()) + ") + sample<%SNUM%>];\n"
"<%SUMS%>";
std::string sumsTemplate = "weight = localWeights[(get_local_id(1) * " + isa::utils::toString(nrBeamsPerThread) + ") + <%BNUM%>];\n"
"beam<%BNUM%>s<%SNUM%>.x += (sample.x * weight.x) - (sample.y * weight.y);\n"
"beam<%BNUM%>s<%SNUM%>.y += (sample.x * weight.y) + (sample.y * weight.x);\n"
"beam<%BNUM%>s<%SNUM%>.z += (sample.z * weight.x) - (sample.w * weight.y);\n"
"beam<%BNUM%>s<%SNUM%>.w += (sample.z * weight.y) + (sample.w * weight.x);\n";
std::string averageTemplate = "beam<%BNUM%>s<%SNUM%> *= " + isa::utils::toString(1.0f / observation.getNrStations()) + "f;\n";
std::string storeTemplate = "output[((beam + <%BNUM%>) * " + isa::utils::toString(observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond()) + ") + (channel * " + isa::utils::toString(observation.getNrSamplesPerPaddedSecond()) + ") + sample<%SNUM%>] = beam<%BNUM%>s<%SNUM%>;\n";
// End kernel's template
std::string * defSamples_s = new std::string();
std::string * defSums_s = new std::string();
std::string * loadCompute_s = new std::string();
std::string * average_s = new std::string();
std::string * store_s = new std::string();
for ( unsigned int sample = 0; sample < nrSamplesPerThread; sample++ ) {
std::string sample_s = isa::utils::toString(sample);
std::string offset_s = isa::utils::toString(sample * nrSamplesPerBlock);
std::string * sums_s = new std::string();
std::string * temp_s = 0;
temp_s = isa::utils::replace(&defSamplesTemplate, "<%SNUM%>", sample_s);
temp_s = isa::utils::replace(temp_s, "<%OFFSET%>", offset_s, true);
defSamples_s->append(*temp_s);
delete temp_s;
for ( unsigned int beam = 0; beam < nrBeamsPerThread; beam++ ) {
std::string beam_s = isa::utils::toString(beam);
std::string * temp_s = 0;
temp_s = isa::utils::replace(&defSumsTemplate, "<%BNUM%>", beam_s);
defSums_s->append(*temp_s);
delete temp_s;
temp_s = isa::utils::replace(&sumsTemplate, "<%BNUM%>", beam_s);
sums_s->append(*temp_s);
delete temp_s;
temp_s = isa::utils::replace(&averageTemplate, "<%BNUM%>", beam_s);
average_s->append(*temp_s);
delete temp_s;
temp_s = isa::utils::replace(&storeTemplate, "<%BNUM%>", beam_s);
store_s->append(*temp_s);
delete temp_s;
}
defSums_s = isa::utils::replace(defSums_s, "<%SNUM%>", sample_s, true);
temp_s = isa::utils::replace(&loadComputeTemplate, "<%SNUM%>", sample_s);
temp_s = isa::utils::replace(temp_s, "<%SUMS%>", *sums_s, true);
temp_s = isa::utils::replace(temp_s, "<%SNUM%>", sample_s, true);
loadCompute_s->append(*temp_s);
delete temp_s;
average_s = isa::utils::replace(average_s, "<%SNUM%>", sample_s, true);
store_s = isa::utils::replace(store_s, "<%SNUM%>", sample_s, true);
}
code = isa::utils::replace(code, "<%DEF_SAMPLES%>", *defSamples_s, true);
code = isa::utils::replace(code, "<%DEF_SUMS%>", *defSums_s, true);
code = isa::utils::replace(code, "<%LOAD_COMPUTE%>", *loadCompute_s, true);
code = isa::utils::replace(code, "<%AVERAGE%>", *average_s, true);
code = isa::utils::replace(code, "<%STORE%>", *store_s, true);
return code;
}
} // RadioAstronomy
#endif // BEAM_FORMER_HPP
<commit_msg>Forgot the return type of the sequential implementation.<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 <string>
#include <utils.hpp>
#include <Observation.hpp>
#ifndef BEAM_FORMER_HPP
#define BEAM_FORMER_HPP
namespace RadioAstronomy {
// Sequential beam forming algorithm
template< typename T > void beamFormer(const AstroData::Observation & observation, const std::vector< T > & samples, std::vector< T > & output, const std::vector< float > & weights);
// OpenCL beam forming algorithm
std::string * getBeamFormerOpenCL(const unsigned int nrSamplesPerBlock, const unsigned int nrBeamsPerBlock, const unsigned int nrSamplesPerThread, const unsigned int nrBeamsPerThread, const std::string & dataType, const AstroData::Observation & observation);
// Implementations
template< typename T > void beamFormer(const AstroData::Observation & observation, const std::vector< T > & samples, std::vector< T > & output, const std::vector< float > & weights) {
for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) {
for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {
for ( unsigned int beam = 0; beam < observation.getNrBeams(); beam++ ) {
T beamP0_r = 0;
T beamP0_i = 0;
T beamP1_r = 0;
T beamP1_i = 0;
for ( unsigned int station = 0; station < observation.getNrStations(); station++ ) {
T * samplePointer = &(samples[(channel * observation.getNrStations() * observation.getNrSamplesPerPaddedSecond() * 4) + (station * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4)]);
float * weightPointer = &(weights[(channel * observation.getNrStations() * observation.getNrPaddedBeams() * 2) + (station * observation.getNrPaddedBeams() * 2) + (beam * 2)]);
beamP0_r += (samplePointer[0] * weightPointer[0]) - (samplePointer[1] * weightPointer[1]);
beamP0_i += (samplePointer[0] * weightPointer[1]) + (samplePointer[1] * weightPointer[0]);
beamP1_r += (samplePointer[2] * weightPointer[0]) - (samplePointer[3] * weightPointer[1]);
beamP1_i += (samplePointer[2] * weightPointer[1]) + (samplePointer[3] * weightPointer[0]);
}
beamP0_r /= observation.getNrStations();
beamP0_i /= observation.getNrStations();
beamP1_r /= observation.getNrStations();
beamP1_i /= observation.getNrStations();
output[(beam * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * 4) + (channel * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4)] = beamP0_r;
output[(beam * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * 4) + (channel * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4) + 1] = beamP0_i;
output[(beam * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * 4) + (channel * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4) + 2] = beamP1_r;
output[(beam * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * 4) + (channel * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4) + 3] = beamP1_i;
}
}
}
}
std::string * getBeamFormerOpenCL(const unsigned int nrSamplesPerBlock, const unsigned int nrBeamsPerBlock, const unsigned int nrSamplesPerThread, const unsigned int nrBeamsPerThread, const std::string & dataType, const AstroData::Observation & observation) {
std::string * code = new std::string();
// Begin kernel's template
*code = "__kernel void beamFormer(__global const " + dataType + "4 * restrict const samples, __global " + dataType + "4 * restrict const output, __global const float2 * restrict const weights) {\n"
"const unsigned int channel = get_group_id(2);\n"
"const unsigned int beam = (get_group_id(1) * " + isa::utils::toString(nrBeamsPerBlock * nrBeamsPerThread) + ") + (get_local_id(1) * " + isa::utils::toString(nrBeamsPerThread) + ");\n"
"unsigned int itemGlobal = 0;\n"
"unsigned int itemLocal = 0;\n"
"<%DEF_SAMPLES%>"
"<%DEF_SUMS%>"
+ dataType + "4 sample = (" + dataType + "4)(0);\n"
"__local float2 localWeights[" + isa::utils::toString(nrBeamsPerBlock * nrBeamsPerThread) + "];\n"
"float2 weight = (float2)(0);\n"
"\n"
"for ( unsigned int station = 0; station < " + isa::utils::toString(observation.getNrStations()) + "; station++ ) {\n"
"<%LOAD_COMPUTE%>"
"}\n"
"<%AVERAGE%>"
"<%STORE%>"
"}\n";
std::string defSamplesTemplate = "const unsigned int sample<%SNUM%> = (get_group_id(0) * " + isa::utils::toString(nrSamplesPerBlock * nrSamplesPerThread) + ") + get_local_id(0) + <%OFFSET%>;\n";
std::string defSumsTemplate = dataType + "4 beam<%BNUM%>s<%SNUM%> = (" + dataType + "4)(0);\n";
std::string loadComputeTemplate = "itemGlobal = (channel * " + isa::utils::toString(observation.getNrStations() * observation.getNrPaddedBeams()) + ") + (station * " + isa::utils::toString(observation.getNrPaddedBeams()) + ") + (get_local_id(1) * " + isa::utils::toString(nrSamplesPerBlock) + ") + get_local_id(0);\n"
"itemLocal = get_local_id(0);\n"
"while ( itemLocal < " + isa::utils::toString(nrBeamsPerBlock * nrBeamsPerThread) + ") {\n"
"localWeights[itemLocal] = weights[itemGlobal];\n"
"itemLocal += " + isa::utils::toString(nrSamplesPerBlock * nrBeamsPerBlock) + ";\n"
"itemGlobal += " + isa::utils::toString(nrSamplesPerBlock * nrBeamsPerBlock) + ";\n"
"}\n"
"barrier(CLK_LOCAL_MEM_FENCE);\n"
"sample = samples[(channel * " + isa::utils::toString(observation.getNrStations() * observation.getNrSamplesPerPaddedSecond()) + ") + (station * " + isa::utils::toString(observation.getNrSamplesPerPaddedSecond()) + ") + sample<%SNUM%>];\n"
"<%SUMS%>";
std::string sumsTemplate = "weight = localWeights[(get_local_id(1) * " + isa::utils::toString(nrBeamsPerThread) + ") + <%BNUM%>];\n"
"beam<%BNUM%>s<%SNUM%>.x += (sample.x * weight.x) - (sample.y * weight.y);\n"
"beam<%BNUM%>s<%SNUM%>.y += (sample.x * weight.y) + (sample.y * weight.x);\n"
"beam<%BNUM%>s<%SNUM%>.z += (sample.z * weight.x) - (sample.w * weight.y);\n"
"beam<%BNUM%>s<%SNUM%>.w += (sample.z * weight.y) + (sample.w * weight.x);\n";
std::string averageTemplate = "beam<%BNUM%>s<%SNUM%> *= " + isa::utils::toString(1.0f / observation.getNrStations()) + "f;\n";
std::string storeTemplate = "output[((beam + <%BNUM%>) * " + isa::utils::toString(observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond()) + ") + (channel * " + isa::utils::toString(observation.getNrSamplesPerPaddedSecond()) + ") + sample<%SNUM%>] = beam<%BNUM%>s<%SNUM%>;\n";
// End kernel's template
std::string * defSamples_s = new std::string();
std::string * defSums_s = new std::string();
std::string * loadCompute_s = new std::string();
std::string * average_s = new std::string();
std::string * store_s = new std::string();
for ( unsigned int sample = 0; sample < nrSamplesPerThread; sample++ ) {
std::string sample_s = isa::utils::toString(sample);
std::string offset_s = isa::utils::toString(sample * nrSamplesPerBlock);
std::string * sums_s = new std::string();
std::string * temp_s = 0;
temp_s = isa::utils::replace(&defSamplesTemplate, "<%SNUM%>", sample_s);
temp_s = isa::utils::replace(temp_s, "<%OFFSET%>", offset_s, true);
defSamples_s->append(*temp_s);
delete temp_s;
for ( unsigned int beam = 0; beam < nrBeamsPerThread; beam++ ) {
std::string beam_s = isa::utils::toString(beam);
std::string * temp_s = 0;
temp_s = isa::utils::replace(&defSumsTemplate, "<%BNUM%>", beam_s);
defSums_s->append(*temp_s);
delete temp_s;
temp_s = isa::utils::replace(&sumsTemplate, "<%BNUM%>", beam_s);
sums_s->append(*temp_s);
delete temp_s;
temp_s = isa::utils::replace(&averageTemplate, "<%BNUM%>", beam_s);
average_s->append(*temp_s);
delete temp_s;
temp_s = isa::utils::replace(&storeTemplate, "<%BNUM%>", beam_s);
store_s->append(*temp_s);
delete temp_s;
}
defSums_s = isa::utils::replace(defSums_s, "<%SNUM%>", sample_s, true);
temp_s = isa::utils::replace(&loadComputeTemplate, "<%SNUM%>", sample_s);
temp_s = isa::utils::replace(temp_s, "<%SUMS%>", *sums_s, true);
temp_s = isa::utils::replace(temp_s, "<%SNUM%>", sample_s, true);
loadCompute_s->append(*temp_s);
delete temp_s;
average_s = isa::utils::replace(average_s, "<%SNUM%>", sample_s, true);
store_s = isa::utils::replace(store_s, "<%SNUM%>", sample_s, true);
}
code = isa::utils::replace(code, "<%DEF_SAMPLES%>", *defSamples_s, true);
code = isa::utils::replace(code, "<%DEF_SUMS%>", *defSums_s, true);
code = isa::utils::replace(code, "<%LOAD_COMPUTE%>", *loadCompute_s, true);
code = isa::utils::replace(code, "<%AVERAGE%>", *average_s, true);
code = isa::utils::replace(code, "<%STORE%>", *store_s, true);
return code;
}
} // RadioAstronomy
#endif // BEAM_FORMER_HPP
<|endoftext|> |
<commit_before>#include "../Common.h"
#include "F200.h"
#include "Projection.h"
#ifndef WIN32
using namespace rs;
namespace f200
{
F200Camera::F200Camera(uvc_context_t * ctx, uvc_device_t * device, int idx) : UVCCamera(ctx, device, idx)
{
}
F200Camera::~F200Camera()
{
}
bool F200Camera::ConfigureStreams()
{
if (streamingModeBitfield == 0)
throw std::invalid_argument("No streams have been configured...");
if (streamingModeBitfield & RS_STREAM_DEPTH)
{
StreamInterface * stream = new StreamInterface();
stream->camera = this;
if (!OpenStreamOnSubdevice(hardware, stream->uvcHandle, 1))
throw std::runtime_error("Failed to open RS_STREAM_DEPTH (subdevice 1)");
// Debugging
uvc_print_stream_ctrl(&stream->ctrl, stdout);
streamInterfaces.insert(std::pair<int, StreamInterface *>(RS_STREAM_DEPTH, stream));
}
if (streamingModeBitfield & RS_STREAM_RGB)
{
StreamInterface * stream = new StreamInterface();
stream->camera = this;
if (!OpenStreamOnSubdevice(hardware, stream->uvcHandle, 0))
throw std::runtime_error("Failed to open RS_STREAM_RGB (subdevice 2)");
// Debugging
uvc_print_stream_ctrl(&stream->ctrl, stdout);
streamInterfaces.insert(std::pair<int, StreamInterface *>(RS_STREAM_RGB, stream));
}
GetUSBInfo(hardware, usbInfo);
std::cout << "Serial Number: " << usbInfo.serial << std::endl;
std::cout << "USB VID: " << usbInfo.vid << std::endl;
std::cout << "USB PID: " << usbInfo.pid << std::endl;
////////////////////////////////////////////////////////////////////////////
hardware_io.reset(new IVCAMHardwareIO(internalContext));
// Set up calibration parameters for internal undistortion
const CameraCalibrationParameters & calib = hardware_io->GetParameters();
const OpticalData & od = hardware_io->GetOpticalData();
rs_intrinsics rect = {}, unrect = {};
rs_extrinsics rotation = {{1.f,0.f,0.f,0.f,1.f,0.f,0.f,0.f,1.f},{0.f,0.f,0.f}};
const int ivWidth = 640;
const int ivHeight = 480;
rect.image_size[0] = ivWidth;
rect.image_size[1] = ivHeight;
rect.focal_length[0] = od.IRUndistortedFocalLengthPxl.x;
rect.focal_length[1] = od.IRUndistortedFocalLengthPxl.y;
rect.principal_point[0] = (ivWidth / 2); // Leo hack not to use real pp
rect.principal_point[1] = (ivHeight / 2); // Ditto
unrect.image_size[0] = ivWidth;
unrect.image_size[1] = ivHeight;
unrect.focal_length[0] = od.IRDistortedFocalLengthPxl.x;
unrect.focal_length[1] = od.IRDistortedFocalLengthPxl.x; // Leo hack for "Squareness"
unrect.principal_point[0] = od.IRPrincipalPoint.x + (ivWidth / 2);
unrect.principal_point[1] = od.IRPrincipalPoint.y + (ivHeight / 2);
unrect.distortion_coeff[0] = calib.Distc[0];
unrect.distortion_coeff[1] = calib.Distc[1];
unrect.distortion_coeff[2] = calib.Distc[2];
unrect.distortion_coeff[3] = calib.Distc[3];
unrect.distortion_coeff[4] = calib.Distc[4];
rectifier.reset(new IVRectifier(ivWidth, ivHeight, rect, unrect, rotation));
////////////////////////////////////////////////////////////////////////////
return true;
}
void F200Camera::StartStream(int streamIdentifier, const StreamConfiguration & c)
{
auto stream = streamInterfaces[streamIdentifier];
if (stream->uvcHandle)
{
stream->fmt = static_cast<uvc_frame_format>(c.format);
uvc_error_t status = uvc_get_stream_ctrl_format_size(stream->uvcHandle, &stream->ctrl, stream->fmt, c.width, c.height, c.fps);
if (status < 0)
{
uvc_perror(status, "uvc_get_stream_ctrl_format_size");
throw std::runtime_error("Open camera_handle Failed");
}
switch (c.format)
{
case FrameFormat::INVR:
case FrameFormat::INVZ:
depthFrame = TripleBufferedFrame(c.width, c.height, sizeof(uint16_t)); break;
case FrameFormat::YUYV:
colorFrame = TripleBufferedFrame(c.width, c.height, sizeof(uint8_t)*3); break;
default:
throw std::runtime_error("invalid frame format");
}
uvc_error_t startStreamResult = uvc_start_streaming(stream->uvcHandle, &stream->ctrl, &UVCCamera::cb, stream, 0);
if (startStreamResult < 0)
{
uvc_perror(startStreamResult, "start_stream");
throw std::runtime_error("Could not start stream");
}
}
}
void F200Camera::StopStream(int streamNum)
{
//@tofix
}
rs_intrinsics F200Camera::GetStreamIntrinsics(int stream)
{
const CameraCalibrationParameters & ivCamParams = hardware_io->GetParameters();
const OpticalData & ivOpticalData = hardware_io->GetOpticalData();
// undistorted for rgb
return {{640,480},{500,500},{320,240},{1,0,0,0,0}}; // TODO: Use actual calibration data
}
rs_extrinsics F200Camera::GetStreamExtrinsics(int from, int to)
{
return {{1,0,0,0,1,0,0,0,1},{0,0,0}};
}
float F200Camera::GetDepthScale()
{
IVCAMCalibrator<float> * calibration = Projection::GetInstance()->GetCalibrationObject();
return calibration->ivcamToMM(1) * 0.001f;
}
const uint16_t * F200Camera::GetDepthImage()
{
if (depthFrame.updated)
{
std::lock_guard<std::mutex> guard(frameMutex);
depthFrame.swap_front();
}
auto rectifiedDepthImage = rectifier->rectify(reinterpret_cast<uint16_t *>(depthFrame.front.data()));
return reinterpret_cast<const uint16_t *>(rectifiedDepthImage);
}
const uint8_t * F200Camera::GetColorImage()
{
if (colorFrame.updated)
{
std::lock_guard<std::mutex> guard(frameMutex);
colorFrame.swap_front();
}
return reinterpret_cast<const uint8_t *>(colorFrame.front.data());
}
} // end f200
#endif
<commit_msg>Getting closer to correct calibration data for IVCam<commit_after>#include "../Common.h"
#include "F200.h"
#include "Projection.h"
#ifndef WIN32
using namespace rs;
namespace f200
{
F200Camera::F200Camera(uvc_context_t * ctx, uvc_device_t * device, int idx) : UVCCamera(ctx, device, idx)
{
}
F200Camera::~F200Camera()
{
}
bool F200Camera::ConfigureStreams()
{
if (streamingModeBitfield == 0)
throw std::invalid_argument("No streams have been configured...");
if (streamingModeBitfield & RS_STREAM_DEPTH)
{
StreamInterface * stream = new StreamInterface();
stream->camera = this;
if (!OpenStreamOnSubdevice(hardware, stream->uvcHandle, 1))
throw std::runtime_error("Failed to open RS_STREAM_DEPTH (subdevice 1)");
// Debugging
uvc_print_stream_ctrl(&stream->ctrl, stdout);
streamInterfaces.insert(std::pair<int, StreamInterface *>(RS_STREAM_DEPTH, stream));
}
if (streamingModeBitfield & RS_STREAM_RGB)
{
StreamInterface * stream = new StreamInterface();
stream->camera = this;
if (!OpenStreamOnSubdevice(hardware, stream->uvcHandle, 0))
throw std::runtime_error("Failed to open RS_STREAM_RGB (subdevice 2)");
// Debugging
uvc_print_stream_ctrl(&stream->ctrl, stdout);
streamInterfaces.insert(std::pair<int, StreamInterface *>(RS_STREAM_RGB, stream));
}
GetUSBInfo(hardware, usbInfo);
std::cout << "Serial Number: " << usbInfo.serial << std::endl;
std::cout << "USB VID: " << usbInfo.vid << std::endl;
std::cout << "USB PID: " << usbInfo.pid << std::endl;
////////////////////////////////////////////////////////////////////////////
hardware_io.reset(new IVCAMHardwareIO(internalContext));
// Set up calibration parameters for internal undistortion
const CameraCalibrationParameters & calib = hardware_io->GetParameters();
const OpticalData & od = hardware_io->GetOpticalData();
rs_intrinsics rect = {}, unrect = {};
rs_extrinsics rotation = {{1.f,0.f,0.f,0.f,1.f,0.f,0.f,0.f,1.f},{0.f,0.f,0.f}};
const int ivWidth = 640;
const int ivHeight = 480;
rect.image_size[0] = ivWidth;
rect.image_size[1] = ivHeight;
rect.focal_length[0] = od.IRUndistortedFocalLengthPxl.x;
rect.focal_length[1] = od.IRUndistortedFocalLengthPxl.y;
rect.principal_point[0] = (ivWidth / 2); // Leo hack not to use real pp
rect.principal_point[1] = (ivHeight / 2); // Ditto
unrect.image_size[0] = ivWidth;
unrect.image_size[1] = ivHeight;
unrect.focal_length[0] = od.IRDistortedFocalLengthPxl.x;
unrect.focal_length[1] = od.IRDistortedFocalLengthPxl.x; // Leo hack for "Squareness"
unrect.principal_point[0] = od.IRPrincipalPoint.x + (ivWidth / 2);
unrect.principal_point[1] = od.IRPrincipalPoint.y + (ivHeight / 2);
unrect.distortion_coeff[0] = calib.Distc[0];
unrect.distortion_coeff[1] = calib.Distc[1];
unrect.distortion_coeff[2] = calib.Distc[2];
unrect.distortion_coeff[3] = calib.Distc[3];
unrect.distortion_coeff[4] = calib.Distc[4];
rectifier.reset(new IVRectifier(ivWidth, ivHeight, rect, unrect, rotation));
////////////////////////////////////////////////////////////////////////////
return true;
}
void F200Camera::StartStream(int streamIdentifier, const StreamConfiguration & c)
{
auto stream = streamInterfaces[streamIdentifier];
if (stream->uvcHandle)
{
stream->fmt = static_cast<uvc_frame_format>(c.format);
uvc_error_t status = uvc_get_stream_ctrl_format_size(stream->uvcHandle, &stream->ctrl, stream->fmt, c.width, c.height, c.fps);
if (status < 0)
{
uvc_perror(status, "uvc_get_stream_ctrl_format_size");
throw std::runtime_error("Open camera_handle Failed");
}
switch (c.format)
{
case FrameFormat::INVR:
case FrameFormat::INVZ:
depthFrame = TripleBufferedFrame(c.width, c.height, sizeof(uint16_t)); break;
case FrameFormat::YUYV:
colorFrame = TripleBufferedFrame(c.width, c.height, sizeof(uint8_t)*3); break;
default:
throw std::runtime_error("invalid frame format");
}
uvc_error_t startStreamResult = uvc_start_streaming(stream->uvcHandle, &stream->ctrl, &UVCCamera::cb, stream, 0);
if (startStreamResult < 0)
{
uvc_perror(startStreamResult, "start_stream");
throw std::runtime_error("Could not start stream");
}
}
}
void F200Camera::StopStream(int streamNum)
{
//@tofix
}
rs_intrinsics F200Camera::GetStreamIntrinsics(int stream)
{
const CameraCalibrationParameters & calib = hardware_io->GetParameters();
const OpticalData & od = hardware_io->GetOpticalData();
switch(stream)
{
case RS_STREAM_DEPTH: return {{640,480},{od.IRUndistortedFocalLengthPxl.x,od.IRUndistortedFocalLengthPxl.y},{320,240},{1,0,0,0,0}};
case RS_STREAM_RGB: return {{640,480},{od.RGBUndistortedFocalLengthPxl.x,od.RGBUndistortedFocalLengthPxl.y},{320,240},{1,0,0,0,0}};
default: throw std::runtime_error("unsupported stream");
}
}
rs_extrinsics F200Camera::GetStreamExtrinsics(int from, int to)
{
const CameraCalibrationParameters & calib = hardware_io->GetParameters();
float scale = 0.001f / GetDepthScale();
return {{calib.Rt[0][0], calib.Rt[0][1], calib.Rt[0][2],
calib.Rt[1][0], calib.Rt[1][1], calib.Rt[1][2],
calib.Rt[2][0], calib.Rt[2][1], calib.Rt[2][2]},
{calib.Tt[0] * scale, calib.Tt[1] * scale, calib.Tt[2] * scale}};
}
float F200Camera::GetDepthScale()
{
IVCAMCalibrator<float> * calibration = Projection::GetInstance()->GetCalibrationObject();
return calibration->ivcamToMM(1) * 0.001f;
}
const uint16_t * F200Camera::GetDepthImage()
{
if (depthFrame.updated)
{
std::lock_guard<std::mutex> guard(frameMutex);
depthFrame.swap_front();
}
auto rectifiedDepthImage = rectifier->rectify(reinterpret_cast<uint16_t *>(depthFrame.front.data()));
return reinterpret_cast<const uint16_t *>(rectifiedDepthImage);
}
const uint8_t * F200Camera::GetColorImage()
{
if (colorFrame.updated)
{
std::lock_guard<std::mutex> guard(frameMutex);
colorFrame.swap_front();
}
return reinterpret_cast<const uint8_t *>(colorFrame.front.data());
}
} // end f200
#endif
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Matrix
{
private:
int Columns;
int Strings;
int **matrix;
public:
Matrix();
Matrix(int _Columns, int _Strings);
Matrix(const Matrix& result);
~Matrix();
int Columns_() const;
int Strings_() const;
void search(string filename);
bool operator == (const Matrix& m2) const;
Matrix operator + (const Matrix& m2) const;
Matrix operator * (const Matrix& m2) const;
Matrix& operator = (const Matrix& result);
friend ostream& operator << (ostream& outfile, const Matrix& result);
friend istream& operator >> (istream& infile, const Matrix& result);
};
<commit_msg>Update matrix.hpp<commit_after>#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Matrix
{
private:
int Columns;
int Strings;
int **matrix;
public:
Matrix();
Matrix(int _Columns, int _Strings);
Matrix(const Matrix& result);
~Matrix();
int Columns_() const;
int Strings_() const;
void search(string filename);
bool operator == (const Matrix& a) const;
Matrix operator + (const Matrix& a) const;
Matrix operator * (const Matrix& a) const;
Matrix& operator = (const Matrix& res);
friend ostream& operator << (ostream& outfile, const Matrix& result);
friend istream& operator >> (istream& infile, const Matrix& result);
};
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <fstream>
using namespace std;
template<typename T>
struct Node
{
T x;
Node<T> * left;
Node<T> * right;
Node(T const& value) : x{ value }, left{ nullptr }, right{ nullptr } {}
};
template<typename T>
class Tree
{
private:
Node<T> * root;
public:
Tree()
{
root = nullptr;
}
~Tree()
{
deleteNode(root);
}
void deleteNode(Node<T> * node)
{
if (node == nullptr) return;
deleteNode(node->left);
deleteNode(node->right);
delete node;
}
T x_() const
{
return root->x;
}
Node<T> * left_() const
{
return root->left;
}
Node<T> * right_() const
{
return root->right;
}
Node<T> * root_() const
{
return root;
}
void insert(const T& value)
{
insert(root, value);
}
void insert(Node<T>* & node, const T& value)
{
if (node) {
if (value < node->x) {
insert(node->left, value);
}
else if (value > node->x) {
insert(node->right, value);
}
else {
return;
}
}
else {
node = new Node<T>(value);
}
}
Node<T> * search(const T& x)const
{
Node<T> * curEl = root;
while (curEl != nullptr)
{
if (curEl->x == x)
break;
else
{
if (x > curEl->x)
curEl = curEl->right;
else curEl = curEl->left;
}
}
return curEl;
}
void fIn(const string filename)
{
ifstream fin;
unsigned int k;
fin.open(filename);
if (!fin.is_open())
cout << "The file isn't find" << endl;
else
{
deleteNode(root);
if (fin.eof()) return;
else
{
fin >> k;
T newEl;
for (unsigned int i = 0; i < k; ++i)
{
fin >> newEl;
insert(newEl);
}
}
fin.close();
}
}
unsigned int size(Node<T> * node)const
{
unsigned int size_ = 0;
if (node != nullptr)
size_ = size(node->left) + 1 + size(node->right);
return size_;
}
void out_to_file(const string filename)const
{
ofstream fout;
fout.open(filename);
if (!fout.is_open())
cout << "The file isn't find" << endl;
else
{
unsigned int size_ = size(root);
if (size_ == 0)
return;
fout << size_ << "\t";
fOut(root, fout);
fout.close();
}
}
void fOut(Node<T> * node, ostream&stream)const
{
if (node != nullptr)
{
fOut(node->left, stream);
stream << node->x << " ";
fOut(node->right, stream);
}
}
void out(ostream & stream)const
{
Out(root, stream, 0);
}
void Out(Node<T> * node, ostream&stream, size_t level)const
{
Node<T> * curEl = node;
if (curEl != nullptr)
{
Out(curEl->right, stream, level + 1);
for (unsigned int i = 0; i < level; ++i)
stream << '-';
stream << curEl->x << endl;
Out(curEl->left, stream, level + 1);
}
}
};
<commit_msg>Update BinaryTree.hpp<commit_after>#include <iostream>
#include <string>
#include <fstream>
using namespace std;
template<typename T>
struct Node
{
T x;
Node<T> * left;
Node<T> * right;
Node(T const& value) : x{ value }, left{ nullptr }, right{ nullptr } {}
};
template<typename T>
class Tree
{
private:
Node<T> * root;
public:
Tree()
{
root = nullptr;
}
~Tree()
{
deleteNode(root);
}
void deleteNode(Node<T> * node)
{
if (node == nullptr) return;
deleteNode(node->left);
deleteNode(node->right);
delete node;
}
T x_() const
{
return root->x;
}
T left_() const
{
return root->left->x;
}
T right_() const
{
return root->right->;
}
Node<T> * root_() const
{
return root;
}
void insert(const T& value)
{
insert(root, value);
}
void insert(Node<T>* & node, const T& value)
{
if (node) {
if (value < node->x) {
insert(node->left, value);
}
else if (value > node->x) {
insert(node->right, value);
}
else {
return;
}
}
else {
node = new Node<T>(value);
}
}
Node<T> * search(const T& x)const
{
Node<T> * curEl = root;
while (curEl != nullptr)
{
if (curEl->x == x)
break;
else
{
if (x > curEl->x)
curEl = curEl->right;
else curEl = curEl->left;
}
}
return curEl;
}
void fIn(const string filename)
{
ifstream fin;
unsigned int k;
fin.open(filename);
if (!fin.is_open())
cout << "The file isn't find" << endl;
else
{
deleteNode(root);
if (fin.eof()) return;
else
{
fin >> k;
T newEl;
for (unsigned int i = 0; i < k; ++i)
{
fin >> newEl;
insert(newEl);
}
}
fin.close();
}
}
unsigned int size(Node<T> * node)const
{
unsigned int size_ = 0;
if (node != nullptr)
size_ = size(node->left) + 1 + size(node->right);
return size_;
}
void out_to_file(const string filename)const
{
ofstream fout;
fout.open(filename);
if (!fout.is_open())
cout << "The file isn't find" << endl;
else
{
unsigned int size_ = size(root);
if (size_ == 0)
return;
fout << size_ << "\t";
fOut(root, fout);
fout.close();
}
}
void fOut(Node<T> * node, ostream&stream)const
{
if (node != nullptr)
{
fOut(node->left, stream);
stream << node->x << " ";
fOut(node->right, stream);
}
}
void out(ostream & stream)const
{
Out(root, stream, 0);
}
void Out(Node<T> * node, ostream&stream, size_t level)const
{
Node<T> * curEl = node;
if (curEl != nullptr)
{
Out(curEl->right, stream, level + 1);
for (unsigned int i = 0; i < level; ++i)
stream << '-';
stream << curEl->x << endl;
Out(curEl->left, stream, level + 1);
}
}
};
<|endoftext|> |
<commit_before>#pragma once
/**
@file
@brief definition of Op
@author MITSUNARI Shigeo(@herumi)
@license modified new BSD license
http://opensource.org/licenses/BSD-3-Clause
*/
#include <mcl/gmp_util.hpp>
#include <memory.h>
#include <mcl/array.hpp>
#if defined(__EMSCRIPTEN__) || defined(__wasm__)
#define MCL_DONT_USE_XBYAK
#define MCL_DONT_USE_OPENSSL
#endif
#if !defined(MCL_DONT_USE_XBYAK) && (defined(_WIN64) || defined(__x86_64__)) && (MCL_SIZEOF_UNIT == 8) && !defined(MCL_STATIC_CODE)
#define MCL_USE_XBYAK
#endif
#if defined(MCL_USE_XBYAK) || defined(MCL_STATIC_CODE)
#define MCL_X64_ASM
#define MCL_XBYAK_DIRECT_CALL
#endif
#define MCL_MAX_HASH_BIT_SIZE 512
namespace mcl {
static const int version = 0x126; /* 0xABC = A.BC */
/*
specifies available string format mode for X::setIoMode()
// for Fp, Fp2, Fp6, Fp12
default(0) : IoDec
printable string(zero terminated, variable size)
IoBin(2) | IoDec(10) | IoHex(16) | IoBinPrefix | IoHexPrefix
byte string(not zero terminated, fixed size)
IoArray | IoArrayRaw
IoArray = IoSerialize
// for Ec
affine(0) | IoEcCompY | IoComp
default : affine
affine and IoEcCompY are available with ioMode for Fp
IoSerialize ignores ioMode for Fp
IoAuto
dec or hex according to ios_base::fmtflags
IoBin
binary number([01]+)
IoDec
decimal number
IoHex
hexadecimal number([0-9a-fA-F]+)
IoBinPrefix
0b + <binary number>
IoHexPrefix
0x + <hexadecimal number>
IoArray
array of Unit(fixed size = Fp::getByteSize())
IoArrayRaw
array of Unit(fixed size = Fp::getByteSize()) without Montgomery conversion
// for Ec::setIoMode()
IoEcAffine(default)
"0" ; infinity
"1 <x> <y>" ; affine coordinate
IoEcProj
"4" <x> <y> <z> ; projective or jacobi coordinate
IoEcCompY
1-bit y prepresentation of elliptic curve
"2 <x>" ; compressed for even y
"3 <x>" ; compressed for odd y
IoSerialize
if isMSBserialize(): // p is not full bit
size = Fp::getByteSize()
use MSB of array of x for 1-bit y for prime p where (p % 8 != 0)
[0] ; infinity
<x> ; for even y
<x>|1 ; for odd y ; |1 means set MSB of x
else:
size = Fp::getByteSize() + 1
[0] ; infinity
2 <x> ; for even y
3 <x> ; for odd y
*/
enum IoMode {
IoAuto = 0, // dec or hex according to ios_base::fmtflags
IoBin = 2, // binary number without prefix
IoDec = 10, // decimal number without prefix
IoHex = 16, // hexadecimal number without prefix
IoArray = 32, // array of Unit(fixed size)
IoArrayRaw = 64, // raw array of Unit without Montgomery conversion
IoPrefix = 128, // append '0b'(bin) or '0x'(hex)
IoBinPrefix = IoBin | IoPrefix,
IoHexPrefix = IoHex | IoPrefix,
IoEcAffine = 0, // affine coordinate
IoEcCompY = 256, // 1-bit y representation of elliptic curve
IoSerialize = 512, // use MBS for 1-bit y
IoFixedSizeByteSeq = IoSerialize, // obsolete
IoEcProj = 1024, // projective or jacobi coordinate
IoSerializeHexStr = 2048, // printable hex string
IoEcAffineSerialize = 4096 // serialize [x:y]
};
namespace fp {
inline bool isIoSerializeMode(int ioMode)
{
return ioMode & (IoArray | IoArrayRaw | IoSerialize | IoEcAffineSerialize | IoSerializeHexStr);
}
const size_t UnitBitSize = sizeof(Unit) * 8;
const size_t maxUnitSize = (MCL_MAX_BIT_SIZE + UnitBitSize - 1) / UnitBitSize;
#define MCL_MAX_UNIT_SIZE ((MCL_MAX_BIT_SIZE + MCL_UNIT_BIT_SIZE - 1) / MCL_UNIT_BIT_SIZE)
const size_t maxMulVecN = 32; // inner loop of mulVec
#ifndef MCL_MAX_MUL_VEC_NGLV
#define MCL_MAX_MUL_VEC_NGLV 16
#endif
const size_t maxMulVecNGLV = MCL_MAX_MUL_VEC_NGLV; // inner loop of mulVec with GLV
struct FpGenerator;
struct Op;
typedef void (*void1u)(Unit*);
typedef void (*void2u)(Unit*, const Unit*);
typedef void (*void2uI)(Unit*, const Unit*, Unit);
typedef void (*void2uIu)(Unit*, const Unit*, Unit, const Unit*);
typedef void (*void2uOp)(Unit*, const Unit*, const Op&);
typedef void (*void3u)(Unit*, const Unit*, const Unit*);
typedef void (*void4u)(Unit*, const Unit*, const Unit*, const Unit*);
typedef int (*int2u)(Unit*, const Unit*);
typedef Unit (*u1uII)(Unit*, Unit, Unit);
typedef Unit (*u3u)(Unit*, const Unit*, const Unit*);
/*
disable -Wcast-function-type
the number of arguments of some JIT functions is smaller than that of T
*/
template<class T, class S>
T func_ptr_cast(S func)
{
return reinterpret_cast<T>(reinterpret_cast<void*>(func));
}
struct Block {
const Unit *p; // pointer to original FpT.v_
size_t n;
Unit v_[maxUnitSize];
};
enum Mode {
FP_AUTO,
FP_GMP,
FP_GMP_MONT,
FP_LLVM,
FP_LLVM_MONT,
FP_XBYAK
};
enum PrimeMode {
PM_GENERIC = 0,
PM_NIST_P192,
PM_SECP256K1,
PM_NIST_P521
};
enum MaskMode {
NoMask = 0, // throw if greater or equal
SmallMask = 1, // 1-bit smaller mask if greater or equal
MaskAndMod = 2, // mask and substract if greater or equal
Mod = 3 // mod p
};
struct Op {
/*
don't change the layout of rp and p
asm code assumes &rp + 1 == p
*/
Unit rp;
Unit p[maxUnitSize];
mpz_class mp;
uint32_t pmod4;
mcl::SquareRoot sq;
mcl::Modp modp;
Unit half[maxUnitSize]; // (p + 1) / 2
Unit oneRep[maxUnitSize]; // 1(=inv R if Montgomery)
/*
for Montgomery
one = 1
R = (1 << (N * sizeof(Unit) * 8)) % p
R2 = (R * R) % p
R3 = RR^3
*/
Unit one[maxUnitSize];
Unit R2[maxUnitSize];
Unit R3[maxUnitSize];
#ifdef MCL_USE_XBYAK
FpGenerator *fg;
#endif
#ifdef MCL_X64_ASM
mcl::Array<Unit> invTbl;
#endif
void3u fp_addA_;
void3u fp_subA_;
void2u fp_negA_;
void3u fp_mulA_;
void2u fp_sqrA_;
void3u fp2_addA_;
void3u fp2_subA_;
void2u fp2_negA_;
void3u fp2_mulA_;
void2u fp2_sqrA_;
void3u fpDbl_addA_;
void3u fpDbl_subA_;
void3u fpDbl_mulPreA_;
void2u fpDbl_sqrPreA_;
void2u fpDbl_modA_;
void3u fp2Dbl_mulPreA_;
void2u fp2Dbl_sqrPreA_;
size_t maxN;
size_t N;
size_t bitSize;
bool (*fp_isZero)(const Unit*);
void1u fp_clear;
void2u fp_copy;
void2u fp_shr1;
void3u fp_neg;
void4u fp_add;
void4u fp_sub;
void4u fp_mul;
void3u fp_sqr;
void2uOp fp_invOp;
void2uIu fp_mulUnit; // fpN1_mod + fp_mulUnitPre
void3u fpDbl_mulPre;
void2u fpDbl_sqrPre;
int2u fp_preInv;
void2uI fp_mulUnitPre; // z[N + 1] = x[N] * y
void3u fpN1_mod; // y[N] = x[N + 1] % p[N]
void4u fpDbl_add;
void4u fpDbl_sub;
void3u fpDbl_mod;
u3u fp_addPre; // without modulo p
u3u fp_subPre; // without modulo p
u3u fpDbl_addPre;
u3u fpDbl_subPre;
/*
for Fp2 = F[u] / (u^2 + 1)
x = a + bu
*/
int xi_a; // xi = xi_a + u
void4u fp2_mulNF;
void2u fp2_inv;
void2u fp2_mul_xiA_;
uint32_t (*hash)(void *out, uint32_t maxOutSize, const void *msg, uint32_t msgSize);
PrimeMode primeMode;
bool isFullBit; // true if bitSize % uniSize == 0
bool isMont; // true if use Montgomery
bool isFastMod; // true if modulo is fast
Op()
{
clear();
}
~Op()
{
#ifdef MCL_USE_XBYAK
destroyFpGenerator(fg);
#endif
}
void clear()
{
rp = 0;
memset(p, 0, sizeof(p));
mp = 0;
pmod4 = 0;
sq.clear();
// fg is not set
memset(half, 0, sizeof(half));
memset(oneRep, 0, sizeof(oneRep));
memset(one, 0, sizeof(one));
memset(R2, 0, sizeof(R2));
memset(R3, 0, sizeof(R3));
#ifdef MCL_X64_ASM
invTbl.clear();
#endif
fp_addA_ = 0;
fp_subA_ = 0;
fp_negA_ = 0;
fp_mulA_ = 0;
fp_sqrA_ = 0;
fp2_addA_ = 0;
fp2_subA_ = 0;
fp2_negA_ = 0;
fp2_mulA_ = 0;
fp2_sqrA_ = 0;
fpDbl_addA_ = 0;
fpDbl_subA_ = 0;
fpDbl_mulPreA_ = 0;
fpDbl_sqrPreA_ = 0;
fpDbl_modA_ = 0;
fp2Dbl_mulPreA_ = 0;
fp2Dbl_sqrPreA_ = 0;
maxN = 0;
N = 0;
bitSize = 0;
fp_isZero = 0;
fp_clear = 0;
fp_copy = 0;
fp_shr1 = 0;
fp_neg = 0;
fp_add = 0;
fp_sub = 0;
fp_mul = 0;
fp_sqr = 0;
fp_invOp = 0;
fp_mulUnit = 0;
fpDbl_mulPre = 0;
fpDbl_sqrPre = 0;
fp_preInv = 0;
fp_mulUnitPre = 0;
fpN1_mod = 0;
fpDbl_add = 0;
fpDbl_sub = 0;
fpDbl_mod = 0;
fp_addPre = 0;
fp_subPre = 0;
fpDbl_addPre = 0;
fpDbl_subPre = 0;
xi_a = 0;
fp2_mulNF = 0;
fp2_inv = 0;
fp2_mul_xiA_ = 0;
hash = 0;
primeMode = PM_GENERIC;
isFullBit = false;
isMont = false;
isFastMod = false;
}
void fromMont(Unit* y, const Unit *x) const
{
/*
M(x, y) = xyR^-1
y = M(x, 1) = xR^-1
*/
fp_mul(y, x, one, p);
}
void toMont(Unit* y, const Unit *x) const
{
/*
y = M(x, R2) = xR^2 R^-1 = xR
*/
fp_mul(y, x, R2, p);
}
bool init(const mpz_class& p, size_t maxBitSize, int xi_a, Mode mode, size_t mclMaxBitSize = MCL_MAX_BIT_SIZE);
#ifdef MCL_USE_XBYAK
static FpGenerator* createFpGenerator();
static void destroyFpGenerator(FpGenerator *fg);
#endif
private:
Op(const Op&);
void operator=(const Op&);
};
inline const char* getIoSeparator(int ioMode)
{
return (ioMode & (IoArray | IoArrayRaw | IoSerialize | IoSerializeHexStr | IoEcAffineSerialize)) ? "" : " ";
}
inline void dump(const void *buf, size_t n)
{
const uint8_t *s = (const uint8_t *)buf;
for (size_t i = 0; i < n; i++) {
printf("%02x ", s[i]);
}
printf("\n");
}
#ifndef CYBOZU_DONT_USE_STRING
int detectIoMode(int ioMode, const std::ios_base& ios);
inline void dump(const std::string& s)
{
dump(s.c_str(), s.size());
}
#endif
} } // mcl::fp
<commit_msg>v1.27<commit_after>#pragma once
/**
@file
@brief definition of Op
@author MITSUNARI Shigeo(@herumi)
@license modified new BSD license
http://opensource.org/licenses/BSD-3-Clause
*/
#include <mcl/gmp_util.hpp>
#include <memory.h>
#include <mcl/array.hpp>
#if defined(__EMSCRIPTEN__) || defined(__wasm__)
#define MCL_DONT_USE_XBYAK
#define MCL_DONT_USE_OPENSSL
#endif
#if !defined(MCL_DONT_USE_XBYAK) && (defined(_WIN64) || defined(__x86_64__)) && (MCL_SIZEOF_UNIT == 8) && !defined(MCL_STATIC_CODE)
#define MCL_USE_XBYAK
#endif
#if defined(MCL_USE_XBYAK) || defined(MCL_STATIC_CODE)
#define MCL_X64_ASM
#define MCL_XBYAK_DIRECT_CALL
#endif
#define MCL_MAX_HASH_BIT_SIZE 512
namespace mcl {
static const int version = 0x127; /* 0xABC = A.BC */
/*
specifies available string format mode for X::setIoMode()
// for Fp, Fp2, Fp6, Fp12
default(0) : IoDec
printable string(zero terminated, variable size)
IoBin(2) | IoDec(10) | IoHex(16) | IoBinPrefix | IoHexPrefix
byte string(not zero terminated, fixed size)
IoArray | IoArrayRaw
IoArray = IoSerialize
// for Ec
affine(0) | IoEcCompY | IoComp
default : affine
affine and IoEcCompY are available with ioMode for Fp
IoSerialize ignores ioMode for Fp
IoAuto
dec or hex according to ios_base::fmtflags
IoBin
binary number([01]+)
IoDec
decimal number
IoHex
hexadecimal number([0-9a-fA-F]+)
IoBinPrefix
0b + <binary number>
IoHexPrefix
0x + <hexadecimal number>
IoArray
array of Unit(fixed size = Fp::getByteSize())
IoArrayRaw
array of Unit(fixed size = Fp::getByteSize()) without Montgomery conversion
// for Ec::setIoMode()
IoEcAffine(default)
"0" ; infinity
"1 <x> <y>" ; affine coordinate
IoEcProj
"4" <x> <y> <z> ; projective or jacobi coordinate
IoEcCompY
1-bit y prepresentation of elliptic curve
"2 <x>" ; compressed for even y
"3 <x>" ; compressed for odd y
IoSerialize
if isMSBserialize(): // p is not full bit
size = Fp::getByteSize()
use MSB of array of x for 1-bit y for prime p where (p % 8 != 0)
[0] ; infinity
<x> ; for even y
<x>|1 ; for odd y ; |1 means set MSB of x
else:
size = Fp::getByteSize() + 1
[0] ; infinity
2 <x> ; for even y
3 <x> ; for odd y
*/
enum IoMode {
IoAuto = 0, // dec or hex according to ios_base::fmtflags
IoBin = 2, // binary number without prefix
IoDec = 10, // decimal number without prefix
IoHex = 16, // hexadecimal number without prefix
IoArray = 32, // array of Unit(fixed size)
IoArrayRaw = 64, // raw array of Unit without Montgomery conversion
IoPrefix = 128, // append '0b'(bin) or '0x'(hex)
IoBinPrefix = IoBin | IoPrefix,
IoHexPrefix = IoHex | IoPrefix,
IoEcAffine = 0, // affine coordinate
IoEcCompY = 256, // 1-bit y representation of elliptic curve
IoSerialize = 512, // use MBS for 1-bit y
IoFixedSizeByteSeq = IoSerialize, // obsolete
IoEcProj = 1024, // projective or jacobi coordinate
IoSerializeHexStr = 2048, // printable hex string
IoEcAffineSerialize = 4096 // serialize [x:y]
};
namespace fp {
inline bool isIoSerializeMode(int ioMode)
{
return ioMode & (IoArray | IoArrayRaw | IoSerialize | IoEcAffineSerialize | IoSerializeHexStr);
}
const size_t UnitBitSize = sizeof(Unit) * 8;
const size_t maxUnitSize = (MCL_MAX_BIT_SIZE + UnitBitSize - 1) / UnitBitSize;
#define MCL_MAX_UNIT_SIZE ((MCL_MAX_BIT_SIZE + MCL_UNIT_BIT_SIZE - 1) / MCL_UNIT_BIT_SIZE)
const size_t maxMulVecN = 32; // inner loop of mulVec
#ifndef MCL_MAX_MUL_VEC_NGLV
#define MCL_MAX_MUL_VEC_NGLV 16
#endif
const size_t maxMulVecNGLV = MCL_MAX_MUL_VEC_NGLV; // inner loop of mulVec with GLV
struct FpGenerator;
struct Op;
typedef void (*void1u)(Unit*);
typedef void (*void2u)(Unit*, const Unit*);
typedef void (*void2uI)(Unit*, const Unit*, Unit);
typedef void (*void2uIu)(Unit*, const Unit*, Unit, const Unit*);
typedef void (*void2uOp)(Unit*, const Unit*, const Op&);
typedef void (*void3u)(Unit*, const Unit*, const Unit*);
typedef void (*void4u)(Unit*, const Unit*, const Unit*, const Unit*);
typedef int (*int2u)(Unit*, const Unit*);
typedef Unit (*u1uII)(Unit*, Unit, Unit);
typedef Unit (*u3u)(Unit*, const Unit*, const Unit*);
/*
disable -Wcast-function-type
the number of arguments of some JIT functions is smaller than that of T
*/
template<class T, class S>
T func_ptr_cast(S func)
{
return reinterpret_cast<T>(reinterpret_cast<void*>(func));
}
struct Block {
const Unit *p; // pointer to original FpT.v_
size_t n;
Unit v_[maxUnitSize];
};
enum Mode {
FP_AUTO,
FP_GMP,
FP_GMP_MONT,
FP_LLVM,
FP_LLVM_MONT,
FP_XBYAK
};
enum PrimeMode {
PM_GENERIC = 0,
PM_NIST_P192,
PM_SECP256K1,
PM_NIST_P521
};
enum MaskMode {
NoMask = 0, // throw if greater or equal
SmallMask = 1, // 1-bit smaller mask if greater or equal
MaskAndMod = 2, // mask and substract if greater or equal
Mod = 3 // mod p
};
struct Op {
/*
don't change the layout of rp and p
asm code assumes &rp + 1 == p
*/
Unit rp;
Unit p[maxUnitSize];
mpz_class mp;
uint32_t pmod4;
mcl::SquareRoot sq;
mcl::Modp modp;
Unit half[maxUnitSize]; // (p + 1) / 2
Unit oneRep[maxUnitSize]; // 1(=inv R if Montgomery)
/*
for Montgomery
one = 1
R = (1 << (N * sizeof(Unit) * 8)) % p
R2 = (R * R) % p
R3 = RR^3
*/
Unit one[maxUnitSize];
Unit R2[maxUnitSize];
Unit R3[maxUnitSize];
#ifdef MCL_USE_XBYAK
FpGenerator *fg;
#endif
#ifdef MCL_X64_ASM
mcl::Array<Unit> invTbl;
#endif
void3u fp_addA_;
void3u fp_subA_;
void2u fp_negA_;
void3u fp_mulA_;
void2u fp_sqrA_;
void3u fp2_addA_;
void3u fp2_subA_;
void2u fp2_negA_;
void3u fp2_mulA_;
void2u fp2_sqrA_;
void3u fpDbl_addA_;
void3u fpDbl_subA_;
void3u fpDbl_mulPreA_;
void2u fpDbl_sqrPreA_;
void2u fpDbl_modA_;
void3u fp2Dbl_mulPreA_;
void2u fp2Dbl_sqrPreA_;
size_t maxN;
size_t N;
size_t bitSize;
bool (*fp_isZero)(const Unit*);
void1u fp_clear;
void2u fp_copy;
void2u fp_shr1;
void3u fp_neg;
void4u fp_add;
void4u fp_sub;
void4u fp_mul;
void3u fp_sqr;
void2uOp fp_invOp;
void2uIu fp_mulUnit; // fpN1_mod + fp_mulUnitPre
void3u fpDbl_mulPre;
void2u fpDbl_sqrPre;
int2u fp_preInv;
void2uI fp_mulUnitPre; // z[N + 1] = x[N] * y
void3u fpN1_mod; // y[N] = x[N + 1] % p[N]
void4u fpDbl_add;
void4u fpDbl_sub;
void3u fpDbl_mod;
u3u fp_addPre; // without modulo p
u3u fp_subPre; // without modulo p
u3u fpDbl_addPre;
u3u fpDbl_subPre;
/*
for Fp2 = F[u] / (u^2 + 1)
x = a + bu
*/
int xi_a; // xi = xi_a + u
void4u fp2_mulNF;
void2u fp2_inv;
void2u fp2_mul_xiA_;
uint32_t (*hash)(void *out, uint32_t maxOutSize, const void *msg, uint32_t msgSize);
PrimeMode primeMode;
bool isFullBit; // true if bitSize % uniSize == 0
bool isMont; // true if use Montgomery
bool isFastMod; // true if modulo is fast
Op()
{
clear();
}
~Op()
{
#ifdef MCL_USE_XBYAK
destroyFpGenerator(fg);
#endif
}
void clear()
{
rp = 0;
memset(p, 0, sizeof(p));
mp = 0;
pmod4 = 0;
sq.clear();
// fg is not set
memset(half, 0, sizeof(half));
memset(oneRep, 0, sizeof(oneRep));
memset(one, 0, sizeof(one));
memset(R2, 0, sizeof(R2));
memset(R3, 0, sizeof(R3));
#ifdef MCL_X64_ASM
invTbl.clear();
#endif
fp_addA_ = 0;
fp_subA_ = 0;
fp_negA_ = 0;
fp_mulA_ = 0;
fp_sqrA_ = 0;
fp2_addA_ = 0;
fp2_subA_ = 0;
fp2_negA_ = 0;
fp2_mulA_ = 0;
fp2_sqrA_ = 0;
fpDbl_addA_ = 0;
fpDbl_subA_ = 0;
fpDbl_mulPreA_ = 0;
fpDbl_sqrPreA_ = 0;
fpDbl_modA_ = 0;
fp2Dbl_mulPreA_ = 0;
fp2Dbl_sqrPreA_ = 0;
maxN = 0;
N = 0;
bitSize = 0;
fp_isZero = 0;
fp_clear = 0;
fp_copy = 0;
fp_shr1 = 0;
fp_neg = 0;
fp_add = 0;
fp_sub = 0;
fp_mul = 0;
fp_sqr = 0;
fp_invOp = 0;
fp_mulUnit = 0;
fpDbl_mulPre = 0;
fpDbl_sqrPre = 0;
fp_preInv = 0;
fp_mulUnitPre = 0;
fpN1_mod = 0;
fpDbl_add = 0;
fpDbl_sub = 0;
fpDbl_mod = 0;
fp_addPre = 0;
fp_subPre = 0;
fpDbl_addPre = 0;
fpDbl_subPre = 0;
xi_a = 0;
fp2_mulNF = 0;
fp2_inv = 0;
fp2_mul_xiA_ = 0;
hash = 0;
primeMode = PM_GENERIC;
isFullBit = false;
isMont = false;
isFastMod = false;
}
void fromMont(Unit* y, const Unit *x) const
{
/*
M(x, y) = xyR^-1
y = M(x, 1) = xR^-1
*/
fp_mul(y, x, one, p);
}
void toMont(Unit* y, const Unit *x) const
{
/*
y = M(x, R2) = xR^2 R^-1 = xR
*/
fp_mul(y, x, R2, p);
}
bool init(const mpz_class& p, size_t maxBitSize, int xi_a, Mode mode, size_t mclMaxBitSize = MCL_MAX_BIT_SIZE);
#ifdef MCL_USE_XBYAK
static FpGenerator* createFpGenerator();
static void destroyFpGenerator(FpGenerator *fg);
#endif
private:
Op(const Op&);
void operator=(const Op&);
};
inline const char* getIoSeparator(int ioMode)
{
return (ioMode & (IoArray | IoArrayRaw | IoSerialize | IoSerializeHexStr | IoEcAffineSerialize)) ? "" : " ";
}
inline void dump(const void *buf, size_t n)
{
const uint8_t *s = (const uint8_t *)buf;
for (size_t i = 0; i < n; i++) {
printf("%02x ", s[i]);
}
printf("\n");
}
#ifndef CYBOZU_DONT_USE_STRING
int detectIoMode(int ioMode, const std::ios_base& ios);
inline void dump(const std::string& s)
{
dump(s.c_str(), s.size());
}
#endif
} } // mcl::fp
<|endoftext|> |
<commit_before><?hh //strict
/**
* This file is part of hhpack\file package.
*
* (c) Noritaka Horio <holy.shared.design@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace hhpack\file;
use \Generator;
final class FileReader
{
private File $file;
private FileStream $stream;
public function __construct(File $file)
{
// echo 'DDDDDDDDDDDDDD';
// var_dump($file->exists());
// echo 'DDDDDDDDDDDDDD';
// if ($file->exists() === false) {
// throw new FileNotFoundException("File {$file->getPath()} can not be found");
// }
$this->file = $file;
$this->stream = FileStream::fromFile($file);
}
public static function fromString(string $filePath) : FileReader
{
return new self(new File($filePath));
}
public static function fromFile(File $file) : FileReader
{
return new self($file);
}
public function readBytes(int $length) : Generator<int, ReadedChunk, void>
{
return $this->stream->readBytes($length);
}
public function readRecords() : Generator<int, ReadedRecord, void>
{
return $this->stream->readRecords();
}
public function totalSize() : int
{
return $this->stream->totalSize();
}
public function readedSize() : int
{
return $this->stream->readedSize();
}
public function close() : void
{
$this->stream->close();
}
}
<commit_msg>Remove property<commit_after><?hh //strict
/**
* This file is part of hhpack\file package.
*
* (c) Noritaka Horio <holy.shared.design@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace hhpack\file;
use \Generator;
final class FileReader
{
private FileStream $stream;
public function __construct(File $file)
{
$this->stream = FileStream::fromFile($file);
}
public static function fromString(string $filePath) : FileReader
{
return new self(new File($filePath));
}
public static function fromFile(File $file) : FileReader
{
return new self($file);
}
public function readBytes(int $length) : Generator<int, ReadedChunk, void>
{
return $this->stream->readBytes($length);
}
public function readRecords() : Generator<int, ReadedRecord, void>
{
return $this->stream->readRecords();
}
public function totalSize() : int
{
return $this->stream->totalSize();
}
public function readedSize() : int
{
return $this->stream->readedSize();
}
public function close() : void
{
$this->stream->close();
}
}
<|endoftext|> |
<commit_before>/*
Title: Multi-Threaded Garbage Collector - Check for weak references
Copyright (c) 2010, 2012 David C. J. Matthews
Based on the original garbage collector code
Copyright 2000-2008
Cambridge University Technical Services Limited
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
*/
/*
This is an intermediate phase in the GC that checks for weak references
that are no longer reachable. It is performed after the first, mark, phase.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#elif defined(_WIN32)
#include "winconfig.h"
#else
#error "No configuration file"
#endif
#ifdef HAVE_ASSERT_H
#include <assert.h>
#define ASSERT(x) assert(x)
#else
#define ASSERT(x)
#endif
#include "globals.h"
#include "gc.h"
#include "scanaddrs.h"
#include "rts_module.h"
#include "memmgr.h"
class MTGCCheckWeakRef: public ScanAddress {
public:
void ScanAreas(void);
private:
virtual void ScanRuntimeAddress(PolyObject **pt, RtsStrength weak);
// This has to be defined since it's virtual.
virtual PolyObject *ScanObjectAddress(PolyObject *base) { return base; }
virtual void ScanAddressesInObject(PolyObject *obj, POLYUNSIGNED lengthWord);
};
// This deals with weak references within the run-time system.
void MTGCCheckWeakRef::ScanRuntimeAddress(PolyObject **pt, RtsStrength weak)
{
/* If the object has not been marked and this is only a weak reference */
/* then the pointer is set to zero. This allows streams or windows */
/* to be closed if there is no other reference to them. */
PolyObject *val = *pt;
PolyWord w = val;
if (weak == STRENGTH_STRONG)
return;
LocalMemSpace *space = gMem.LocalSpaceForAddress(w.AsStackAddr());
if (space == 0)
return; // Not in local area
// If it hasn't been marked set it to zero.
if (! space->bitmap.TestBit(space->wordNo(w.AsStackAddr())))
*pt = 0;
}
// Deal with weak objects
void MTGCCheckWeakRef::ScanAddressesInObject(PolyObject *obj, POLYUNSIGNED L)
{
if (! OBJ_IS_WEAKREF_OBJECT(L)) return;
ASSERT(OBJ_IS_MUTABLE_OBJECT(L)); // Should be a mutable.
ASSERT(OBJ_IS_WORD_OBJECT(L)); // Should be a plain object.
// See if any of the SOME objects contain unreferenced refs.
POLYUNSIGNED length = OBJ_OBJECT_LENGTH(L);
PolyWord *baseAddr = (PolyWord*)obj;
for (POLYUNSIGNED i = 0; i < length; i++)
{
PolyWord someAddr = baseAddr[i];
if (someAddr.IsDataPtr())
{
LocalMemSpace *someSpace = gMem.LocalSpaceForAddress(someAddr.AsAddress());
if (someSpace != 0)
{
PolyObject *someObj = someAddr.AsObjPtr();
// If this is a weak object the SOME value may refer to an unreferenced
// ref. If so we have to set this entry to NONE. For safety we also
// set the contents of the SOME to TAGGED(0).
ASSERT(someObj->Length() == 1 && someObj->IsWordObject()); // Should be a SOME node.
PolyWord refAddress = someObj->Get(0);
LocalMemSpace *space = gMem.LocalSpaceForAddress(refAddress.AsAddress());
if (space != 0)
// If the ref is permanent it's always there.
{
POLYUNSIGNED new_bitno = space->wordNo(refAddress.AsStackAddr());
if (! space->bitmap.TestBit(new_bitno))
{
// It wasn't marked so it's otherwise unreferenced.
baseAddr[i] = TAGGED(0); // Set it to NONE.
someObj->Set(0, TAGGED(0)); // For safety.
convertedWeak = true;
}
}
}
}
}
}
// We need to check any weak references both in the areas we are
// currently collecting and any other areas. This actually checks
// weak refs in the area we're collecting even if they are not
// actually reachable any more. N.B. This differs from OpMutables
// because it also scans the area we're collecting.
void MTGCCheckWeakRef::ScanAreas(void)
{
for (unsigned i = 0; i < gMem.nlSpaces; i++)
{
LocalMemSpace *space = gMem.lSpaces[i];
if (space->isMutable)
ScanAddressesInRegion(space->lowestWeak, space->highestWeak);
}
// Scan the permanent mutable areas.
for (unsigned j = 0; j < gMem.npSpaces; j++)
{
MemSpace *space = gMem.pSpaces[j];
if (space->isMutable)
ScanAddressesInRegion(space->lowestWeak, space->highestWeak);
}
}
void GCheckWeakRefs()
{
MTGCCheckWeakRef checkRef;
GCModules(&checkRef);
checkRef.ScanAreas();
}
<commit_msg>Fix bug with Weak.weakArray If the same SOME cell was referenced in two different places within weak refs or a weak array the second reference was not removed when the "token" ref was unreachable. Since the contents of the SOME cell was set to TAGGED(0) "for safety" it no longer referred to a ref. E.g. Weak.weakArray (2, SOME (ref ())) could segfault after GC.<commit_after>/*
Title: Multi-Threaded Garbage Collector - Check for weak references
Copyright (c) 2010, 2012 David C. J. Matthews
Based on the original garbage collector code
Copyright 2000-2008
Cambridge University Technical Services Limited
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
*/
/*
This is an intermediate phase in the GC that checks for weak references
that are no longer reachable. It is performed after the first, mark, phase.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#elif defined(_WIN32)
#include "winconfig.h"
#else
#error "No configuration file"
#endif
#ifdef HAVE_ASSERT_H
#include <assert.h>
#define ASSERT(x) assert(x)
#else
#define ASSERT(x)
#endif
#include "globals.h"
#include "gc.h"
#include "scanaddrs.h"
#include "rts_module.h"
#include "memmgr.h"
class MTGCCheckWeakRef: public ScanAddress {
public:
void ScanAreas(void);
private:
virtual void ScanRuntimeAddress(PolyObject **pt, RtsStrength weak);
// This has to be defined since it's virtual.
virtual PolyObject *ScanObjectAddress(PolyObject *base) { return base; }
virtual void ScanAddressesInObject(PolyObject *obj, POLYUNSIGNED lengthWord);
};
// This deals with weak references within the run-time system.
void MTGCCheckWeakRef::ScanRuntimeAddress(PolyObject **pt, RtsStrength weak)
{
/* If the object has not been marked and this is only a weak reference */
/* then the pointer is set to zero. This allows streams or windows */
/* to be closed if there is no other reference to them. */
PolyObject *val = *pt;
PolyWord w = val;
if (weak == STRENGTH_STRONG)
return;
LocalMemSpace *space = gMem.LocalSpaceForAddress(w.AsStackAddr());
if (space == 0)
return; // Not in local area
// If it hasn't been marked set it to zero.
if (! space->bitmap.TestBit(space->wordNo(w.AsStackAddr())))
*pt = 0;
}
// Deal with weak objects
void MTGCCheckWeakRef::ScanAddressesInObject(PolyObject *obj, POLYUNSIGNED L)
{
if (! OBJ_IS_WEAKREF_OBJECT(L)) return;
ASSERT(OBJ_IS_MUTABLE_OBJECT(L)); // Should be a mutable.
ASSERT(OBJ_IS_WORD_OBJECT(L)); // Should be a plain object.
// See if any of the SOME objects contain unreferenced refs.
POLYUNSIGNED length = OBJ_OBJECT_LENGTH(L);
PolyWord *baseAddr = (PolyWord*)obj;
for (POLYUNSIGNED i = 0; i < length; i++)
{
PolyWord someAddr = baseAddr[i];
if (someAddr.IsDataPtr())
{
LocalMemSpace *someSpace = gMem.LocalSpaceForAddress(someAddr.AsAddress());
if (someSpace != 0)
{
PolyObject *someObj = someAddr.AsObjPtr();
// If this is a weak object the SOME value may refer to an unreferenced
// ref. If so we have to set this entry to NONE. For safety we also
// set the contents of the SOME to TAGGED(0).
ASSERT(someObj->Length() == 1 && someObj->IsWordObject()); // Should be a SOME node.
PolyWord refAddress = someObj->Get(0);
bool deleteRef = false;
if (refAddress.IsTagged())
// If we have the same SOME cell referenced in two different places
// we will have overwritten the address with TAGGED(0) "For safety".
// We still need to overwrite the new reference to the SOME cell.
deleteRef = true; // We've overwritten it.
else
{
// Usual case: the contents of the SOME cell is the address of a ref.
LocalMemSpace *space = gMem.LocalSpaceForAddress(refAddress.AsAddress());
if (space != 0) // If the ref is permanent it's always there.
{
POLYUNSIGNED new_bitno = space->wordNo(refAddress.AsStackAddr());
// It wasn't marked so it's otherwise unreferenced.
if (! space->bitmap.TestBit(new_bitno)) deleteRef = true;
}
}
if (deleteRef)
{
baseAddr[i] = TAGGED(0); // Set it to NONE.
someObj->Set(0, TAGGED(0)); // For safety.
convertedWeak = true;
}
}
}
}
}
// We need to check any weak references both in the areas we are
// currently collecting and any other areas. This actually checks
// weak refs in the area we're collecting even if they are not
// actually reachable any more. N.B. This differs from OpMutables
// because it also scans the area we're collecting.
void MTGCCheckWeakRef::ScanAreas(void)
{
for (unsigned i = 0; i < gMem.nlSpaces; i++)
{
LocalMemSpace *space = gMem.lSpaces[i];
if (space->isMutable)
ScanAddressesInRegion(space->lowestWeak, space->highestWeak);
}
// Scan the permanent mutable areas.
for (unsigned j = 0; j < gMem.npSpaces; j++)
{
MemSpace *space = gMem.pSpaces[j];
if (space->isMutable)
ScanAddressesInRegion(space->lowestWeak, space->highestWeak);
}
}
void GCheckWeakRefs()
{
MTGCCheckWeakRef checkRef;
GCModules(&checkRef);
checkRef.ScanAreas();
}
<|endoftext|> |
<commit_before>#include "Solver.h"
#include "defines.h"
namespace sqaod {
/* name string for float/double */
template<class real> const char *typeString();
template<> const char *typeString<float>() { return "float"; }
template<> const char *typeString<double>() { return "double"; }
}
using namespace sqaod;
template<class real>
void Solver<real>::setPreferences(const Preferences &prefs) {
for (Preferences::const_iterator it = prefs.begin();
it != prefs.end(); ++it) {
setPreference(*it);
}
}
/* solver state */
template<class real>
void Solver<real>::setState(SolverState state) {
clearState(state);
solverState_ |= state;
}
template<class real>
void Solver<real>::clearState(SolverState state) {
int stateToClear = 0;
switch (state) {
case solRandSeedGiven:
stateToClear = solRandSeedGiven;
break; /* independent state */
case solProblemSet :
stateToClear |= solProblemSet;
/* no break */
case solPrepared:
stateToClear |= solPrepared;
/* no break */
case solQSet:
stateToClear |= solQSet;
/* no break */
case solEAvailable:
case solSolutionAvailable:
stateToClear |= solEAvailable;
stateToClear |= solSolutionAvailable;
/* no break */
default:
break;
}
solverState_ &= ~stateToClear;
}
template<class real>
bool Solver<real>::isRandSeedGiven() const {
return (solverState_ & solRandSeedGiven) != 0;
}
template<class real>
bool Solver<real>::isProblemSet() const {
return (solverState_ & solProblemSet) != 0;
}
template<class real>
bool Solver<real>::isPrepared() const {
return (solverState_ & solPrepared) != 0;
}
template<class real>
bool Solver<real>::isQSet() const {
return (solverState_ & solQSet) != 0;
}
template<class real>
bool Solver<real>::isEAvailable() const {
return (solverState_ & solEAvailable) != 0;
}
template<class real>
bool Solver<real>::isSolutionAvailable() const {
return (solverState_ & solSolutionAvailable) != 0;
}
template<class real>
void Solver<real>::throwErrorIfProblemNotSet() const {
throwErrorIf(!isProblemSet(), "Problem is not set.");
}
template<class real>
void Solver<real>::throwErrorIfNotPrepared() const {
throwErrorIfProblemNotSet();
throwErrorIf(!isPrepared(),
"not prepared, call prepare() in advance.");
}
template<class real>
void Solver<real>::throwErrorIfQNotSet() const {
throwErrorIf(!isQSet(),
"Bits(x or q) not initialized. Plase set or randomize in advance.");
}
template<class real>
Algorithm BFSearcher<real>::selectAlgorithm(Algorithm algo) {
return algoBruteForceSearch;
}
template<class real>
Algorithm BFSearcher<real>::getAlgorithm() const {
return algoBruteForceSearch;
}
template<class real>
Preferences Annealer<real>::getPreferences() const {
Preferences prefs;
prefs.pushBack(Preference(pnAlgorithm, this->getAlgorithm()));
prefs.pushBack(Preference(pnNumTrotters, m_));
prefs.pushBack(Preference(pnPrecision, typeString<real>()));
return prefs;
}
template<class real>
void Annealer<real>::setPreference(const Preference &pref) {
if (pref.name == pnNumTrotters) {
throwErrorIf(pref.nTrotters <= 0, "# trotters must be a positive integer.");
if (m_ != pref.nTrotters)
Solver<real>::clearState(Solver<real>::solPrepared);
m_ = pref.nTrotters;
}
else if (pref.name == pnAlgorithm) {
this->selectAlgorithm(pref.algo);
}
}
template<class real>
void DenseGraphSolver<real>::getProblemSize(SizeType *N) const {
*N = N_;
}
template<class real>
void BipartiteGraphSolver<real>::getProblemSize(SizeType *N0, SizeType *N1) const {
*N0 = N0_;
*N1 = N1_;
}
template<class real>
Preferences DenseGraphBFSearcher<real>::getPreferences() const {
Preferences prefs;
prefs.pushBack(Preference(pnAlgorithm, algoBruteForceSearch));
prefs.pushBack(Preference(pnTileSize, tileSize_));
prefs.pushBack(Preference(pnPrecision, typeString<real>()));
return prefs;
}
template<class real>
void DenseGraphBFSearcher<real>::setPreference(const Preference &pref) {
if (pref.name == pnTileSize) {
throwErrorIf(pref.tileSize <= 0, "tileSize must be a positive integer.");
tileSize_ = pref.tileSize;
}
}
template<class real>
void DenseGraphBFSearcher<real>::search() {
this->prepare();
while (!searchRange(NULL));
this->makeSolution();
}
template<class real>
Preferences BipartiteGraphBFSearcher<real>::getPreferences() const {
Preferences prefs;
prefs.pushBack(Preference(pnAlgorithm, algoBruteForceSearch));
prefs.pushBack(Preference(pnTileSize0, tileSize0_));
prefs.pushBack(Preference(pnTileSize1, tileSize1_));
return prefs;
}
template<class real>
void BipartiteGraphBFSearcher<real>::setPreference(const Preference &pref) {
if (pref.name == pnTileSize0) {
throwErrorIf(pref.tileSize <= 0, "tileSize0 must be a positive integer.");
tileSize0_ = pref.tileSize;
}
if (pref.name == pnTileSize1) {
throwErrorIf(pref.tileSize <= 0, "tileSize1 must be a positive integer.");
tileSize1_ = pref.tileSize;
}
}
template<class real>
void BipartiteGraphBFSearcher<real>::search() {
this->prepare();
while (!searchRange(NULL, NULL));
this->makeSolution();
}
/* explicit instantiation */
template struct sqaod::Solver<double>;
template struct sqaod::Solver<float>;
template struct sqaod::BFSearcher<double>;
template struct sqaod::BFSearcher<float>;
template struct sqaod::Annealer<double>;
template struct sqaod::Annealer<float>;
template struct sqaod::DenseGraphSolver<double>;
template struct sqaod::DenseGraphSolver<float>;
template struct sqaod::BipartiteGraphSolver<double>;
template struct sqaod::BipartiteGraphSolver<float>;
template struct sqaod::DenseGraphBFSearcher<double>;
template struct sqaod::DenseGraphBFSearcher<float>;
template struct sqaod::DenseGraphAnnealer<double>;
template struct sqaod::DenseGraphAnnealer<float>;
template struct sqaod::BipartiteGraphBFSearcher<double>;
template struct sqaod::BipartiteGraphBFSearcher<float>;
template struct sqaod::BipartiteGraphAnnealer<double>;
template struct sqaod::BipartiteGraphAnnealer<float>;
<commit_msg>BipartiteGraphBFSearcher: adding precision to preference.<commit_after>#include "Solver.h"
#include "defines.h"
namespace sqaod {
/* name string for float/double */
template<class real> const char *typeString();
template<> const char *typeString<float>() { return "float"; }
template<> const char *typeString<double>() { return "double"; }
}
using namespace sqaod;
template<class real>
void Solver<real>::setPreferences(const Preferences &prefs) {
for (Preferences::const_iterator it = prefs.begin();
it != prefs.end(); ++it) {
setPreference(*it);
}
}
/* solver state */
template<class real>
void Solver<real>::setState(SolverState state) {
clearState(state);
solverState_ |= state;
}
template<class real>
void Solver<real>::clearState(SolverState state) {
int stateToClear = 0;
switch (state) {
case solRandSeedGiven:
stateToClear = solRandSeedGiven;
break; /* independent state */
case solProblemSet :
stateToClear |= solProblemSet;
/* no break */
case solPrepared:
stateToClear |= solPrepared;
/* no break */
case solQSet:
stateToClear |= solQSet;
/* no break */
case solEAvailable:
case solSolutionAvailable:
stateToClear |= solEAvailable;
stateToClear |= solSolutionAvailable;
/* no break */
default:
break;
}
solverState_ &= ~stateToClear;
}
template<class real>
bool Solver<real>::isRandSeedGiven() const {
return (solverState_ & solRandSeedGiven) != 0;
}
template<class real>
bool Solver<real>::isProblemSet() const {
return (solverState_ & solProblemSet) != 0;
}
template<class real>
bool Solver<real>::isPrepared() const {
return (solverState_ & solPrepared) != 0;
}
template<class real>
bool Solver<real>::isQSet() const {
return (solverState_ & solQSet) != 0;
}
template<class real>
bool Solver<real>::isEAvailable() const {
return (solverState_ & solEAvailable) != 0;
}
template<class real>
bool Solver<real>::isSolutionAvailable() const {
return (solverState_ & solSolutionAvailable) != 0;
}
template<class real>
void Solver<real>::throwErrorIfProblemNotSet() const {
throwErrorIf(!isProblemSet(), "Problem is not set.");
}
template<class real>
void Solver<real>::throwErrorIfNotPrepared() const {
throwErrorIfProblemNotSet();
throwErrorIf(!isPrepared(),
"not prepared, call prepare() in advance.");
}
template<class real>
void Solver<real>::throwErrorIfQNotSet() const {
throwErrorIf(!isQSet(),
"Bits(x or q) not initialized. Plase set or randomize in advance.");
}
template<class real>
Algorithm BFSearcher<real>::selectAlgorithm(Algorithm algo) {
return algoBruteForceSearch;
}
template<class real>
Algorithm BFSearcher<real>::getAlgorithm() const {
return algoBruteForceSearch;
}
template<class real>
Preferences Annealer<real>::getPreferences() const {
Preferences prefs;
prefs.pushBack(Preference(pnAlgorithm, this->getAlgorithm()));
prefs.pushBack(Preference(pnNumTrotters, m_));
prefs.pushBack(Preference(pnPrecision, typeString<real>()));
return prefs;
}
template<class real>
void Annealer<real>::setPreference(const Preference &pref) {
if (pref.name == pnNumTrotters) {
throwErrorIf(pref.nTrotters <= 0, "# trotters must be a positive integer.");
if (m_ != pref.nTrotters)
Solver<real>::clearState(Solver<real>::solPrepared);
m_ = pref.nTrotters;
}
else if (pref.name == pnAlgorithm) {
this->selectAlgorithm(pref.algo);
}
}
template<class real>
void DenseGraphSolver<real>::getProblemSize(SizeType *N) const {
*N = N_;
}
template<class real>
void BipartiteGraphSolver<real>::getProblemSize(SizeType *N0, SizeType *N1) const {
*N0 = N0_;
*N1 = N1_;
}
template<class real>
Preferences DenseGraphBFSearcher<real>::getPreferences() const {
Preferences prefs;
prefs.pushBack(Preference(pnAlgorithm, algoBruteForceSearch));
prefs.pushBack(Preference(pnTileSize, tileSize_));
prefs.pushBack(Preference(pnPrecision, typeString<real>()));
return prefs;
}
template<class real>
void DenseGraphBFSearcher<real>::setPreference(const Preference &pref) {
if (pref.name == pnTileSize) {
throwErrorIf(pref.tileSize <= 0, "tileSize must be a positive integer.");
tileSize_ = pref.tileSize;
}
}
template<class real>
void DenseGraphBFSearcher<real>::search() {
this->prepare();
while (!searchRange(NULL));
this->makeSolution();
}
template<class real>
Preferences BipartiteGraphBFSearcher<real>::getPreferences() const {
Preferences prefs;
prefs.pushBack(Preference(pnAlgorithm, algoBruteForceSearch));
prefs.pushBack(Preference(pnTileSize0, tileSize0_));
prefs.pushBack(Preference(pnTileSize1, tileSize1_));
prefs.pushBack(Preference(pnPrecision, typeString<real>()));
return prefs;
}
template<class real>
void BipartiteGraphBFSearcher<real>::setPreference(const Preference &pref) {
if (pref.name == pnTileSize0) {
throwErrorIf(pref.tileSize <= 0, "tileSize0 must be a positive integer.");
tileSize0_ = pref.tileSize;
}
if (pref.name == pnTileSize1) {
throwErrorIf(pref.tileSize <= 0, "tileSize1 must be a positive integer.");
tileSize1_ = pref.tileSize;
}
}
template<class real>
void BipartiteGraphBFSearcher<real>::search() {
this->prepare();
while (!searchRange(NULL, NULL));
this->makeSolution();
}
/* explicit instantiation */
template struct sqaod::Solver<double>;
template struct sqaod::Solver<float>;
template struct sqaod::BFSearcher<double>;
template struct sqaod::BFSearcher<float>;
template struct sqaod::Annealer<double>;
template struct sqaod::Annealer<float>;
template struct sqaod::DenseGraphSolver<double>;
template struct sqaod::DenseGraphSolver<float>;
template struct sqaod::BipartiteGraphSolver<double>;
template struct sqaod::BipartiteGraphSolver<float>;
template struct sqaod::DenseGraphBFSearcher<double>;
template struct sqaod::DenseGraphBFSearcher<float>;
template struct sqaod::DenseGraphAnnealer<double>;
template struct sqaod::DenseGraphAnnealer<float>;
template struct sqaod::BipartiteGraphBFSearcher<double>;
template struct sqaod::BipartiteGraphBFSearcher<float>;
template struct sqaod::BipartiteGraphAnnealer<double>;
template struct sqaod::BipartiteGraphAnnealer<float>;
<|endoftext|> |
<commit_before><commit_msg>Fix signed/unsigned comparisons<commit_after><|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkAxesTransformRepresentation.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkAxesTransformRepresentation.h"
#include "vtkPointHandleRepresentation3D.h"
#include "vtkPolyDataMapper.h"
#include "vtkPoints.h"
#include "vtkCellArray.h"
#include "vtkPolyData.h"
#include "vtkPolyDataMapper.h"
#include "vtkActor.h"
#include "vtkVectorText.h"
#include "vtkFollower.h"
#include "vtkCamera.h"
#include "vtkProperty.h"
#include "vtkCoordinate.h"
#include "vtkRenderer.h"
#include "vtkObjectFactory.h"
#include "vtkInteractorObserver.h"
#include "vtkMath.h"
#include "vtkWindow.h"
#include "vtkSmartPointer.h"
#include "vtkBox.h"
#include "vtkGlyph3D.h"
#include "vtkCylinderSource.h"
#include "vtkDoubleArray.h"
#include "vtkPointData.h"
#include "vtkTransformPolyDataFilter.h"
#include "vtkTransform.h"
#include "vtkSmartPointer.h"
vtkStandardNewMacro(vtkAxesTransformRepresentation);
//----------------------------------------------------------------------
vtkAxesTransformRepresentation::vtkAxesTransformRepresentation()
{
// By default, use one of these handles
this->OriginRepresentation = vtkPointHandleRepresentation3D::New();
this->SelectionRepresentation = vtkPointHandleRepresentation3D::New();
// The line
this->LinePoints = vtkPoints::New();
this->LinePoints->SetDataTypeToDouble();
this->LinePoints->SetNumberOfPoints(2);
this->LinePolyData = vtkPolyData::New();
this->LinePolyData->SetPoints(this->LinePoints);
vtkSmartPointer<vtkCellArray> line = vtkSmartPointer<vtkCellArray>::New();
line->InsertNextCell(2);
line->InsertCellPoint(0);
line->InsertCellPoint(1);
this->LinePolyData->SetLines(line);
this->LineMapper = vtkPolyDataMapper::New();
this->LineMapper->SetInput(this->LinePolyData);
this->LineActor = vtkActor::New();
this->LineActor->SetMapper(this->LineMapper);
// The label
this->LabelText = vtkVectorText::New();
this->LabelMapper = vtkPolyDataMapper::New();
this->LabelMapper->SetInputConnection(this->LabelText->GetOutputPort());
this->LabelActor = vtkFollower::New();
this->LabelActor->SetMapper(this->LabelMapper);
// The tick marks
this->GlyphPoints = vtkPoints::New();
this->GlyphPoints->SetDataTypeToDouble();
this->GlyphVectors = vtkDoubleArray::New();
this->GlyphVectors->SetNumberOfComponents(3);
this->GlyphPolyData = vtkPolyData::New();
this->GlyphPolyData->SetPoints(this->GlyphPoints);
this->GlyphPolyData->GetPointData()->SetVectors(this->GlyphVectors);
this->GlyphCylinder = vtkCylinderSource::New();
this->GlyphCylinder->SetRadius(0.5);
this->GlyphCylinder->SetHeight(0.1);
this->GlyphCylinder->SetResolution(12);
vtkSmartPointer<vtkTransform> xform = vtkSmartPointer<vtkTransform>::New();
this->GlyphXForm = vtkTransformPolyDataFilter::New();
this->GlyphXForm->SetInputConnection(this->GlyphCylinder->GetOutputPort());
this->GlyphXForm->SetTransform(xform);
xform->RotateZ(90);
this->Glyph3D = vtkGlyph3D::New();
this->Glyph3D->SetInput(this->GlyphPolyData);
this->Glyph3D->SetSourceConnection(this->GlyphXForm->GetOutputPort());
this->Glyph3D->SetScaleModeToDataScalingOff();
this->GlyphMapper = vtkPolyDataMapper::New();
this->GlyphMapper->SetInputConnection(this->Glyph3D->GetOutputPort());
this->GlyphActor = vtkActor::New();
this->GlyphActor->SetMapper(this->GlyphMapper);
// The bounding box
this->BoundingBox = vtkBox::New();
}
//----------------------------------------------------------------------
vtkAxesTransformRepresentation::~vtkAxesTransformRepresentation()
{
this->LinePoints->Delete();
this->LinePolyData->Delete();
this->LineMapper->Delete();
this->LineActor->Delete();
this->LabelText->Delete();
this->LabelMapper->Delete();
this->LabelActor->Delete();
this->GlyphPoints->Delete();
this->GlyphVectors->Delete();
this->GlyphPolyData->Delete();
this->GlyphCylinder->Delete();
this->GlyphXForm->Delete();
this->Glyph3D->Delete();
this->GlyphMapper->Delete();
this->GlyphActor->Delete();
this->BoundingBox->Delete();
}
//----------------------------------------------------------------------
void vtkAxesTransformRepresentation::GetOriginWorldPosition(double pos[3])
{
this->OriginRepresentation->GetWorldPosition(pos);
}
//----------------------------------------------------------------------
double* vtkAxesTransformRepresentation::GetOriginWorldPosition()
{
if (!this->OriginRepresentation)
{
static double temp[3]= {0, 0, 0};
return temp;
}
return this->OriginRepresentation->GetWorldPosition();
}
//----------------------------------------------------------------------
void vtkAxesTransformRepresentation::SetOriginDisplayPosition(double x[3])
{
this->OriginRepresentation->SetDisplayPosition(x);
double p[3];
this->OriginRepresentation->GetWorldPosition(p);
this->OriginRepresentation->SetWorldPosition(p);
}
//----------------------------------------------------------------------
void vtkAxesTransformRepresentation::SetOriginWorldPosition(double x[3])
{
if (this->OriginRepresentation)
{
this->OriginRepresentation->SetWorldPosition(x);
}
}
//----------------------------------------------------------------------
void vtkAxesTransformRepresentation::GetOriginDisplayPosition(double pos[3])
{
this->OriginRepresentation->GetDisplayPosition(pos);
pos[2] = 0.0;
}
//----------------------------------------------------------------------
double *vtkAxesTransformRepresentation::GetBounds()
{
this->BuildRepresentation();
this->BoundingBox->SetBounds(this->OriginRepresentation->GetBounds());
this->BoundingBox->AddBounds(this->SelectionRepresentation->GetBounds());
this->BoundingBox->AddBounds(this->LineActor->GetBounds());
return this->BoundingBox->GetBounds();
}
//----------------------------------------------------------------------
void vtkAxesTransformRepresentation::StartWidgetInteraction(double e[2])
{
// Store the start position
this->StartEventPosition[0] = e[0];
this->StartEventPosition[1] = e[1];
this->StartEventPosition[2] = 0.0;
// Store the start position
this->LastEventPosition[0] = e[0];
this->LastEventPosition[1] = e[1];
this->LastEventPosition[2] = 0.0;
// Get the coordinates of the three handles
// this->OriginRepresentation->GetWorldPosition(this->StartP1);
// this->SelectionRepresentation->GetWorldPosition(this->StartP2);
}
//----------------------------------------------------------------------
void vtkAxesTransformRepresentation::WidgetInteraction(double e[2])
{
// Store the start position
this->LastEventPosition[0] = e[0];
this->LastEventPosition[1] = e[1];
this->LastEventPosition[2] = 0.0;
}
//----------------------------------------------------------------------------
int vtkAxesTransformRepresentation::ComputeInteractionState(int X, int Y, int vtkNotUsed(modify))
{
// Check if we are on the origin. Use the handle to determine this.
int p1State = this->OriginRepresentation->ComputeInteractionState(X,Y,0);
if ( p1State == vtkHandleRepresentation::Nearby )
{
this->InteractionState = vtkAxesTransformRepresentation::OnOrigin;
// this->SetRepresentationState(vtkAxesTransformRepresentation::OnOrigin);
}
else
{
this->InteractionState = vtkAxesTransformRepresentation::Outside;
}
// Okay if we're near a handle return, otherwise test the line
if ( this->InteractionState != vtkAxesTransformRepresentation::Outside )
{
return this->InteractionState;
}
return this->InteractionState;
}
//----------------------------------------------------------------------
void vtkAxesTransformRepresentation::BuildRepresentation()
{
if ( this->GetMTime() > this->BuildTime ||
this->OriginRepresentation->GetMTime() > this->BuildTime ||
this->SelectionRepresentation->GetMTime() > this->BuildTime ||
(this->Renderer && this->Renderer->GetVTKWindow() &&
this->Renderer->GetVTKWindow()->GetMTime() > this->BuildTime) )
{
this->BuildTime.Modified();
}
}
//----------------------------------------------------------------------
void vtkAxesTransformRepresentation::
ReleaseGraphicsResources(vtkWindow *w)
{
this->LineActor->ReleaseGraphicsResources(w);
this->LabelActor->ReleaseGraphicsResources(w);
this->GlyphActor->ReleaseGraphicsResources(w);
}
//----------------------------------------------------------------------
int vtkAxesTransformRepresentation::
RenderOpaqueGeometry(vtkViewport *v)
{
this->BuildRepresentation();
this->LineActor->RenderOpaqueGeometry(v);
this->LabelActor->RenderOpaqueGeometry(v);
this->GlyphActor->RenderOpaqueGeometry(v);
return 3;
}
//----------------------------------------------------------------------
int vtkAxesTransformRepresentation::
RenderTranslucentPolygonalGeometry(vtkViewport *v)
{
this->BuildRepresentation();
this->LineActor->RenderTranslucentPolygonalGeometry(v);
this->LabelActor->RenderTranslucentPolygonalGeometry(v);
this->GlyphActor->RenderTranslucentPolygonalGeometry(v);
return 3;
}
//----------------------------------------------------------------------
void vtkAxesTransformRepresentation::SetLabelScale( double scale[3] )
{
this->LabelActor->SetScale( scale );
}
//----------------------------------------------------------------------
double * vtkAxesTransformRepresentation::GetLabelScale()
{
return this->LabelActor->GetScale();
}
//----------------------------------------------------------------------------
vtkProperty * vtkAxesTransformRepresentation::GetLabelProperty()
{
return this->LabelActor->GetProperty();
}
//----------------------------------------------------------------------
void vtkAxesTransformRepresentation::PrintSelf(ostream& os, vtkIndent indent)
{
//Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h
this->Superclass::PrintSelf(os,indent);
}
<commit_msg>Fix Widgets printself test.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkAxesTransformRepresentation.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkAxesTransformRepresentation.h"
#include "vtkPointHandleRepresentation3D.h"
#include "vtkPolyDataMapper.h"
#include "vtkPoints.h"
#include "vtkCellArray.h"
#include "vtkPolyData.h"
#include "vtkPolyDataMapper.h"
#include "vtkActor.h"
#include "vtkVectorText.h"
#include "vtkFollower.h"
#include "vtkCamera.h"
#include "vtkProperty.h"
#include "vtkCoordinate.h"
#include "vtkRenderer.h"
#include "vtkObjectFactory.h"
#include "vtkInteractorObserver.h"
#include "vtkMath.h"
#include "vtkWindow.h"
#include "vtkSmartPointer.h"
#include "vtkBox.h"
#include "vtkGlyph3D.h"
#include "vtkCylinderSource.h"
#include "vtkDoubleArray.h"
#include "vtkPointData.h"
#include "vtkTransformPolyDataFilter.h"
#include "vtkTransform.h"
#include "vtkSmartPointer.h"
vtkStandardNewMacro(vtkAxesTransformRepresentation);
//----------------------------------------------------------------------
vtkAxesTransformRepresentation::vtkAxesTransformRepresentation()
{
// By default, use one of these handles
this->OriginRepresentation = vtkPointHandleRepresentation3D::New();
this->SelectionRepresentation = vtkPointHandleRepresentation3D::New();
// The line
this->LinePoints = vtkPoints::New();
this->LinePoints->SetDataTypeToDouble();
this->LinePoints->SetNumberOfPoints(2);
this->LinePolyData = vtkPolyData::New();
this->LinePolyData->SetPoints(this->LinePoints);
vtkSmartPointer<vtkCellArray> line = vtkSmartPointer<vtkCellArray>::New();
line->InsertNextCell(2);
line->InsertCellPoint(0);
line->InsertCellPoint(1);
this->LinePolyData->SetLines(line);
this->LineMapper = vtkPolyDataMapper::New();
this->LineMapper->SetInput(this->LinePolyData);
this->LineActor = vtkActor::New();
this->LineActor->SetMapper(this->LineMapper);
// The label
this->LabelText = vtkVectorText::New();
this->LabelMapper = vtkPolyDataMapper::New();
this->LabelMapper->SetInputConnection(this->LabelText->GetOutputPort());
this->LabelActor = vtkFollower::New();
this->LabelActor->SetMapper(this->LabelMapper);
// The tick marks
this->GlyphPoints = vtkPoints::New();
this->GlyphPoints->SetDataTypeToDouble();
this->GlyphVectors = vtkDoubleArray::New();
this->GlyphVectors->SetNumberOfComponents(3);
this->GlyphPolyData = vtkPolyData::New();
this->GlyphPolyData->SetPoints(this->GlyphPoints);
this->GlyphPolyData->GetPointData()->SetVectors(this->GlyphVectors);
this->GlyphCylinder = vtkCylinderSource::New();
this->GlyphCylinder->SetRadius(0.5);
this->GlyphCylinder->SetHeight(0.1);
this->GlyphCylinder->SetResolution(12);
vtkSmartPointer<vtkTransform> xform = vtkSmartPointer<vtkTransform>::New();
this->GlyphXForm = vtkTransformPolyDataFilter::New();
this->GlyphXForm->SetInputConnection(this->GlyphCylinder->GetOutputPort());
this->GlyphXForm->SetTransform(xform);
xform->RotateZ(90);
this->Glyph3D = vtkGlyph3D::New();
this->Glyph3D->SetInput(this->GlyphPolyData);
this->Glyph3D->SetSourceConnection(this->GlyphXForm->GetOutputPort());
this->Glyph3D->SetScaleModeToDataScalingOff();
this->GlyphMapper = vtkPolyDataMapper::New();
this->GlyphMapper->SetInputConnection(this->Glyph3D->GetOutputPort());
this->GlyphActor = vtkActor::New();
this->GlyphActor->SetMapper(this->GlyphMapper);
// The bounding box
this->BoundingBox = vtkBox::New();
}
//----------------------------------------------------------------------
vtkAxesTransformRepresentation::~vtkAxesTransformRepresentation()
{
this->LinePoints->Delete();
this->LinePolyData->Delete();
this->LineMapper->Delete();
this->LineActor->Delete();
this->LabelText->Delete();
this->LabelMapper->Delete();
this->LabelActor->Delete();
this->GlyphPoints->Delete();
this->GlyphVectors->Delete();
this->GlyphPolyData->Delete();
this->GlyphCylinder->Delete();
this->GlyphXForm->Delete();
this->Glyph3D->Delete();
this->GlyphMapper->Delete();
this->GlyphActor->Delete();
this->BoundingBox->Delete();
}
//----------------------------------------------------------------------
void vtkAxesTransformRepresentation::GetOriginWorldPosition(double pos[3])
{
this->OriginRepresentation->GetWorldPosition(pos);
}
//----------------------------------------------------------------------
double* vtkAxesTransformRepresentation::GetOriginWorldPosition()
{
if (!this->OriginRepresentation)
{
static double temp[3]= {0, 0, 0};
return temp;
}
return this->OriginRepresentation->GetWorldPosition();
}
//----------------------------------------------------------------------
void vtkAxesTransformRepresentation::SetOriginDisplayPosition(double x[3])
{
this->OriginRepresentation->SetDisplayPosition(x);
double p[3];
this->OriginRepresentation->GetWorldPosition(p);
this->OriginRepresentation->SetWorldPosition(p);
}
//----------------------------------------------------------------------
void vtkAxesTransformRepresentation::SetOriginWorldPosition(double x[3])
{
if (this->OriginRepresentation)
{
this->OriginRepresentation->SetWorldPosition(x);
}
}
//----------------------------------------------------------------------
void vtkAxesTransformRepresentation::GetOriginDisplayPosition(double pos[3])
{
this->OriginRepresentation->GetDisplayPosition(pos);
pos[2] = 0.0;
}
//----------------------------------------------------------------------
double *vtkAxesTransformRepresentation::GetBounds()
{
this->BuildRepresentation();
this->BoundingBox->SetBounds(this->OriginRepresentation->GetBounds());
this->BoundingBox->AddBounds(this->SelectionRepresentation->GetBounds());
this->BoundingBox->AddBounds(this->LineActor->GetBounds());
return this->BoundingBox->GetBounds();
}
//----------------------------------------------------------------------
void vtkAxesTransformRepresentation::StartWidgetInteraction(double e[2])
{
// Store the start position
this->StartEventPosition[0] = e[0];
this->StartEventPosition[1] = e[1];
this->StartEventPosition[2] = 0.0;
// Store the start position
this->LastEventPosition[0] = e[0];
this->LastEventPosition[1] = e[1];
this->LastEventPosition[2] = 0.0;
// Get the coordinates of the three handles
// this->OriginRepresentation->GetWorldPosition(this->StartP1);
// this->SelectionRepresentation->GetWorldPosition(this->StartP2);
}
//----------------------------------------------------------------------
void vtkAxesTransformRepresentation::WidgetInteraction(double e[2])
{
// Store the start position
this->LastEventPosition[0] = e[0];
this->LastEventPosition[1] = e[1];
this->LastEventPosition[2] = 0.0;
}
//----------------------------------------------------------------------------
int vtkAxesTransformRepresentation::ComputeInteractionState(int X, int Y, int vtkNotUsed(modify))
{
// Check if we are on the origin. Use the handle to determine this.
int p1State = this->OriginRepresentation->ComputeInteractionState(X,Y,0);
if ( p1State == vtkHandleRepresentation::Nearby )
{
this->InteractionState = vtkAxesTransformRepresentation::OnOrigin;
// this->SetRepresentationState(vtkAxesTransformRepresentation::OnOrigin);
}
else
{
this->InteractionState = vtkAxesTransformRepresentation::Outside;
}
// Okay if we're near a handle return, otherwise test the line
if ( this->InteractionState != vtkAxesTransformRepresentation::Outside )
{
return this->InteractionState;
}
return this->InteractionState;
}
//----------------------------------------------------------------------
void vtkAxesTransformRepresentation::BuildRepresentation()
{
if ( this->GetMTime() > this->BuildTime ||
this->OriginRepresentation->GetMTime() > this->BuildTime ||
this->SelectionRepresentation->GetMTime() > this->BuildTime ||
(this->Renderer && this->Renderer->GetVTKWindow() &&
this->Renderer->GetVTKWindow()->GetMTime() > this->BuildTime) )
{
this->BuildTime.Modified();
}
}
//----------------------------------------------------------------------
void vtkAxesTransformRepresentation::
ReleaseGraphicsResources(vtkWindow *w)
{
this->LineActor->ReleaseGraphicsResources(w);
this->LabelActor->ReleaseGraphicsResources(w);
this->GlyphActor->ReleaseGraphicsResources(w);
}
//----------------------------------------------------------------------
int vtkAxesTransformRepresentation::
RenderOpaqueGeometry(vtkViewport *v)
{
this->BuildRepresentation();
this->LineActor->RenderOpaqueGeometry(v);
this->LabelActor->RenderOpaqueGeometry(v);
this->GlyphActor->RenderOpaqueGeometry(v);
return 3;
}
//----------------------------------------------------------------------
int vtkAxesTransformRepresentation::
RenderTranslucentPolygonalGeometry(vtkViewport *v)
{
this->BuildRepresentation();
this->LineActor->RenderTranslucentPolygonalGeometry(v);
this->LabelActor->RenderTranslucentPolygonalGeometry(v);
this->GlyphActor->RenderTranslucentPolygonalGeometry(v);
return 3;
}
//----------------------------------------------------------------------
void vtkAxesTransformRepresentation::SetLabelScale( double scale[3] )
{
this->LabelActor->SetScale( scale );
}
//----------------------------------------------------------------------
double * vtkAxesTransformRepresentation::GetLabelScale()
{
return this->LabelActor->GetScale();
}
//----------------------------------------------------------------------------
vtkProperty * vtkAxesTransformRepresentation::GetLabelProperty()
{
return this->LabelActor->GetProperty();
}
//----------------------------------------------------------------------
void vtkAxesTransformRepresentation::PrintSelf(ostream& os, vtkIndent indent)
{
std::cout << "LabelFormat: " << this->LabelFormat << std::endl;
std::cout << "Tolerance: " << this->Tolerance << std::endl;
std::cout << "InteractionState: " << this->InteractionState << std::endl;
std::cout << "OriginRepresentation: " << this->OriginRepresentation << endl;
std::cout << "SelectionRepresentation: " << this->SelectionRepresentation << endl;
this->Superclass::PrintSelf(os,indent);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <sstream>
#include "IRPrinter.h"
#include "IROperator.h"
#include "IR.h"
namespace Halide {
using std::ostream;
using std::vector;
using std::string;
using std::ostringstream;
ostream &operator<<(ostream &out, const Type &type) {
switch (type.code) {
case Type::Int:
out << "int";
break;
case Type::UInt:
out << "uint";
break;
case Type::Float:
out << "float";
break;
case Type::Handle:
out << "handle";
break;
}
out << type.bits;
if (type.width > 1) out << 'x' << type.width;
return out;
}
ostream &operator<<(ostream &stream, const Expr &ir) {
if (!ir.defined()) {
stream << "(undefined)";
} else {
Internal::IRPrinter p(stream);
p.print(ir);
}
return stream;
}
namespace Internal {
void IRPrinter::test() {
Type i32 = Int(32);
Type f32 = Float(32);
Expr x = Variable::make(Int(32), "x");
Expr y = Variable::make(Int(32), "y");
ostringstream expr_source;
expr_source << (x + 3) * (y / 2 + 17);
internal_assert(expr_source.str() == "((x + 3)*((y/2) + 17))");
Stmt store = Store::make("buf", (x * 17) / (x - 3), y - 1);
Stmt for_loop = For::make("x", -2, y + 2, For::Parallel, store);
vector<Expr> args(1); args[0] = x % 3;
Expr call = Call::make(i32, "buf", args, Call::Extern);
Stmt store2 = Store::make("out", call + 1, x);
Stmt for_loop2 = For::make("x", 0, y, For::Vectorized , store2);
Stmt pipeline = Pipeline::make("buf", for_loop, Stmt(), for_loop2);
Stmt assertion = AssertStmt::make(y > 3, "y is greater than %d", vec<Expr>(3));
Stmt block = Block::make(assertion, pipeline);
Stmt let_stmt = LetStmt::make("y", 17, block);
Stmt allocate = Allocate::make("buf", f32, vec(Expr(1023)), let_stmt);
ostringstream source;
source << allocate;
std::string correct_source = \
"allocate buf[float32 * 1023]\n"
"let y = 17\n"
"assert((y > 3), \"y is greater than %d\", 3)\n"
"produce buf {\n"
" parallel (x, -2, (y + 2)) {\n"
" buf[(y - 1)] = ((x*17)/(x - 3))\n"
" }\n"
"}\n"
"vectorized (x, 0, y) {\n"
" out[x] = (buf((x % 3)) + 1)\n"
"}\n";
if (source.str() != correct_source) {
internal_error << "Correct output:\n" << correct_source
<< "Actual output:\n" << source.str();
}
std::cout << "IRPrinter test passed\n";
}
ostream &operator<<(ostream &out, const For::ForType &type) {
switch (type) {
case For::Serial:
out << "for";
break;
case For::Parallel:
out << "parallel";
break;
case For::Unrolled:
out << "unrolled";
break;
case For::Vectorized:
out << "vectorized";
break;
}
return out;
}
ostream &operator<<(ostream &stream, const Stmt &ir) {
if (!ir.defined()) {
stream << "(undefined)\n";
} else {
Internal::IRPrinter p(stream);
p.print(ir);
}
return stream;
}
IRPrinter::IRPrinter(ostream &s) : stream(s), indent(0) {
s.setf(std::ios::fixed, std::ios::floatfield);
}
void IRPrinter::print(Expr ir) {
ir.accept(this);
}
void IRPrinter::print(Stmt ir) {
ir.accept(this);
}
void IRPrinter::do_indent() {
for (int i = 0; i < indent; i++) stream << ' ';
}
void IRPrinter::visit(const IntImm *op) {
stream << op->value;
}
void IRPrinter::visit(const FloatImm *op) {
stream << op->value << 'f';
}
void IRPrinter::visit(const StringImm *op) {
stream << '"';
for (size_t i = 0; i < op->value.size(); i++) {
unsigned char c = op->value[i];
if (c >= ' ' && c <= '~' && c != '\\' && c != '"') {
stream << c;
} else {
stream << '\\';
switch (c) {
case '"':
stream << '"';
break;
case '\\':
stream << '\\';
break;
case '\t':
stream << 't';
break;
case '\r':
stream << 'r';
break;
case '\n':
stream << 'n';
break;
default:
string hex_digits = "0123456789ABCDEF";
stream << 'x' << hex_digits[c >> 4] << hex_digits[c & 0xf];
}
}
}
stream << '"';
}
void IRPrinter::visit(const Cast *op) {
stream << op->type << '(';
print(op->value);
stream << ')';
}
void IRPrinter::visit(const Variable *op) {
// omit the type
// stream << op->name << "." << op->type;
stream << op->name;
}
void IRPrinter::visit(const Add *op) {
stream << '(';
print(op->a);
stream << " + ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Sub *op) {
stream << '(';
print(op->a);
stream << " - ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Mul *op) {
stream << '(';
print(op->a);
stream << "*";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Div *op) {
stream << '(';
print(op->a);
stream << "/";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Mod *op) {
stream << '(';
print(op->a);
stream << " % ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Min *op) {
stream << "min(";
print(op->a);
stream << ", ";
print(op->b);
stream << ")";
}
void IRPrinter::visit(const Max *op) {
stream << "max(";
print(op->a);
stream << ", ";
print(op->b);
stream << ")";
}
void IRPrinter::visit(const EQ *op) {
stream << '(';
print(op->a);
stream << " == ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const NE *op) {
stream << '(';
print(op->a);
stream << " != ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const LT *op) {
stream << '(';
print(op->a);
stream << " < ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const LE *op) {
stream << '(';
print(op->a);
stream << " <= ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const GT *op) {
stream << '(';
print(op->a);
stream << " > ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const GE *op) {
stream << '(';
print(op->a);
stream << " >= ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const And *op) {
stream << '(';
print(op->a);
stream << " && ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Or *op) {
stream << '(';
print(op->a);
stream << " || ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Not *op) {
stream << '!';
print(op->a);
}
void IRPrinter::visit(const Select *op) {
stream << "select(";
print(op->condition);
stream << ", ";
print(op->true_value);
stream << ", ";
print(op->false_value);
stream << ")";
}
void IRPrinter::visit(const Load *op) {
stream << op->name << "[";
print(op->index);
stream << "]";
}
void IRPrinter::visit(const Ramp *op) {
stream << "ramp(";
print(op->base);
stream << ", ";
print(op->stride);
stream << ", " << op->width << ")";
}
void IRPrinter::visit(const Broadcast *op) {
stream << "x" << op->width << "(";
print(op->value);
stream << ")";
}
void IRPrinter::visit(const Call *op) {
// Special-case some intrinsics for readability
if (op->call_type == Call::Intrinsic) {
if (op->name == Call::extract_buffer_min) {
print(op->args[0]);
stream << ".min[" << op->args[1] << "]";
return;
} else if (op->name == Call::extract_buffer_extent) {
print(op->args[0]);
stream << ".extent[" << op->args[1] << "]";
return;
}
}
stream << op->name << "(";
for (size_t i = 0; i < op->args.size(); i++) {
print(op->args[i]);
if (i < op->args.size() - 1) {
stream << ", ";
}
}
stream << ")";
}
void IRPrinter::visit(const Let *op) {
stream << "(let " << op->name << " = ";
print(op->value);
stream << " in ";
print(op->body);
stream << ")";
}
void IRPrinter::visit(const LetStmt *op) {
do_indent();
stream << "let " << op->name << " = ";
print(op->value);
stream << '\n';
print(op->body);
}
void IRPrinter::visit(const AssertStmt *op) {
do_indent();
stream << "assert(";
print(op->condition);
stream << ", " << '"' << op->message << '"';
for (size_t i = 0; i < op->args.size(); i++) {
stream << ", ";
print(op->args[i]);
}
stream << ")\n";
}
void IRPrinter::visit(const Pipeline *op) {
do_indent();
stream << "produce " << op->name << " {\n";
indent += 2;
print(op->produce);
indent -= 2;
if (op->update.defined()) {
do_indent();
stream << "} update " << op->name << " {\n";
indent += 2;
print(op->update);
indent -= 2;
}
do_indent();
stream << "}\n";
print(op->consume);
}
void IRPrinter::visit(const For *op) {
do_indent();
stream << op->for_type << " (" << op->name << ", ";
print(op->min);
stream << ", ";
print(op->extent);
stream << ") {\n";
indent += 2;
print(op->body);
indent -= 2;
do_indent();
stream << "}\n";
}
void IRPrinter::visit(const Store *op) {
do_indent();
stream << op->name << "[";
print(op->index);
stream << "] = ";
print(op->value);
stream << '\n';
}
void IRPrinter::visit(const Provide *op) {
do_indent();
stream << op->name << "(";
for (size_t i = 0; i < op->args.size(); i++) {
print(op->args[i]);
if (i < op->args.size() - 1) stream << ", ";
}
stream << ") = ";
if (op->values.size() > 1) {
stream << "{";
}
for (size_t i = 0; i < op->values.size(); i++) {
if (i > 0) {
stream << ", ";
}
print(op->values[i]);
}
if (op->values.size() > 1) {
stream << "}";
}
stream << '\n';
}
void IRPrinter::visit(const Allocate *op) {
do_indent();
stream << "allocate " << op->name << "[" << op->type;
for (size_t i = 0; i < op->extents.size(); i++) {
stream << " * ";
print(op->extents[i]);
}
stream << "]\n";
print(op->body);
}
void IRPrinter::visit(const Free *op) {
do_indent();
stream << "free " << op->name << '\n';
}
void IRPrinter::visit(const Realize *op) {
do_indent();
stream << "realize " << op->name << "(";
for (size_t i = 0; i < op->bounds.size(); i++) {
stream << "[";
print(op->bounds[i].min);
stream << ", ";
print(op->bounds[i].extent);
stream << "]";
if (i < op->bounds.size() - 1) stream << ", ";
}
stream << ") {\n";
indent += 2;
print(op->body);
indent -= 2;
do_indent();
stream << "}\n";
}
void IRPrinter::visit(const Block *op) {
print(op->first);
if (op->rest.defined()) print(op->rest);
}
void IRPrinter::visit(const IfThenElse *op) {
do_indent();
stream << "if (" << op->condition << ") {\n";
indent += 2;
print(op->then_case);
indent -= 2;
if (op->else_case.defined()) {
do_indent();
stream << "} else {\n";
indent += 2;
print(op->else_case);
indent -= 2;
}
do_indent();
stream << "}\n";
}
void IRPrinter::visit(const Evaluate *op) {
do_indent();
print(op->value);
stream << "\n";
}
}}
<commit_msg>Improve printing of nested if then else statements.<commit_after>#include <iostream>
#include <sstream>
#include "IRPrinter.h"
#include "IROperator.h"
#include "IR.h"
namespace Halide {
using std::ostream;
using std::vector;
using std::string;
using std::ostringstream;
ostream &operator<<(ostream &out, const Type &type) {
switch (type.code) {
case Type::Int:
out << "int";
break;
case Type::UInt:
out << "uint";
break;
case Type::Float:
out << "float";
break;
case Type::Handle:
out << "handle";
break;
}
out << type.bits;
if (type.width > 1) out << 'x' << type.width;
return out;
}
ostream &operator<<(ostream &stream, const Expr &ir) {
if (!ir.defined()) {
stream << "(undefined)";
} else {
Internal::IRPrinter p(stream);
p.print(ir);
}
return stream;
}
namespace Internal {
void IRPrinter::test() {
Type i32 = Int(32);
Type f32 = Float(32);
Expr x = Variable::make(Int(32), "x");
Expr y = Variable::make(Int(32), "y");
ostringstream expr_source;
expr_source << (x + 3) * (y / 2 + 17);
internal_assert(expr_source.str() == "((x + 3)*((y/2) + 17))");
Stmt store = Store::make("buf", (x * 17) / (x - 3), y - 1);
Stmt for_loop = For::make("x", -2, y + 2, For::Parallel, store);
vector<Expr> args(1); args[0] = x % 3;
Expr call = Call::make(i32, "buf", args, Call::Extern);
Stmt store2 = Store::make("out", call + 1, x);
Stmt for_loop2 = For::make("x", 0, y, For::Vectorized , store2);
Stmt pipeline = Pipeline::make("buf", for_loop, Stmt(), for_loop2);
Stmt assertion = AssertStmt::make(y > 3, "y is greater than %d", vec<Expr>(3));
Stmt block = Block::make(assertion, pipeline);
Stmt let_stmt = LetStmt::make("y", 17, block);
Stmt allocate = Allocate::make("buf", f32, vec(Expr(1023)), let_stmt);
ostringstream source;
source << allocate;
std::string correct_source = \
"allocate buf[float32 * 1023]\n"
"let y = 17\n"
"assert((y > 3), \"y is greater than %d\", 3)\n"
"produce buf {\n"
" parallel (x, -2, (y + 2)) {\n"
" buf[(y - 1)] = ((x*17)/(x - 3))\n"
" }\n"
"}\n"
"vectorized (x, 0, y) {\n"
" out[x] = (buf((x % 3)) + 1)\n"
"}\n";
if (source.str() != correct_source) {
internal_error << "Correct output:\n" << correct_source
<< "Actual output:\n" << source.str();
}
std::cout << "IRPrinter test passed\n";
}
ostream &operator<<(ostream &out, const For::ForType &type) {
switch (type) {
case For::Serial:
out << "for";
break;
case For::Parallel:
out << "parallel";
break;
case For::Unrolled:
out << "unrolled";
break;
case For::Vectorized:
out << "vectorized";
break;
}
return out;
}
ostream &operator<<(ostream &stream, const Stmt &ir) {
if (!ir.defined()) {
stream << "(undefined)\n";
} else {
Internal::IRPrinter p(stream);
p.print(ir);
}
return stream;
}
IRPrinter::IRPrinter(ostream &s) : stream(s), indent(0) {
s.setf(std::ios::fixed, std::ios::floatfield);
}
void IRPrinter::print(Expr ir) {
ir.accept(this);
}
void IRPrinter::print(Stmt ir) {
ir.accept(this);
}
void IRPrinter::do_indent() {
for (int i = 0; i < indent; i++) stream << ' ';
}
void IRPrinter::visit(const IntImm *op) {
stream << op->value;
}
void IRPrinter::visit(const FloatImm *op) {
stream << op->value << 'f';
}
void IRPrinter::visit(const StringImm *op) {
stream << '"';
for (size_t i = 0; i < op->value.size(); i++) {
unsigned char c = op->value[i];
if (c >= ' ' && c <= '~' && c != '\\' && c != '"') {
stream << c;
} else {
stream << '\\';
switch (c) {
case '"':
stream << '"';
break;
case '\\':
stream << '\\';
break;
case '\t':
stream << 't';
break;
case '\r':
stream << 'r';
break;
case '\n':
stream << 'n';
break;
default:
string hex_digits = "0123456789ABCDEF";
stream << 'x' << hex_digits[c >> 4] << hex_digits[c & 0xf];
}
}
}
stream << '"';
}
void IRPrinter::visit(const Cast *op) {
stream << op->type << '(';
print(op->value);
stream << ')';
}
void IRPrinter::visit(const Variable *op) {
// omit the type
// stream << op->name << "." << op->type;
stream << op->name;
}
void IRPrinter::visit(const Add *op) {
stream << '(';
print(op->a);
stream << " + ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Sub *op) {
stream << '(';
print(op->a);
stream << " - ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Mul *op) {
stream << '(';
print(op->a);
stream << "*";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Div *op) {
stream << '(';
print(op->a);
stream << "/";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Mod *op) {
stream << '(';
print(op->a);
stream << " % ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Min *op) {
stream << "min(";
print(op->a);
stream << ", ";
print(op->b);
stream << ")";
}
void IRPrinter::visit(const Max *op) {
stream << "max(";
print(op->a);
stream << ", ";
print(op->b);
stream << ")";
}
void IRPrinter::visit(const EQ *op) {
stream << '(';
print(op->a);
stream << " == ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const NE *op) {
stream << '(';
print(op->a);
stream << " != ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const LT *op) {
stream << '(';
print(op->a);
stream << " < ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const LE *op) {
stream << '(';
print(op->a);
stream << " <= ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const GT *op) {
stream << '(';
print(op->a);
stream << " > ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const GE *op) {
stream << '(';
print(op->a);
stream << " >= ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const And *op) {
stream << '(';
print(op->a);
stream << " && ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Or *op) {
stream << '(';
print(op->a);
stream << " || ";
print(op->b);
stream << ')';
}
void IRPrinter::visit(const Not *op) {
stream << '!';
print(op->a);
}
void IRPrinter::visit(const Select *op) {
stream << "select(";
print(op->condition);
stream << ", ";
print(op->true_value);
stream << ", ";
print(op->false_value);
stream << ")";
}
void IRPrinter::visit(const Load *op) {
stream << op->name << "[";
print(op->index);
stream << "]";
}
void IRPrinter::visit(const Ramp *op) {
stream << "ramp(";
print(op->base);
stream << ", ";
print(op->stride);
stream << ", " << op->width << ")";
}
void IRPrinter::visit(const Broadcast *op) {
stream << "x" << op->width << "(";
print(op->value);
stream << ")";
}
void IRPrinter::visit(const Call *op) {
// Special-case some intrinsics for readability
if (op->call_type == Call::Intrinsic) {
if (op->name == Call::extract_buffer_min) {
print(op->args[0]);
stream << ".min[" << op->args[1] << "]";
return;
} else if (op->name == Call::extract_buffer_extent) {
print(op->args[0]);
stream << ".extent[" << op->args[1] << "]";
return;
}
}
stream << op->name << "(";
for (size_t i = 0; i < op->args.size(); i++) {
print(op->args[i]);
if (i < op->args.size() - 1) {
stream << ", ";
}
}
stream << ")";
}
void IRPrinter::visit(const Let *op) {
stream << "(let " << op->name << " = ";
print(op->value);
stream << " in ";
print(op->body);
stream << ")";
}
void IRPrinter::visit(const LetStmt *op) {
do_indent();
stream << "let " << op->name << " = ";
print(op->value);
stream << '\n';
print(op->body);
}
void IRPrinter::visit(const AssertStmt *op) {
do_indent();
stream << "assert(";
print(op->condition);
stream << ", " << '"' << op->message << '"';
for (size_t i = 0; i < op->args.size(); i++) {
stream << ", ";
print(op->args[i]);
}
stream << ")\n";
}
void IRPrinter::visit(const Pipeline *op) {
do_indent();
stream << "produce " << op->name << " {\n";
indent += 2;
print(op->produce);
indent -= 2;
if (op->update.defined()) {
do_indent();
stream << "} update " << op->name << " {\n";
indent += 2;
print(op->update);
indent -= 2;
}
do_indent();
stream << "}\n";
print(op->consume);
}
void IRPrinter::visit(const For *op) {
do_indent();
stream << op->for_type << " (" << op->name << ", ";
print(op->min);
stream << ", ";
print(op->extent);
stream << ") {\n";
indent += 2;
print(op->body);
indent -= 2;
do_indent();
stream << "}\n";
}
void IRPrinter::visit(const Store *op) {
do_indent();
stream << op->name << "[";
print(op->index);
stream << "] = ";
print(op->value);
stream << '\n';
}
void IRPrinter::visit(const Provide *op) {
do_indent();
stream << op->name << "(";
for (size_t i = 0; i < op->args.size(); i++) {
print(op->args[i]);
if (i < op->args.size() - 1) stream << ", ";
}
stream << ") = ";
if (op->values.size() > 1) {
stream << "{";
}
for (size_t i = 0; i < op->values.size(); i++) {
if (i > 0) {
stream << ", ";
}
print(op->values[i]);
}
if (op->values.size() > 1) {
stream << "}";
}
stream << '\n';
}
void IRPrinter::visit(const Allocate *op) {
do_indent();
stream << "allocate " << op->name << "[" << op->type;
for (size_t i = 0; i < op->extents.size(); i++) {
stream << " * ";
print(op->extents[i]);
}
stream << "]\n";
print(op->body);
}
void IRPrinter::visit(const Free *op) {
do_indent();
stream << "free " << op->name << '\n';
}
void IRPrinter::visit(const Realize *op) {
do_indent();
stream << "realize " << op->name << "(";
for (size_t i = 0; i < op->bounds.size(); i++) {
stream << "[";
print(op->bounds[i].min);
stream << ", ";
print(op->bounds[i].extent);
stream << "]";
if (i < op->bounds.size() - 1) stream << ", ";
}
stream << ") {\n";
indent += 2;
print(op->body);
indent -= 2;
do_indent();
stream << "}\n";
}
void IRPrinter::visit(const Block *op) {
print(op->first);
if (op->rest.defined()) print(op->rest);
}
void IRPrinter::visit(const IfThenElse *op) {
do_indent();
while (1) {
stream << "if (" << op->condition << ") {\n";
indent += 2;
print(op->then_case);
indent -= 2;
if (!op->else_case.defined()) {
break;
}
if (const IfThenElse *nested_if = op->else_case.as<IfThenElse>()) {
do_indent();
stream << "} else ";
op = nested_if;
} else {
do_indent();
stream << "} else {\n";
indent += 2;
print(op->else_case);
indent -= 2;
break;
}
}
do_indent();
stream << "}\n";
}
void IRPrinter::visit(const Evaluate *op) {
do_indent();
print(op->value);
stream << "\n";
}
}}
<|endoftext|> |
<commit_before>#include "InputData.h"
#include <stdio.h>
InputData* InputData::instance = NULL;
InputData::InputData(){
drivers_.clear();
trailers_.clear();
location_.clear();
bases_.clear();
customers_.clear();
time_ = NULL;
distance_ = NULL;
}
InputData::~InputData(){
int i;
int nLoc = (int)location_.size();
int nDrivers = (int)drivers_.size();
int nTrailers = (int)trailers_.size();
//Release matrices and locations
for(i=0;i<nLoc;i++){
delete[] time_[i];
delete[] distance_[i];
delete location_[i]; //Locations pointers
}
delete[] time_;
delete[] distance_;
//Release drivers and trailers
for(i=0;i<nDrivers;i++)
delete drivers_[i]; //Drivers pointers
for(i=0;i<nTrailers;i++)
delete trailers_[i];//Trailers pointers
//Clear vectors
drivers_.clear();
trailers_.clear();
location_.clear();
bases_.clear();
customers_.clear();
}
InputData* InputData::getInstance(){
if( instance == NULL )
instance = new InputData();
return instance;
}
std::vector<Driver*>* InputData::getDrivers(){
return &(instance->drivers_);
}
std::vector<Trailer*>* InputData::getTrailers(){
return &(instance->trailers_);
}
std::vector<Location*>* InputData::getLocation(){
return &(instance->location_);
}
std::vector<Base*>* InputData::getBases(){
return &(instance->bases_);
}
std::vector<Customer*>* InputData::getCustomers(){
return &(instance->customers_);
}
<commit_msg>Atualização da InputData<commit_after>#include "InputData.h"
#include <stdio.h>
InputData* InputData::instance = NULL;
InputData::InputData(){
drivers_.clear();
trailers_.clear();
location_.clear();
bases_.clear();
customers_.clear();
time_ = NULL;
distance_ = NULL;
}
InputData::~InputData(){
int i;
int nLoc = (int)location_.size();
int nDrivers = (int)drivers_.size();
int nTrailers = (int)trailers_.size();
//Release matrices and locations
for(i=0;i<nLoc;i++){
delete[] time_[i];
delete[] distance_[i];
delete location_[i]; //Locations pointers
}
delete[] time_;
delete[] distance_;
//Release drivers and trailers
for(i=0;i<nDrivers;i++)
delete drivers_[i]; //Drivers pointers
for(i=0;i<nTrailers;i++)
delete trailers_[i];//Trailers pointers
//Clear vectors
drivers_.clear();
trailers_.clear();
location_.clear();
bases_.clear();
customers_.clear();
}
InputData* InputData::getInstance(){
if( instance == NULL )
instance = new InputData();
return instance;
}
std::vector<Driver*>* InputData::getDrivers(){
return &(instance->drivers_);
}
std::vector<Trailer*>* InputData::getTrailers(){
return &(instance->trailers_);
}
std::vector<Location*>* InputData::getLocation(){
return &(instance->location_);
}
std::vector<Base*>* InputData::getBases(){
return &(instance->bases_);
}
std::vector<Customer*>* InputData::getCustomers(){
return &(instance->customers_);
}
Driver* InputData::findDriver(int id){
//if it is sequencial
return instance->drivers_.at(id - 1);
//else
// for(Driver* d : drivers_){
// if(d->getIndex() == id){
// return d;
// }
// }
}
Trailer* InputData::findTrailer(int id){
//if it is sequencial
return instance->trailers_.at(id - 1);
//else
// for(Trailer* t : trailers_){
// if(t->getIndex() == id){
// return t;
// }
// }
}
Location* InputData::findLocation(int id){
//if it is sequencial
return instance->location_.at(id - 1);
//else
// for(Location* l : location_){
// if(l->getIndex() == id){
// return l;
// }
// }
}
double InputData::getDistance(int origin, int destination){
return instance->distance_[origin][destination];
}
int InputData::getTime(int origin, int destination){
return instance->time_[origin][destination];
}
<|endoftext|> |
<commit_before>
/* Copyright 2017 - 2022 R. Thomas
* Copyright 2017 - 2022 Quarkslab
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string>
#include "OAT/Structures.hpp"
#include "LIEF/OAT/utils.hpp"
#include "LIEF/ELF/Binary.hpp"
#include "LIEF/ELF/Parser.hpp"
#include "LIEF/ELF/Symbol.hpp"
#include "LIEF/ELF/utils.hpp"
namespace LIEF {
namespace OAT {
bool is_oat(const std::string& file) {
if (!ELF::is_elf(file)) {
return false;
}
try {
if (const auto elf_binary = ELF::Parser::parse(file)) {
return is_oat(*elf_binary);
}
} catch (const exception&) {
return false;
}
return false;
}
bool is_oat(const std::vector<uint8_t>& raw) {
try {
if (const auto elf_binary = ELF::Parser::parse(raw)) {
return is_oat(*elf_binary);
}
} catch (const exception&) {
return false;
}
return false;
}
bool is_oat(const ELF::Binary& elf) {
if (const auto* oatdata = elf.get_dynamic_symbol("oatdata")) {
const std::vector<uint8_t>& header = elf.get_content_from_virtual_address(oatdata->value(), sizeof(details::oat_magic));
return std::equal(std::begin(header), std::end(header),
std::begin(details::oat_magic));
}
return false;
}
oat_version_t version(const std::string& file) {
if (!is_oat(file)) {
return 0;
}
std::unique_ptr<const ELF::Binary> elf_binary;
try {
if (const auto elf = ELF::Parser::parse(file)) {
return version(*elf_binary);
}
} catch (const exception&) {
return 0;
}
return 0;
}
oat_version_t version(const std::vector<uint8_t>& raw) {
if (!is_oat(raw)) {
return 0;
}
std::unique_ptr<const ELF::Binary> elf_binary;
try {
if (const auto elf = ELF::Parser::parse(raw)) {
return version(*elf_binary);
}
} catch (const exception&) {
return 0;
}
return 0;
}
oat_version_t version(const ELF::Binary& elf) {
if (const auto* oatdata = elf.get_dynamic_symbol("oatdata")) {
const std::vector<uint8_t>& header = elf.get_content_from_virtual_address(oatdata->value() + sizeof(details::oat_magic), sizeof(details::oat_version));
if (header.size() != sizeof(details::oat_version)) {
return 0;
}
return std::stoul(std::string(reinterpret_cast<const char*>(header.data()), 3));
}
return 0;
}
Android::ANDROID_VERSIONS android_version(oat_version_t version) {
static const std::map<oat_version_t, Android::ANDROID_VERSIONS> oat2android {
{ 64, Android::ANDROID_VERSIONS::VERSION_601 },
{ 79, Android::ANDROID_VERSIONS::VERSION_700 },
{ 88, Android::ANDROID_VERSIONS::VERSION_712 },
{ 124, Android::ANDROID_VERSIONS::VERSION_800 },
{ 131, Android::ANDROID_VERSIONS::VERSION_810 },
{ 138, Android::ANDROID_VERSIONS::VERSION_900 },
};
auto it = oat2android.lower_bound(version);
return it == oat2android.end() ? Android::ANDROID_VERSIONS::VERSION_UNKNOWN : it->second;
}
} // namespace OAT
} // namespace LIEF
<commit_msg>Resolve #684<commit_after>
/* Copyright 2017 - 2022 R. Thomas
* Copyright 2017 - 2022 Quarkslab
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string>
#include "OAT/Structures.hpp"
#include "LIEF/OAT/utils.hpp"
#include "LIEF/ELF/Binary.hpp"
#include "LIEF/ELF/Parser.hpp"
#include "LIEF/ELF/Symbol.hpp"
#include "LIEF/ELF/utils.hpp"
namespace LIEF {
namespace OAT {
bool is_oat(const std::string& file) {
if (!ELF::is_elf(file)) {
return false;
}
try {
if (const auto elf_binary = ELF::Parser::parse(file)) {
return is_oat(*elf_binary);
}
} catch (const exception&) {
return false;
}
return false;
}
bool is_oat(const std::vector<uint8_t>& raw) {
try {
if (const auto elf_binary = ELF::Parser::parse(raw)) {
return is_oat(*elf_binary);
}
} catch (const exception&) {
return false;
}
return false;
}
bool is_oat(const ELF::Binary& elf) {
if (const auto* oatdata = elf.get_dynamic_symbol("oatdata")) {
const std::vector<uint8_t>& header = elf.get_content_from_virtual_address(oatdata->value(), sizeof(details::oat_magic));
return std::equal(std::begin(header), std::end(header),
std::begin(details::oat_magic));
}
return false;
}
oat_version_t version(const std::string& file) {
if (!is_oat(file)) {
return 0;
}
try {
if (const auto elf = ELF::Parser::parse(file)) {
return version(*elf);
}
} catch (const exception&) {
return 0;
}
return 0;
}
oat_version_t version(const std::vector<uint8_t>& raw) {
if (!is_oat(raw)) {
return 0;
}
try {
if (const auto elf = ELF::Parser::parse(raw)) {
return version(*elf);
}
} catch (const exception&) {
return 0;
}
return 0;
}
oat_version_t version(const ELF::Binary& elf) {
if (const auto* oatdata = elf.get_dynamic_symbol("oatdata")) {
const std::vector<uint8_t>& header = elf.get_content_from_virtual_address(oatdata->value() + sizeof(details::oat_magic), sizeof(details::oat_version));
if (header.size() != sizeof(details::oat_version)) {
return 0;
}
return std::stoul(std::string(reinterpret_cast<const char*>(header.data()), 3));
}
return 0;
}
Android::ANDROID_VERSIONS android_version(oat_version_t version) {
static const std::map<oat_version_t, Android::ANDROID_VERSIONS> oat2android {
{ 64, Android::ANDROID_VERSIONS::VERSION_601 },
{ 79, Android::ANDROID_VERSIONS::VERSION_700 },
{ 88, Android::ANDROID_VERSIONS::VERSION_712 },
{ 124, Android::ANDROID_VERSIONS::VERSION_800 },
{ 131, Android::ANDROID_VERSIONS::VERSION_810 },
{ 138, Android::ANDROID_VERSIONS::VERSION_900 },
};
auto it = oat2android.lower_bound(version);
return it == oat2android.end() ? Android::ANDROID_VERSIONS::VERSION_UNKNOWN : it->second;
}
} // namespace OAT
} // namespace LIEF
<|endoftext|> |
<commit_before>/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.70
Copyright (C) 2018 GOMC Group
A copy of the GNU General Public License can be found in the COPYRIGHT.txt
along with this program, also can be found at <http://www.gnu.org/licenses/>.
********************************************************************************/
#include <stdint.h>
#include "CheckpointOutput.h"
#include "MoleculeLookup.h"
#include "System.h"
#include "GOMC_Config.h"
#include "Endian.h"
namespace
{
union dbl_output_union {
char bin_value[8];
double dbl_value;
};
union uint32_output_union {
char bin_value[4];
uint32_t uint_value;
};
union uint64_output_union {
char bin_value[8];
uint64_t uint_value;
};
union int8_input_union {
char bin_value[1];
int8_t int_value;
};
}
CheckpointOutput::CheckpointOutput(System & sys, StaticVals const& statV) :
moveSetRef(sys.moveSettings), molLookupRef(sys.molLookupRef),
boxDimRef(sys.boxDimRef), molRef(statV.mol), prngRef(sys.prng),
coordCurrRef(sys.coordinates),
#if GOMC_LIB_MPI
prngPTRef(*sys.prngParallelTemp),
enableParallelTempering(sys.ms->parallelTemperingEnabled)
#else
enableParallelTempering(false)
#endif
{
outputFile = NULL;
}
void CheckpointOutput::Init(pdb_setup::Atoms const& atoms,
config_setup::Output const& output)
{
enableOutCheckpoint = output.restart.settings.enable;
stepsPerCheckpoint = output.restart.settings.frequency;
std::string file = output.statistics.settings.uniqueStr.val + "_restart.chk";
#if GOMC_LIB_MPI
filename = pathToReplicaOutputDirectory + file;
#else
filename = file;
#endif
}
void CheckpointOutput::DoOutput(const ulong step)
{
if(enableOutCheckpoint) {
std::cout << "Writing checkpoint to file " << filename << " at step " << step+1 << "\n";
openOutputFile();
printGOMCVersion();
printStepNumber(step);
printRandomNumbers();
printMoleculeLookupData();
printMoveSettingsData();
printMoleculesData();
#if GOMC_LIB_MPI
printParallelTemperingBoolean();
if(enableParallelTempering)
printRandomNumbersParallelTempering();
#endif
std::cout << "Checkpoint saved to " << filename << std::endl;
}
}
void CheckpointOutput::setGOMCVersion()
{
sprintf(gomc_version, "%d.%02d\0", GOMC_VERSION_MAJOR, GOMC_VERSION_MINOR % 100);
}
void CheckpointOutput::printGOMCVersion()
{
setGOMCVersion();
fprintf(outputFile, "%c%s%c", '$', gomc_version, '$');
}
void CheckpointOutput::printParallelTemperingBoolean()
{
int8_t s = (int8_t) enableParallelTempering;
write_uint8_binary(s);
}
void CheckpointOutput::printStepNumber(const ulong step)
{
write_uint64_binary(step+1);
}
void CheckpointOutput::printRandomNumbers()
{
// First let's save the state array inside prng
// the length of the array is 624
// there is a save function inside MersenneTwister.h file
// to read back we can use the load function
const int N = 624;
// The MT::save function also appends the "left" variable,
// so need to allocate one more array element
uint32_t* saveArray = new uint32_t[N + 1];
prngRef.GetGenerator()->save(saveArray);
for(int i = 0; i < N; i++) {
write_uint32_binary(saveArray[i]);
}
// Save the location of pointer in state
uint32_t location = prngRef.GetGenerator()->pNext -
prngRef.GetGenerator()->state;
write_uint32_binary(location);
// save the "left" value so we can restore it later
write_uint32_binary(prngRef.GetGenerator()->left);
// let's save seedValue just in case
// not sure if that is used or not, or how important it is
write_uint32_binary(prngRef.GetGenerator()->seedValue);
delete[] saveArray;
}
#if GOMC_LIB_MPI
void CheckpointOutput::printRandomNumbersParallelTempering()
{
// First let's save the state array inside prng
// the length of the array is 624
// there is a save function inside MersenneTwister.h file
// to read back we can use the load function
const int N = 624;
uint32_t* saveArray = new uint32_t[N];
prngPTRef.GetGenerator()->save(saveArray);
for(int i = 0; i < N; i++) {
write_uint32_binary(saveArray[i]);
}
// Save the location of pointer in state
uint32_t location = prngPTRef.GetGenerator()->pNext -
prngPTRef.GetGenerator()->state;
write_uint32_binary(location);
// save the "left" value so we can restore it later
write_uint32_binary(prngPTRef.GetGenerator()->left);
// let's save seedValue just in case
// not sure if that is used or not, or how important it is
write_uint32_binary(prngPTRef.GetGenerator()->seedValue);
}
#endif
void CheckpointOutput::printMoleculeLookupData()
{
// print the size of molLookup array
write_uint32_binary(molLookupRef.molLookupCount);
// print the molLookup array itself
for(int i = 0; i < (int) molLookupRef.molLookupCount; i++) {
write_uint32_binary(molLookupRef.molLookup[i]);
}
// print the size of boxAndKindStart array
write_uint32_binary(molLookupRef.boxAndKindStartCount);
// print the BoxAndKindStart array
for(int i = 0; i < (int) molLookupRef.boxAndKindStartCount; i++) {
write_uint32_binary(molLookupRef.boxAndKindStart[i]);
}
// print numKinds
write_uint32_binary(molLookupRef.numKinds);
//print the size of fixedAtom array
write_uint32_binary((uint)molLookupRef.fixedAtom.size());
//print the fixedAtom array itself
for(int i = 0; i < (int) molLookupRef.fixedAtom.size(); i++) {
write_uint32_binary(molLookupRef.fixedAtom[i]);
}
}
void CheckpointOutput::printMoleculesData()
{
// print the start of each molecule
// there is an extra one at the end which store the total count
// that is used for to calculate the length of molecule
// so the length of last molecule can be calculated using
// start[molIndex+1]-start[molIndex]
write_uint32_binary(molRef.count);
for(int i = 0; i < (int)molRef.count+1; i++) {
write_uint32_binary(molRef.start[i]);
}
// print the start of each kind
write_uint32_binary(molRef.kIndexCount);
for(int i = 0; i < (int)molRef.kIndexCount; i++) {
write_uint32_binary(molRef.kIndex[i]);
}
}
void CheckpointOutput::printMoveSettingsData()
{
printVector3DDouble(moveSetRef.scale);
printVector3DDouble(moveSetRef.acceptPercent);
printVector3DUint(moveSetRef.accepted);
printVector3DUint(moveSetRef.tries);
printVector3DUint(moveSetRef.tempAccepted);
printVector3DUint(moveSetRef.tempTries);
printVector2DUint(moveSetRef.mp_tries);
printVector2DUint(moveSetRef.mp_accepted);
printVector1DDouble(moveSetRef.mp_t_max);
printVector1DDouble(moveSetRef.mp_r_max);
}
void CheckpointOutput::printVector3DDouble(std::vector< std::vector< std::vector<double> > > data)
{
// print size of tempTries
ulong size_x = data.size();
ulong size_y = data[0].size();
ulong size_z = data[0][0].size();
write_uint64_binary(size_x);
write_uint64_binary(size_y);
write_uint64_binary(size_z);
// print tempTries array
for(int i = 0; i < (int) size_x; i++) {
for(int j = 0; j < (int) size_y; j++) {
for(int k = 0; k < (int) size_z; k++) {
write_double_binary(data[i][j][k]);
}
}
}
}
void CheckpointOutput::printVector3DUint(std::vector< std::vector< std::vector<uint> > > data)
{
// print size of tempTries
ulong size_x = data.size();
ulong size_y = data[0].size();
ulong size_z = data[0][0].size();
write_uint64_binary(size_x);
write_uint64_binary(size_y);
write_uint64_binary(size_z);
// print tempTries array
for(int i = 0; i < (int) size_x; i++) {
for(int j = 0; j < (int) size_y; j++) {
for(int k = 0; k < (int) size_z; k++) {
write_uint32_binary(data[i][j][k]);
}
}
}
}
void CheckpointOutput::printVector2DUint(std::vector< std::vector< uint > > data)
{
// print size of array
ulong size_x = data.size();
ulong size_y = data[0].size();
write_uint64_binary(size_x);
write_uint64_binary(size_y);
// print array itself
for(int i = 0; i < (int) size_x; i++) {
for(int j = 0; j < (int) size_y; j++) {
write_uint32_binary(data[i][j]);
}
}
}
void CheckpointOutput::printVector1DDouble(std::vector< double > data)
{
// print size of array
ulong size_x = data.size();
write_uint64_binary(size_x);
// print array itself
for(int i = 0; i < (int) size_x; i++) {
write_double_binary(data[i]);
}
}
void CheckpointOutput::openOutputFile()
{
outputFile = fopen(filename.c_str(), "wb");
if(outputFile == NULL) {
fprintf(stderr, "Error opening checkpoint output file %s\n",
filename.c_str());
exit(EXIT_FAILURE);
}
}
void CheckpointOutput::write_double_binary(double data)
{
if(outputFile == NULL) {
fprintf(stderr, "Error opening checkpoint output file %s\n",
filename.c_str());
exit(EXIT_FAILURE);
}
dbl_output_union temp;
temp.dbl_value = data;
fprintf(outputFile, "%c%c%c%c%c%c%c%c",
temp.bin_value[0],
temp.bin_value[1],
temp.bin_value[2],
temp.bin_value[3],
temp.bin_value[4],
temp.bin_value[5],
temp.bin_value[6],
temp.bin_value[7]);
fflush(outputFile);
}
void CheckpointOutput::write_uint8_binary(int8_t data)
{
if(outputFile == NULL) {
fprintf(stderr, "Error opening checkpoint output file %s\n",
filename.c_str());
exit(EXIT_FAILURE);
}
int8_input_union temp;
temp.int_value = data;
fprintf(outputFile, "%c",
temp.bin_value[0]);
fflush(outputFile);
}
void CheckpointOutput::write_uint64_binary(uint64_t data)
{
if(outputFile == NULL) {
fprintf(stderr, "Error opening checkpoint output file %s\n",
filename.c_str());
exit(EXIT_FAILURE);
}
uint64_output_union temp;
temp.uint_value = htof64(data);
fprintf(outputFile, "%c%c%c%c%c%c%c%c",
temp.bin_value[0],
temp.bin_value[1],
temp.bin_value[2],
temp.bin_value[3],
temp.bin_value[4],
temp.bin_value[5],
temp.bin_value[6],
temp.bin_value[7]);
fflush(outputFile);
}
void CheckpointOutput::write_uint32_binary(uint32_t data)
{
if(outputFile == NULL) {
fprintf(stderr, "Error opening checkpoint output file %s\n",
filename.c_str());
exit(EXIT_FAILURE);
}
uint32_output_union temp;
temp.uint_value = htof32(data);
fprintf(outputFile, "%c%c%c%c",
temp.bin_value[0],
temp.bin_value[1],
temp.bin_value[2],
temp.bin_value[3]);
fflush(outputFile);
}<commit_msg>sprintf automatically adds null terminating character <commit_after>/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.70
Copyright (C) 2018 GOMC Group
A copy of the GNU General Public License can be found in the COPYRIGHT.txt
along with this program, also can be found at <http://www.gnu.org/licenses/>.
********************************************************************************/
#include <stdint.h>
#include "CheckpointOutput.h"
#include "MoleculeLookup.h"
#include "System.h"
#include "GOMC_Config.h"
#include "Endian.h"
namespace
{
union dbl_output_union {
char bin_value[8];
double dbl_value;
};
union uint32_output_union {
char bin_value[4];
uint32_t uint_value;
};
union uint64_output_union {
char bin_value[8];
uint64_t uint_value;
};
union int8_input_union {
char bin_value[1];
int8_t int_value;
};
}
CheckpointOutput::CheckpointOutput(System & sys, StaticVals const& statV) :
moveSetRef(sys.moveSettings), molLookupRef(sys.molLookupRef),
boxDimRef(sys.boxDimRef), molRef(statV.mol), prngRef(sys.prng),
coordCurrRef(sys.coordinates),
#if GOMC_LIB_MPI
prngPTRef(*sys.prngParallelTemp),
enableParallelTempering(sys.ms->parallelTemperingEnabled)
#else
enableParallelTempering(false)
#endif
{
outputFile = NULL;
}
void CheckpointOutput::Init(pdb_setup::Atoms const& atoms,
config_setup::Output const& output)
{
enableOutCheckpoint = output.restart.settings.enable;
stepsPerCheckpoint = output.restart.settings.frequency;
std::string file = output.statistics.settings.uniqueStr.val + "_restart.chk";
#if GOMC_LIB_MPI
filename = pathToReplicaOutputDirectory + file;
#else
filename = file;
#endif
}
void CheckpointOutput::DoOutput(const ulong step)
{
if(enableOutCheckpoint) {
std::cout << "Writing checkpoint to file " << filename << " at step " << step+1 << "\n";
openOutputFile();
printGOMCVersion();
printStepNumber(step);
printRandomNumbers();
printMoleculeLookupData();
printMoveSettingsData();
printMoleculesData();
#if GOMC_LIB_MPI
printParallelTemperingBoolean();
if(enableParallelTempering)
printRandomNumbersParallelTempering();
#endif
std::cout << "Checkpoint saved to " << filename << std::endl;
}
}
void CheckpointOutput::setGOMCVersion()
{
sprintf(gomc_version, "%d.%02d", GOMC_VERSION_MAJOR, GOMC_VERSION_MINOR % 100);
}
void CheckpointOutput::printGOMCVersion()
{
setGOMCVersion();
fprintf(outputFile, "%c%s%c", '$', gomc_version, '$');
}
void CheckpointOutput::printParallelTemperingBoolean()
{
int8_t s = (int8_t) enableParallelTempering;
write_uint8_binary(s);
}
void CheckpointOutput::printStepNumber(const ulong step)
{
write_uint64_binary(step+1);
}
void CheckpointOutput::printRandomNumbers()
{
// First let's save the state array inside prng
// the length of the array is 624
// there is a save function inside MersenneTwister.h file
// to read back we can use the load function
const int N = 624;
// The MT::save function also appends the "left" variable,
// so need to allocate one more array element
uint32_t* saveArray = new uint32_t[N + 1];
prngRef.GetGenerator()->save(saveArray);
for(int i = 0; i < N; i++) {
write_uint32_binary(saveArray[i]);
}
// Save the location of pointer in state
uint32_t location = prngRef.GetGenerator()->pNext -
prngRef.GetGenerator()->state;
write_uint32_binary(location);
// save the "left" value so we can restore it later
write_uint32_binary(prngRef.GetGenerator()->left);
// let's save seedValue just in case
// not sure if that is used or not, or how important it is
write_uint32_binary(prngRef.GetGenerator()->seedValue);
delete[] saveArray;
}
#if GOMC_LIB_MPI
void CheckpointOutput::printRandomNumbersParallelTempering()
{
// First let's save the state array inside prng
// the length of the array is 624
// there is a save function inside MersenneTwister.h file
// to read back we can use the load function
const int N = 624;
uint32_t* saveArray = new uint32_t[N];
prngPTRef.GetGenerator()->save(saveArray);
for(int i = 0; i < N; i++) {
write_uint32_binary(saveArray[i]);
}
// Save the location of pointer in state
uint32_t location = prngPTRef.GetGenerator()->pNext -
prngPTRef.GetGenerator()->state;
write_uint32_binary(location);
// save the "left" value so we can restore it later
write_uint32_binary(prngPTRef.GetGenerator()->left);
// let's save seedValue just in case
// not sure if that is used or not, or how important it is
write_uint32_binary(prngPTRef.GetGenerator()->seedValue);
}
#endif
void CheckpointOutput::printMoleculeLookupData()
{
// print the size of molLookup array
write_uint32_binary(molLookupRef.molLookupCount);
// print the molLookup array itself
for(int i = 0; i < (int) molLookupRef.molLookupCount; i++) {
write_uint32_binary(molLookupRef.molLookup[i]);
}
// print the size of boxAndKindStart array
write_uint32_binary(molLookupRef.boxAndKindStartCount);
// print the BoxAndKindStart array
for(int i = 0; i < (int) molLookupRef.boxAndKindStartCount; i++) {
write_uint32_binary(molLookupRef.boxAndKindStart[i]);
}
// print numKinds
write_uint32_binary(molLookupRef.numKinds);
//print the size of fixedAtom array
write_uint32_binary((uint)molLookupRef.fixedAtom.size());
//print the fixedAtom array itself
for(int i = 0; i < (int) molLookupRef.fixedAtom.size(); i++) {
write_uint32_binary(molLookupRef.fixedAtom[i]);
}
}
void CheckpointOutput::printMoleculesData()
{
// print the start of each molecule
// there is an extra one at the end which store the total count
// that is used for to calculate the length of molecule
// so the length of last molecule can be calculated using
// start[molIndex+1]-start[molIndex]
write_uint32_binary(molRef.count);
for(int i = 0; i < (int)molRef.count+1; i++) {
write_uint32_binary(molRef.start[i]);
}
// print the start of each kind
write_uint32_binary(molRef.kIndexCount);
for(int i = 0; i < (int)molRef.kIndexCount; i++) {
write_uint32_binary(molRef.kIndex[i]);
}
}
void CheckpointOutput::printMoveSettingsData()
{
printVector3DDouble(moveSetRef.scale);
printVector3DDouble(moveSetRef.acceptPercent);
printVector3DUint(moveSetRef.accepted);
printVector3DUint(moveSetRef.tries);
printVector3DUint(moveSetRef.tempAccepted);
printVector3DUint(moveSetRef.tempTries);
printVector2DUint(moveSetRef.mp_tries);
printVector2DUint(moveSetRef.mp_accepted);
printVector1DDouble(moveSetRef.mp_t_max);
printVector1DDouble(moveSetRef.mp_r_max);
}
void CheckpointOutput::printVector3DDouble(std::vector< std::vector< std::vector<double> > > data)
{
// print size of tempTries
ulong size_x = data.size();
ulong size_y = data[0].size();
ulong size_z = data[0][0].size();
write_uint64_binary(size_x);
write_uint64_binary(size_y);
write_uint64_binary(size_z);
// print tempTries array
for(int i = 0; i < (int) size_x; i++) {
for(int j = 0; j < (int) size_y; j++) {
for(int k = 0; k < (int) size_z; k++) {
write_double_binary(data[i][j][k]);
}
}
}
}
void CheckpointOutput::printVector3DUint(std::vector< std::vector< std::vector<uint> > > data)
{
// print size of tempTries
ulong size_x = data.size();
ulong size_y = data[0].size();
ulong size_z = data[0][0].size();
write_uint64_binary(size_x);
write_uint64_binary(size_y);
write_uint64_binary(size_z);
// print tempTries array
for(int i = 0; i < (int) size_x; i++) {
for(int j = 0; j < (int) size_y; j++) {
for(int k = 0; k < (int) size_z; k++) {
write_uint32_binary(data[i][j][k]);
}
}
}
}
void CheckpointOutput::printVector2DUint(std::vector< std::vector< uint > > data)
{
// print size of array
ulong size_x = data.size();
ulong size_y = data[0].size();
write_uint64_binary(size_x);
write_uint64_binary(size_y);
// print array itself
for(int i = 0; i < (int) size_x; i++) {
for(int j = 0; j < (int) size_y; j++) {
write_uint32_binary(data[i][j]);
}
}
}
void CheckpointOutput::printVector1DDouble(std::vector< double > data)
{
// print size of array
ulong size_x = data.size();
write_uint64_binary(size_x);
// print array itself
for(int i = 0; i < (int) size_x; i++) {
write_double_binary(data[i]);
}
}
void CheckpointOutput::openOutputFile()
{
outputFile = fopen(filename.c_str(), "wb");
if(outputFile == NULL) {
fprintf(stderr, "Error opening checkpoint output file %s\n",
filename.c_str());
exit(EXIT_FAILURE);
}
}
void CheckpointOutput::write_double_binary(double data)
{
if(outputFile == NULL) {
fprintf(stderr, "Error opening checkpoint output file %s\n",
filename.c_str());
exit(EXIT_FAILURE);
}
dbl_output_union temp;
temp.dbl_value = data;
fprintf(outputFile, "%c%c%c%c%c%c%c%c",
temp.bin_value[0],
temp.bin_value[1],
temp.bin_value[2],
temp.bin_value[3],
temp.bin_value[4],
temp.bin_value[5],
temp.bin_value[6],
temp.bin_value[7]);
fflush(outputFile);
}
void CheckpointOutput::write_uint8_binary(int8_t data)
{
if(outputFile == NULL) {
fprintf(stderr, "Error opening checkpoint output file %s\n",
filename.c_str());
exit(EXIT_FAILURE);
}
int8_input_union temp;
temp.int_value = data;
fprintf(outputFile, "%c",
temp.bin_value[0]);
fflush(outputFile);
}
void CheckpointOutput::write_uint64_binary(uint64_t data)
{
if(outputFile == NULL) {
fprintf(stderr, "Error opening checkpoint output file %s\n",
filename.c_str());
exit(EXIT_FAILURE);
}
uint64_output_union temp;
temp.uint_value = htof64(data);
fprintf(outputFile, "%c%c%c%c%c%c%c%c",
temp.bin_value[0],
temp.bin_value[1],
temp.bin_value[2],
temp.bin_value[3],
temp.bin_value[4],
temp.bin_value[5],
temp.bin_value[6],
temp.bin_value[7]);
fflush(outputFile);
}
void CheckpointOutput::write_uint32_binary(uint32_t data)
{
if(outputFile == NULL) {
fprintf(stderr, "Error opening checkpoint output file %s\n",
filename.c_str());
exit(EXIT_FAILURE);
}
uint32_output_union temp;
temp.uint_value = htof32(data);
fprintf(outputFile, "%c%c%c%c",
temp.bin_value[0],
temp.bin_value[1],
temp.bin_value[2],
temp.bin_value[3]);
fflush(outputFile);
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting 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 "libpc/PointData.hpp"
#include <cassert>
#include <iostream>
#include <numeric>
using std::string;
namespace libpc
{
PointData::PointData(const SchemaLayout& schemaLayout, boost::uint32_t numPoints) :
m_schemaLayout(schemaLayout),
m_data(NULL),
m_pointSize(m_schemaLayout.getByteSize()),
m_numPoints(numPoints),
m_isValid(numPoints)
{
m_data = new boost::uint8_t[m_pointSize * m_numPoints];
// the points will all be set to invalid here
m_isValid.assign(0, m_isValid.size());
return;
}
PointData::~PointData()
{
if (m_data)
delete[] m_data;
}
bool
PointData::isValid(std::size_t index) const
{
return static_cast<bool>(m_isValid[index]);
}
bool PointData::allValid() const
{
valid_mask_type::size_type i = 0;
while(i < m_isValid.size())
{
if (m_isValid[i] != 1) return false;
i++;
}
return true;
}
void
PointData::setValid(std::size_t index, bool value)
{
m_isValid[index] = static_cast<bool>(value);
}
boost::uint8_t* PointData::getData(std::size_t index) const
{
return m_data + m_pointSize * index;
}
boost::uint32_t PointData::getNumPoints() const
{
return m_numPoints;
}
void PointData::copyPointFast(std::size_t destPointIndex, std::size_t srcPointIndex, const PointData& srcPointData)
{
assert(getSchemaLayout() == srcPointData.getSchemaLayout());
boost::uint8_t* src = srcPointData.getData(srcPointIndex);
boost::uint8_t* dest = getData(destPointIndex);
std::size_t len = getSchemaLayout().getByteSize();
memcpy(dest, src, len);
setValid(destPointIndex, srcPointData.isValid(srcPointIndex));
return;
}
void PointData::copyPointsFast(std::size_t destPointIndex, std::size_t srcPointIndex, const PointData& srcPointData, std::size_t numPoints)
{
assert(getSchemaLayout() == srcPointData.getSchemaLayout());
boost::uint8_t* src = srcPointData.getData(srcPointIndex);
boost::uint8_t* dest = getData(destPointIndex);
std::size_t len = getSchemaLayout().getByteSize();
memcpy(dest, src, len * numPoints);
if (srcPointData.allValid())
{
m_isValid.assign(1, m_isValid.size());
}
else
{
for (valid_mask_type::size_type i=0; i<numPoints; i++)
{
setValid(destPointIndex+i, srcPointData.isValid(srcPointIndex+i));
}
}
return;
}
std::ostream& operator<<(std::ostream& ostr, const PointData& pointData)
{
using std::endl;
const SchemaLayout& schemaLayout = pointData.getSchemaLayout();
const std::vector<DimensionLayout>& dimensionLayouts = schemaLayout.getDimensionLayouts();
const std::size_t numPoints = pointData.getNumPoints();
int cnt = 0;
for (boost::uint32_t pointIndex=0; pointIndex<numPoints; pointIndex++)
{
if (pointData.isValid(pointIndex))
++cnt;
}
ostr << "Contains " << cnt << " valid points (" << pointData.getNumPoints() << " total)" << endl;
for (boost::uint32_t pointIndex=0; pointIndex<numPoints; pointIndex++)
{
if (!pointData.isValid(pointIndex)) continue;
ostr << "Point: " << pointIndex << endl;
for (SchemaLayout::DimensionLayoutsCIter citer=dimensionLayouts.begin(); citer != dimensionLayouts.end(); ++citer)
{
const DimensionLayout& dimensionLayout = *citer;
const Dimension& dimension = dimensionLayout.getDimension();
std::size_t fieldIndex = dimensionLayout.getPosition();
ostr << dimension.getFieldName() << " (" << dimension.getDataTypeName(dimension.getDataType()) << ") : ";
switch (dimension.getDataType())
{
case Dimension::Int8:
ostr << (int)(pointData.getField<boost::int8_t>(pointIndex, fieldIndex));
break;
case Dimension::Uint8:
ostr << (int)(pointData.getField<boost::uint8_t>(pointIndex, fieldIndex));
break;
case Dimension::Int16:
ostr << pointData.getField<boost::int16_t>(pointIndex, fieldIndex);
break;
case Dimension::Uint16:
ostr << pointData.getField<boost::uint16_t>(pointIndex, fieldIndex);
break;
case Dimension::Int32:
ostr << pointData.getField<boost::int32_t>(pointIndex, fieldIndex);
break;
case Dimension::Uint32:
ostr << pointData.getField<boost::uint32_t>(pointIndex, fieldIndex);
break;
case Dimension::Int64:
ostr << pointData.getField<boost::int64_t>(pointIndex, fieldIndex);
break;
case Dimension::Uint64:
ostr << pointData.getField<boost::uint64_t>(pointIndex, fieldIndex);
break;
case Dimension::Float:
ostr << pointData.getField<float>(pointIndex, fieldIndex);
break;
case Dimension::Double:
ostr << pointData.getField<double>(pointIndex, fieldIndex);
break;
default:
throw;
}
ostr << endl;
}
}
return ostr;
}
} // namespace libpc
<commit_msg>fix argument order<commit_after>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting 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 "libpc/PointData.hpp"
#include <cassert>
#include <iostream>
#include <numeric>
using std::string;
namespace libpc
{
PointData::PointData(const SchemaLayout& schemaLayout, boost::uint32_t numPoints) :
m_schemaLayout(schemaLayout),
m_data(NULL),
m_pointSize(m_schemaLayout.getByteSize()),
m_numPoints(numPoints),
m_isValid(numPoints)
{
m_data = new boost::uint8_t[m_pointSize * m_numPoints];
// the points will all be set to invalid here
m_isValid.assign(m_isValid.size(), 0);
return;
}
PointData::~PointData()
{
if (m_data)
delete[] m_data;
}
bool
PointData::isValid(std::size_t index) const
{
return static_cast<bool>(m_isValid[index]);
}
bool PointData::allValid() const
{
valid_mask_type::size_type i = 0;
while(i < m_isValid.size())
{
if (m_isValid[i] != 1) return false;
i++;
}
return true;
}
void
PointData::setValid(std::size_t index, bool value)
{
m_isValid[index] = static_cast<bool>(value);
}
boost::uint8_t* PointData::getData(std::size_t index) const
{
return m_data + m_pointSize * index;
}
boost::uint32_t PointData::getNumPoints() const
{
return m_numPoints;
}
void PointData::copyPointFast(std::size_t destPointIndex, std::size_t srcPointIndex, const PointData& srcPointData)
{
assert(getSchemaLayout() == srcPointData.getSchemaLayout());
boost::uint8_t* src = srcPointData.getData(srcPointIndex);
boost::uint8_t* dest = getData(destPointIndex);
std::size_t len = getSchemaLayout().getByteSize();
memcpy(dest, src, len);
setValid(destPointIndex, srcPointData.isValid(srcPointIndex));
return;
}
void PointData::copyPointsFast(std::size_t destPointIndex, std::size_t srcPointIndex, const PointData& srcPointData, std::size_t numPoints)
{
assert(getSchemaLayout() == srcPointData.getSchemaLayout());
boost::uint8_t* src = srcPointData.getData(srcPointIndex);
boost::uint8_t* dest = getData(destPointIndex);
std::size_t len = getSchemaLayout().getByteSize();
memcpy(dest, src, len * numPoints);
if (srcPointData.allValid())
{
m_isValid.assign(1, m_isValid.size());
}
else
{
for (valid_mask_type::size_type i=0; i<numPoints; i++)
{
setValid(destPointIndex+i, srcPointData.isValid(srcPointIndex+i));
}
}
return;
}
std::ostream& operator<<(std::ostream& ostr, const PointData& pointData)
{
using std::endl;
const SchemaLayout& schemaLayout = pointData.getSchemaLayout();
const std::vector<DimensionLayout>& dimensionLayouts = schemaLayout.getDimensionLayouts();
const std::size_t numPoints = pointData.getNumPoints();
int cnt = 0;
for (boost::uint32_t pointIndex=0; pointIndex<numPoints; pointIndex++)
{
if (pointData.isValid(pointIndex))
++cnt;
}
ostr << "Contains " << cnt << " valid points (" << pointData.getNumPoints() << " total)" << endl;
for (boost::uint32_t pointIndex=0; pointIndex<numPoints; pointIndex++)
{
if (!pointData.isValid(pointIndex)) continue;
ostr << "Point: " << pointIndex << endl;
for (SchemaLayout::DimensionLayoutsCIter citer=dimensionLayouts.begin(); citer != dimensionLayouts.end(); ++citer)
{
const DimensionLayout& dimensionLayout = *citer;
const Dimension& dimension = dimensionLayout.getDimension();
std::size_t fieldIndex = dimensionLayout.getPosition();
ostr << dimension.getFieldName() << " (" << dimension.getDataTypeName(dimension.getDataType()) << ") : ";
switch (dimension.getDataType())
{
case Dimension::Int8:
ostr << (int)(pointData.getField<boost::int8_t>(pointIndex, fieldIndex));
break;
case Dimension::Uint8:
ostr << (int)(pointData.getField<boost::uint8_t>(pointIndex, fieldIndex));
break;
case Dimension::Int16:
ostr << pointData.getField<boost::int16_t>(pointIndex, fieldIndex);
break;
case Dimension::Uint16:
ostr << pointData.getField<boost::uint16_t>(pointIndex, fieldIndex);
break;
case Dimension::Int32:
ostr << pointData.getField<boost::int32_t>(pointIndex, fieldIndex);
break;
case Dimension::Uint32:
ostr << pointData.getField<boost::uint32_t>(pointIndex, fieldIndex);
break;
case Dimension::Int64:
ostr << pointData.getField<boost::int64_t>(pointIndex, fieldIndex);
break;
case Dimension::Uint64:
ostr << pointData.getField<boost::uint64_t>(pointIndex, fieldIndex);
break;
case Dimension::Float:
ostr << pointData.getField<float>(pointIndex, fieldIndex);
break;
case Dimension::Double:
ostr << pointData.getField<double>(pointIndex, fieldIndex);
break;
default:
throw;
}
ostr << endl;
}
}
return ostr;
}
} // namespace libpc
<|endoftext|> |
<commit_before>#include "ClientConnection.hpp"
namespace et {
const int NULL_CLIENT_ID = -1;
ClientConnection::ClientConnection(
std::shared_ptr<SocketHandler> _socketHandler, //
const std::string& _hostname, //
int _port, //
const string& _key)
: Connection(_socketHandler, _key), //
hostname(_hostname), //
port(_port) {}
ClientConnection::~ClientConnection() {
if (reconnectThread) {
reconnectThread->join();
reconnectThread.reset();
}
}
void ClientConnection::connect() {
try {
VLOG(1) << "Connecting" << endl;
socketFd = socketHandler->connect(hostname, port);
VLOG(1) << "Sending null id" << endl;
et::ConnectRequest request;
request.set_clientid(NULL_CLIENT_ID);
socketHandler->writeProto(socketFd, request);
VLOG(1) << "Receiving client id" << endl;
et::ConnectResponse response =
socketHandler->readProto<et::ConnectResponse>(socketFd);
clientId = response.clientid();
VLOG(1) << "Creating backed reader" << endl;
reader = std::shared_ptr<BackedReader>(new BackedReader(
socketHandler, shared_ptr<CryptoHandler>(new CryptoHandler(key)),
socketFd));
VLOG(1) << "Creating backed writer" << endl;
writer = std::shared_ptr<BackedWriter>(new BackedWriter(
socketHandler, shared_ptr<CryptoHandler>(new CryptoHandler(key)),
socketFd));
VLOG(1) << "Client Connection established" << endl;
} catch (const runtime_error& err) {
socketHandler->close(socketFd);
throw err;
}
}
void ClientConnection::closeSocket() {
LOG(INFO) << "Closing socket";
if (reconnectThread.get()) {
reconnectThread->join();
reconnectThread.reset();
}
// Close the socket
Connection::closeSocket();
// Spin up a thread to poll for reconnects
reconnectThread = std::shared_ptr<std::thread>(
new std::thread(&ClientConnection::pollReconnect, this));
}
ssize_t ClientConnection::read(void* buf, size_t count) {
lock_guard<std::mutex> guard(reconnectMutex);
return Connection::read(buf, count);
}
ssize_t ClientConnection::write(const void* buf, size_t count) {
lock_guard<std::mutex> guard(reconnectMutex);
return Connection::write(buf, count);
}
void ClientConnection::pollReconnect() {
while (socketFd == -1) {
{
lock_guard<std::mutex> guard(reconnectMutex);
LOG(INFO) << "Trying to reconnect to " << hostname << ":" << port << endl;
int newSocketFd = socketHandler->connect(hostname, port);
if (newSocketFd != -1) {
et::ConnectRequest request;
request.set_clientid(clientId);
socketHandler->writeProto(newSocketFd, request);
recover(newSocketFd);
}
}
if (socketFd == -1) {
VLOG(1) << "Waiting to retry...";
sleep(1);
}
}
}
}
<commit_msg>Fix bug where closing a connection while trying to reconnect could clobber errno<commit_after>#include "ClientConnection.hpp"
namespace et {
const int NULL_CLIENT_ID = -1;
ClientConnection::ClientConnection(
std::shared_ptr<SocketHandler> _socketHandler, //
const std::string& _hostname, //
int _port, //
const string& _key)
: Connection(_socketHandler, _key), //
hostname(_hostname), //
port(_port) {}
ClientConnection::~ClientConnection() {
if (reconnectThread) {
reconnectThread->join();
reconnectThread.reset();
}
}
void ClientConnection::connect() {
try {
VLOG(1) << "Connecting" << endl;
socketFd = socketHandler->connect(hostname, port);
VLOG(1) << "Sending null id" << endl;
et::ConnectRequest request;
request.set_clientid(NULL_CLIENT_ID);
socketHandler->writeProto(socketFd, request);
VLOG(1) << "Receiving client id" << endl;
et::ConnectResponse response =
socketHandler->readProto<et::ConnectResponse>(socketFd);
clientId = response.clientid();
VLOG(1) << "Creating backed reader" << endl;
reader = std::shared_ptr<BackedReader>(new BackedReader(
socketHandler, shared_ptr<CryptoHandler>(new CryptoHandler(key)),
socketFd));
VLOG(1) << "Creating backed writer" << endl;
writer = std::shared_ptr<BackedWriter>(new BackedWriter(
socketHandler, shared_ptr<CryptoHandler>(new CryptoHandler(key)),
socketFd));
VLOG(1) << "Client Connection established" << endl;
} catch (const runtime_error& err) {
socketHandler->close(socketFd);
throw err;
}
}
void ClientConnection::closeSocket() {
LOG(INFO) << "Closing socket";
if (reconnectThread.get()) {
reconnectThread->join();
reconnectThread.reset();
}
{
// Close the socket
lock_guard<std::mutex> guard(reconnectMutex);
Connection::closeSocket();
}
// Spin up a thread to poll for reconnects
reconnectThread = std::shared_ptr<std::thread>(
new std::thread(&ClientConnection::pollReconnect, this));
}
ssize_t ClientConnection::read(void* buf, size_t count) {
lock_guard<std::mutex> guard(reconnectMutex);
return Connection::read(buf, count);
}
ssize_t ClientConnection::write(const void* buf, size_t count) {
lock_guard<std::mutex> guard(reconnectMutex);
return Connection::write(buf, count);
}
void ClientConnection::pollReconnect() {
while (socketFd == -1) {
{
lock_guard<std::mutex> guard(reconnectMutex);
LOG(INFO) << "Trying to reconnect to " << hostname << ":" << port << endl;
int newSocketFd = socketHandler->connect(hostname, port);
if (newSocketFd != -1) {
et::ConnectRequest request;
request.set_clientid(clientId);
socketHandler->writeProto(newSocketFd, request);
recover(newSocketFd);
}
}
if (socketFd == -1) {
VLOG(1) << "Waiting to retry...";
sleep(1);
}
}
}
}
<|endoftext|> |
<commit_before>#include <memory>
#include "DAutomaton.hpp"
namespace FACore {
template<unsigned int ALPHABET_SIZE>
class DRegularLanguage {
public:
typedef DAutomaton<ALPHABET_SIZE> Machine;
typedef typename Machine::Label Character;
typedef typename Machine::StateId StateId;
constexpr static unsigned int AlphabetSize = ALPHABET_SIZE;
private:
class DigitIterator {
public:
static DigitIterator end() {
return DigitIterator(0);
}
DigitIterator(unsigned int value) : mValue(value)
{}
Character operator* () {
return mValue % ALPHABET_SIZE;
}
DigitIterator& operator++() {
mValue = mValue / ALPHABET_SIZE;
return *this;
}
bool operator==(const DigitIterator &other) {
return mValue == other.mValue;
}
bool operator!=(const DigitIterator &other) {
return !operator==(other);
}
private:
unsigned int mValue;
};
public:
DRegularLanguage(std::shared_ptr<const Machine> automaton, StateId initialState) : mAutomaton(automaton), mInitialState(initialState)
{}
DRegularLanguage(Machine* automaton, StateId initialState) : DRegularLanguage(std::shared_ptr<const Machine>(automaton), initialState)
{}
// These objects are lightweight and dynamic allocating should be avoided.
DRegularLanguage(DRegularLanguage&& other) = default;
template<typename IterType>
bool contains(IterType begin, IterType end) {
StateId currentState = mInitialState;
for(auto iter = begin; iter != end && currentState != mAutomaton->INVALID_STATE(); ++iter) {
Character c = *iter;
currentState = mAutomaton->GetNext(currentState, c);
}
return mAutomaton->IsFinal(currentState);
}
bool contains(unsigned int number) {
return contains(DigitIterator(number), DigitIterator::end());
}
private:
std::shared_ptr<const Machine> mAutomaton;
StateId mInitialState;
};
}<commit_msg>Fixed bug where the old INVALID_STATE() was being used instead of the new constexpr<commit_after>#include <memory>
#include "DAutomaton.hpp"
namespace FACore {
template<unsigned int ALPHABET_SIZE>
class DRegularLanguage {
public:
typedef DAutomaton<ALPHABET_SIZE> Machine;
typedef typename Machine::Label Character;
typedef typename Machine::StateId StateId;
constexpr static unsigned int AlphabetSize = ALPHABET_SIZE;
private:
class DigitIterator {
public:
static DigitIterator end() {
return DigitIterator(0);
}
DigitIterator(unsigned int value) : mValue(value)
{}
Character operator* () {
return mValue % ALPHABET_SIZE;
}
DigitIterator& operator++() {
mValue = mValue / ALPHABET_SIZE;
return *this;
}
bool operator==(const DigitIterator &other) {
return mValue == other.mValue;
}
bool operator!=(const DigitIterator &other) {
return !operator==(other);
}
private:
unsigned int mValue;
};
public:
DRegularLanguage(std::shared_ptr<const Machine> automaton, StateId initialState) : mAutomaton(automaton), mInitialState(initialState)
{}
DRegularLanguage(Machine* automaton, StateId initialState) : DRegularLanguage(std::shared_ptr<const Machine>(automaton), initialState)
{}
// These objects are lightweight and dynamic allocating should be avoided.
DRegularLanguage(DRegularLanguage&& other) = default;
template<typename IterType>
bool contains(IterType begin, IterType end) {
StateId currentState = mInitialState;
for(auto iter = begin; iter != end && currentState != Machine::INVALID_STATE; ++iter) {
Character c = *iter;
currentState = mAutomaton->GetNext(currentState, c);
}
return mAutomaton->IsFinal(currentState);
}
bool contains(unsigned int number) {
return contains(DigitIterator(number), DigitIterator::end());
}
private:
std::shared_ptr<const Machine> mAutomaton;
StateId mInitialState;
};
}<|endoftext|> |
<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 <ctime>
#include <ArgumentList.hpp>
#include <Observation.hpp>
#include <InitializeOpenCL.hpp>
#include <Kernel.hpp>
#include <utils.hpp>
#include <Shifts.hpp>
#include <Dedispersion.hpp>
typedef float dataType;
std::string typeName("float");
int main(int argc, char *argv[]) {
bool print = false;
unsigned int clPlatformID = 0;
unsigned int clDeviceID = 0;
long long unsigned int wrongSamples = 0;
PulsarSearch::DedispersionConf conf;
AstroData::Observation observation;
try {
isa::utils::ArgumentList args(argc, argv);
print = args.getSwitch("-print");
clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");
observation.setPadding(args.getSwitchArgument< unsigned int >("-padding"));
conf.setLocalMem(args.getSwitch("-local"));
conf.setNrSamplesPerBlock(args.getSwitchArgument< unsigned int >("-sb"));
conf.setNrDMsPerBlock(args.getSwitchArgument< unsigned int >("-db"));
conf.setNrSamplesPerThread(args.getSwitchArgument< unsigned int >("-st"));
conf.setNrDMsPerThread(args.getSwitchArgument< unsigned int >("-dt"));
conf.setUnroll(args.getSwitchArgument< unsigned int >("-unroll"));
observation.setFrequencyRange(args.getSwitchArgument< unsigned int >("-channels"), args.getSwitchArgument< float >("-min_freq"), args.getSwitchArgument< float >("-channel_bandwidth"));
observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples"));
observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), args.getSwitchArgument< float >("-dm_first"), args.getSwitchArgument< float >("-dm_step"));
} catch ( isa::utils::SwitchNotFound & err ) {
std::cerr << err.what() << std::endl;
return 1;
}catch ( std::exception & err ) {
std::cerr << "Usage: " << argv[0] << " [-print] -opencl_platform ... -opencl_device ... -padding ... [-local] -sb ... -db ... -st ... -dt ... -unroll ... -min_freq ... -channel_bandwidth ... -samples ... -channels ... -dms ... -dm_first ... -dm_step ..." << 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);
std::vector< float > * shifts = PulsarSearch::getShifts(observation);
observation.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerSecond() + static_cast< unsigned int >((shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep()))) * observation.getNrSamplesPerSecond()));
// Allocate memory
cl::Buffer shifts_d;
std::vector< dataType > dispersedData = std::vector< dataType >(observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel());
cl::Buffer dispersedData_d;
std::vector< dataType > dedispersedData = std::vector< dataType >(observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());
cl::Buffer dedispersedData_d;
std::vector< dataType > controlData = std::vector< dataType >(observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());
try {
shifts_d = cl::Buffer(*clContext, CL_MEM_READ_ONLY, shifts->size() * sizeof(float), 0, 0);
dispersedData_d = cl::Buffer(*clContext, CL_MEM_READ_ONLY, dispersedData.size() * sizeof(dataType), 0, 0);
dedispersedData_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, dedispersedData.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));
for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) {
for ( unsigned int sample = 0; sample < observation.getNrSamplesPerDispersedChannel(); sample++ ) {
dispersedData[(channel * observation.getNrSamplesPerDispersedChannel()) + sample] = static_cast< dataType >(rand() % 10);
}
}
// Copy data structures to device
try {
clQueues->at(clDeviceID)[0].enqueueWriteBuffer(shifts_d, CL_FALSE, 0, shifts->size() * sizeof(float), reinterpret_cast< void * >(shifts->data()), 0, 0);
clQueues->at(clDeviceID)[0].enqueueWriteBuffer(dispersedData_d, CL_FALSE, 0, dispersedData.size() * sizeof(dataType), reinterpret_cast< void * >(dispersedData.data()), 0, 0);
} catch ( cl::Error & err ) {
std::cerr << "OpenCL error H2D transfer: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl;
return 1;
}
// Generate kernel
std::string * code = PulsarSearch::getDedispersionOpenCL(conf, typeName, observation, *shifts);
cl::Kernel * kernel;
if ( print ) {
std::cout << *code << std::endl;
}
try {
kernel = isa::OpenCL::compile("dedispersion", *code, "-cl-mad-enable -Werror", *clContext, clDevices->at(clDeviceID));
} catch ( isa::OpenCL::OpenCLError & err ) {
std::cerr << err.what() << std::endl;
return 1;
}
// Run OpenCL kernel and CPU control
try {
cl::NDRange global(observation.getNrSamplesPerPaddedSecond() / conf.getNrSamplesPerThread(), observation.getNrDMs() / conf.getNrDMsPerThread());
cl::NDRange local(conf.getNrSamplesPerBlock(), conf.getNrDMsPerBlock());
kernel->setArg(0, dispersedData_d);
kernel->setArg(1, dedispersedData_d);
kernel->setArg(2, shifts_d);
clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local);
PulsarSearch::dedispersion< dataType >(observation, dispersedData, controlData, *shifts);
clQueues->at(clDeviceID)[0].enqueueReadBuffer(dedispersedData_d, CL_TRUE, 0, dedispersedData.size() * sizeof(dataType), reinterpret_cast< void * >(dedispersedData.data()));
} catch ( cl::Error & err ) {
std::cerr << "OpenCL error kernel execution: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl;
return 1;
}
for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {
for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {
if ( !isa::utils::same(controlData[(dm * observation.getNrSamplesPerPaddedSecond()) + sample], dedispersedData[(dm * observation.getNrSamplesPerPaddedSecond()) + sample]) ) {
wrongSamples++;
}
}
}
if ( wrongSamples > 0 ) {
std::cout << "Wrong samples: " << wrongSamples << " (" << (wrongSamples * 100.0) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrSamplesPerSecond()) << "%)." << std::endl;
} else {
std::cout << "TEST PASSED." << std::endl;
}
return 0;
}
<commit_msg>Revert "Fixed the bug on the number of samples for dispersed second also for the"<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 <ctime>
#include <ArgumentList.hpp>
#include <Observation.hpp>
#include <InitializeOpenCL.hpp>
#include <Kernel.hpp>
#include <utils.hpp>
#include <Shifts.hpp>
#include <Dedispersion.hpp>
typedef float dataType;
std::string typeName("float");
int main(int argc, char *argv[]) {
bool print = false;
unsigned int clPlatformID = 0;
unsigned int clDeviceID = 0;
long long unsigned int wrongSamples = 0;
PulsarSearch::DedispersionConf conf;
AstroData::Observation observation;
try {
isa::utils::ArgumentList args(argc, argv);
print = args.getSwitch("-print");
clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");
observation.setPadding(args.getSwitchArgument< unsigned int >("-padding"));
conf.setLocalMem(args.getSwitch("-local"));
conf.setNrSamplesPerBlock(args.getSwitchArgument< unsigned int >("-sb"));
conf.setNrDMsPerBlock(args.getSwitchArgument< unsigned int >("-db"));
conf.setNrSamplesPerThread(args.getSwitchArgument< unsigned int >("-st"));
conf.setNrDMsPerThread(args.getSwitchArgument< unsigned int >("-dt"));
conf.setUnroll(args.getSwitchArgument< unsigned int >("-unroll"));
observation.setFrequencyRange(args.getSwitchArgument< unsigned int >("-channels"), args.getSwitchArgument< float >("-min_freq"), args.getSwitchArgument< float >("-channel_bandwidth"));
observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples"));
observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), args.getSwitchArgument< float >("-dm_first"), args.getSwitchArgument< float >("-dm_step"));
} catch ( isa::utils::SwitchNotFound & err ) {
std::cerr << err.what() << std::endl;
return 1;
}catch ( std::exception & err ) {
std::cerr << "Usage: " << argv[0] << " [-print] -opencl_platform ... -opencl_device ... -padding ... [-local] -sb ... -db ... -st ... -dt ... -unroll ... -min_freq ... -channel_bandwidth ... -samples ... -channels ... -dms ... -dm_first ... -dm_step ..." << 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);
std::vector< float > * shifts = PulsarSearch::getShifts(observation);
observation.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerSecond() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep()))));
// Allocate memory
cl::Buffer shifts_d;
std::vector< dataType > dispersedData = std::vector< dataType >(observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel());
cl::Buffer dispersedData_d;
std::vector< dataType > dedispersedData = std::vector< dataType >(observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());
cl::Buffer dedispersedData_d;
std::vector< dataType > controlData = std::vector< dataType >(observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());
try {
shifts_d = cl::Buffer(*clContext, CL_MEM_READ_ONLY, shifts->size() * sizeof(float), 0, 0);
dispersedData_d = cl::Buffer(*clContext, CL_MEM_READ_ONLY, dispersedData.size() * sizeof(dataType), 0, 0);
dedispersedData_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, dedispersedData.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));
for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) {
for ( unsigned int sample = 0; sample < observation.getNrSamplesPerDispersedChannel(); sample++ ) {
dispersedData[(channel * observation.getNrSamplesPerDispersedChannel()) + sample] = static_cast< dataType >(rand() % 10);
}
}
// Copy data structures to device
try {
clQueues->at(clDeviceID)[0].enqueueWriteBuffer(shifts_d, CL_FALSE, 0, shifts->size() * sizeof(float), reinterpret_cast< void * >(shifts->data()), 0, 0);
clQueues->at(clDeviceID)[0].enqueueWriteBuffer(dispersedData_d, CL_FALSE, 0, dispersedData.size() * sizeof(dataType), reinterpret_cast< void * >(dispersedData.data()), 0, 0);
} catch ( cl::Error & err ) {
std::cerr << "OpenCL error H2D transfer: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl;
return 1;
}
// Generate kernel
std::string * code = PulsarSearch::getDedispersionOpenCL(conf, typeName, observation, *shifts);
cl::Kernel * kernel;
if ( print ) {
std::cout << *code << std::endl;
}
try {
kernel = isa::OpenCL::compile("dedispersion", *code, "-cl-mad-enable -Werror", *clContext, clDevices->at(clDeviceID));
} catch ( isa::OpenCL::OpenCLError & err ) {
std::cerr << err.what() << std::endl;
return 1;
}
// Run OpenCL kernel and CPU control
try {
cl::NDRange global(observation.getNrSamplesPerPaddedSecond() / conf.getNrSamplesPerThread(), observation.getNrDMs() / conf.getNrDMsPerThread());
cl::NDRange local(conf.getNrSamplesPerBlock(), conf.getNrDMsPerBlock());
kernel->setArg(0, dispersedData_d);
kernel->setArg(1, dedispersedData_d);
kernel->setArg(2, shifts_d);
clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local);
PulsarSearch::dedispersion< dataType >(observation, dispersedData, controlData, *shifts);
clQueues->at(clDeviceID)[0].enqueueReadBuffer(dedispersedData_d, CL_TRUE, 0, dedispersedData.size() * sizeof(dataType), reinterpret_cast< void * >(dedispersedData.data()));
} catch ( cl::Error & err ) {
std::cerr << "OpenCL error kernel execution: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl;
return 1;
}
for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {
for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {
if ( !isa::utils::same(controlData[(dm * observation.getNrSamplesPerPaddedSecond()) + sample], dedispersedData[(dm * observation.getNrSamplesPerPaddedSecond()) + sample]) ) {
wrongSamples++;
}
}
}
if ( wrongSamples > 0 ) {
std::cout << "Wrong samples: " << wrongSamples << " (" << (wrongSamples * 100.0) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrSamplesPerSecond()) << "%)." << std::endl;
} else {
std::cout << "TEST PASSED." << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>#include "../allocator.hpp"
#include "../platform.hpp"
namespace stx {
static
char*& _old_arena(char* arena) {
return *((char**) arena);
}
static
char* _create_arena(size_t size, char* old, char** top, char** end) {
char* result = new char[size + sizeof(char*)];
_old_arena(result) = old;
if(top != nullptr)
*top = result + sizeof(char*);
if(end != nullptr)
*end = *top + size;
return result;
}
static
void _destroy_arena(char* arena) {
while(arena) {
char* old_arena = _old_arena(arena);
delete[] arena;
arena = old_arena;
}
}
arena_allocator::arena_allocator(size_t block_size) :
m_arena_size(block_size),
m_arena(nullptr),
m_top(nullptr),
m_arena_end(nullptr)
{}
arena_allocator::arena_allocator(arena_allocator&& other) noexcept {
m_arena = other.m_arena; other.m_arena = nullptr;
m_top = other.m_top; other.m_top = nullptr;
m_arena_end = other.m_arena_end; other.m_arena_end = nullptr;
m_arena_size = other.m_arena_size;
}
arena_allocator& arena_allocator::operator=(arena_allocator&& other) noexcept {
m_arena = other.m_arena; other.m_arena = nullptr;
m_top = other.m_top; other.m_top = nullptr;
m_arena_end = other.m_arena_end; other.m_arena_end = nullptr;
m_arena_size = other.m_arena_size;
return *this;
}
void arena_allocator::reset() {
_destroy_arena(m_arena);
m_arena = m_top = m_arena_end = nullptr;
}
char* arena_allocator::alloc(size_t bytes) {
char* new_top = m_top + bytes;
if(STX_UNLIKELY(new_top > m_arena_end)) {
if(bytes > m_arena_size) {
// Bigger than our usual arena size, insert a new arena just for this one
char* result = _create_arena(bytes, _old_arena(m_arena), nullptr, nullptr);
_old_arena(m_arena) = result;
return result;
}
else {
m_arena = _create_arena(m_arena_size, m_arena, &m_top, &m_arena_end);
}
}
char* result = m_top;
m_top = new_top;
return result;
}
char* arena_allocator::alloc_string(size_t n) {
char* result = alloc(n + 1);
result[n] = '\0';
return result;
}
void arena_allocator::undo_alloc(size_t bytes) {
// TODO: arena_allocator::undo_alloc
}
} // namespace stx
<commit_msg>Added missing destructor<commit_after>#include "../allocator.hpp"
#include "../platform.hpp"
namespace stx {
static
char*& _old_arena(char* arena) {
return *((char**) arena);
}
static
char* _create_arena(size_t size, char* old, char** top, char** end) {
char* result = new char[size + sizeof(char*)];
_old_arena(result) = old;
if(top != nullptr)
*top = result + sizeof(char*);
if(end != nullptr)
*end = *top + size;
return result;
}
static
void _destroy_arena(char* arena) {
while(arena) {
char* old_arena = _old_arena(arena);
delete[] arena;
arena = old_arena;
}
}
arena_allocator::arena_allocator(size_t block_size) :
m_arena_size(block_size),
m_arena(nullptr),
m_top(nullptr),
m_arena_end(nullptr)
{}
arena_allocator::~arena_allocator() {
reset();
}
arena_allocator::arena_allocator(arena_allocator&& other) noexcept {
m_arena = other.m_arena; other.m_arena = nullptr;
m_top = other.m_top; other.m_top = nullptr;
m_arena_end = other.m_arena_end; other.m_arena_end = nullptr;
m_arena_size = other.m_arena_size;
}
arena_allocator& arena_allocator::operator=(arena_allocator&& other) noexcept {
m_arena = other.m_arena; other.m_arena = nullptr;
m_top = other.m_top; other.m_top = nullptr;
m_arena_end = other.m_arena_end; other.m_arena_end = nullptr;
m_arena_size = other.m_arena_size;
return *this;
}
void arena_allocator::reset() {
_destroy_arena(m_arena);
m_arena = m_top = m_arena_end = nullptr;
}
char* arena_allocator::alloc(size_t bytes) {
char* new_top = m_top + bytes;
if(STX_UNLIKELY(new_top > m_arena_end)) {
if(bytes > m_arena_size) {
// Bigger than our usual arena size, insert a new arena just for this one
char* result = _create_arena(bytes, _old_arena(m_arena), nullptr, nullptr);
_old_arena(m_arena) = result;
return result;
}
else {
m_arena = _create_arena(m_arena_size, m_arena, &m_top, &m_arena_end);
}
}
char* result = m_top;
m_top = new_top;
return result;
}
char* arena_allocator::alloc_string(size_t n) {
char* result = alloc(n + 1);
result[n] = '\0';
return result;
}
void arena_allocator::undo_alloc(size_t bytes) {
// TODO: arena_allocator::undo_alloc
}
} // namespace stx
<|endoftext|> |
<commit_before>#pragma once
#include <vector>
#include <string>
class TextureAsset;
class ScriptFile;
namespace Geometry {
class Model;
}
namespace Audio {
class SoundBuffer;
}
/// A list of all the resources in a hymn.
class ResourceList {
friend ResourceList& Resources();
public:
/// Save all resources to file.
void Save() const;
/// Load all resources from file.
void Load();
/// Clear resources.
void Clear();
/// Scenes.
std::vector<std::string> scenes;
/// The index to the activeScene.
int activeScene;
/// Models.
std::vector<Geometry::Model*> models;
/// The id of the next model to create.
unsigned int modelNumber = 0U;
/// Textures.
std::vector<TextureAsset*> textures;
/// The id of the next texture to create.
unsigned int textureNumber = 0U;
/// Sounds.
std::vector<Audio::SoundBuffer*> sounds;
/// The id of the next sound to create.
unsigned int soundNumber = 0U;
private:
static ResourceList& GetInstance();
ResourceList();
ResourceList(ResourceList const&) = delete;
void operator=(ResourceList const&) = delete;
};
/// Get the resource list.
/**
* @return The %ResourceList instance.
*/
ResourceList& Resources();
<commit_msg>Resource struct<commit_after>#pragma once
#include <vector>
#include <string>
class TextureAsset;
class ScriptFile;
namespace Geometry {
class Model;
}
namespace Audio {
class SoundBuffer;
}
/// A list of all the resources in a hymn.
class ResourceList {
friend ResourceList& Resources();
public:
/// A resource.
struct Resource {
/// The type of resource.
enum Type {
SCENE = 0,
MODEL,
TEXTURE,
SOUND
} type;
/// Scene name.
std::string scene;
/// Model.
Geometry::Model* model;
/// Texture.
TextureAsset* texture;
/// Sound.
Audio::SoundBuffer* sound;
};
/// Save all resources to file.
void Save() const;
/// Load all resources from file.
void Load();
/// Clear resources.
void Clear();
/// Resources.
std::vector<Resource> resources;
/// Scenes.
std::vector<std::string> scenes;
/// The index to the activeScene.
int activeScene;
/// Models.
std::vector<Geometry::Model*> models;
/// The id of the next model to create.
unsigned int modelNumber = 0U;
/// Textures.
std::vector<TextureAsset*> textures;
/// The id of the next texture to create.
unsigned int textureNumber = 0U;
/// Sounds.
std::vector<Audio::SoundBuffer*> sounds;
/// The id of the next sound to create.
unsigned int soundNumber = 0U;
private:
static ResourceList& GetInstance();
ResourceList();
ResourceList(ResourceList const&) = delete;
void operator=(ResourceList const&) = delete;
};
/// Get the resource list.
/**
* @return The %ResourceList instance.
*/
ResourceList& Resources();
<|endoftext|> |
<commit_before>#include <UtH/Engine/Transform.hpp>
#include <UtH/Engine/GameObject.hpp>
#include <cmath>
#include <array>
using namespace uth;
Transform::Transform(Object* p)
: parent(p),
m_position(0, 0),
m_size(0, 0),
m_scale(1, 1),
m_origin(0, 0),
m_angle(0),
m_transformNeedsUpdate(true)
{ }
Transform::~Transform()
{
}
// Public
void Transform::Move(const pmath::Vec2& offset)
{
m_position += offset;
m_transformNeedsUpdate = true;
}
void Transform::Move(const float offsetX, const float offsetY)
{
Move(pmath::Vec2(offsetX, offsetY));
}
void Transform::SetPosition(const pmath::Vec2& position)
{
this->m_position = position;
m_transformNeedsUpdate = true;
}
void Transform::SetPosition(const float posX, const float posY)
{
SetPosition(pmath::Vec2(posX, posY));
}
const pmath::Vec2& Transform::GetPosition() const
{
return m_position;
}
void Transform::SetSize(const pmath::Vec2& size)
{
ScaleToSize(size.x, size.y);
}
void Transform::SetSize(const float width, const float height)
{
ScaleToSize(width, height);
}
void Transform::ScaleToSize(const pmath::Vec2& size)
{
SetSize(size.x, size.y);
}
void Transform::ScaleToSize(const float width, const float height)
{
SetScale(width / m_size.x, height / m_size.y);
m_transformNeedsUpdate = true;
}
const pmath::Vec2& Transform::GetSize() const
{
return m_size;
}
void Transform::SetOrigin(const pmath::Vec2& origin)
{
this->m_origin = origin;
m_transformNeedsUpdate = true;
}
void Transform::SetOrigin(const int originPoint)
{
using namespace pmath;
switch (originPoint)
{
case Origin::Point::BottomLeft:
SetOrigin(Vec2(m_size.x * -0.5f, m_size.y * 0.5f));
break;
case Origin::Point::BottomCenter:
SetOrigin(Vec2(0.0f, m_size.y * 0.5f));
break;
case Origin::Point::BottomRight:
SetOrigin(Vec2(m_size.x * 0.5f, m_size.y * 0.5f));
break;
case Origin::Point::MidLeft:
SetOrigin(Vec2(m_size.x * -0.5f, 0.f));
break;
case Origin::Point::MidRight:
SetOrigin(Vec2(m_size.x * 0.5f, 0.f));
break;
case Origin::Point::TopLeft:
SetOrigin(Vec2(m_size.x * -0.5f, m_size.y * -0.5f));
break;
case Origin::Point::TopCenter:
SetOrigin(Vec2(0.0f, m_size.y * -0.5f));
break;
case Origin::Point::TopRight:
SetOrigin(Vec2(m_size.x * 0.5f, m_size.y * -0.5f));
break;
case Origin::Point::Center:
default:
SetOrigin(Vec2());
break;
}
}
const pmath::Vec2& Transform::GetOrigin() const
{
return m_origin;
}
void Transform::SetScale(const pmath::Vec2& scale)
{
this->m_scale = scale;
m_transformNeedsUpdate = true;
}
void Transform::SetScale(const float xScale, const float yScale)
{
SetScale(pmath::Vec2(xScale, yScale));
}
void Transform::SetScale(const float scale)
{
SetScale(pmath::Vec2(scale, scale));
}
const pmath::Vec2& Transform::GetScale() const
{
return m_scale;
}
void Transform::SetRotation(const float degrees)
{
this->m_angle = degrees;
m_transformNeedsUpdate = true;
}
const float Transform::GetRotation() const
{
return m_angle;
}
void Transform::Rotate(const float degrees)
{
this->m_angle += degrees;
m_transformNeedsUpdate = true;
}
pmath::Rect Transform::GetBounds() const
{
pmath::Vec2 scaled = m_size;
scaled.scale(m_scale);
pmath::Vec2 sOrig = m_origin;
sOrig.scale(m_scale);
return pmath::Rect((m_position - sOrig) - scaled / 2.f, scaled);
}
pmath::Rect Transform::GetTransformedBounds() const
{
const pmath::Vec2 topLeft(m_position - m_size / 2.f - m_origin);
const auto& tf = GetTransform();
std::array<pmath::Vec2, 4> points =
{ {
pmath::Vec2(topLeft),
pmath::Vec2(topLeft.x, topLeft.y + m_size.y),
pmath::Vec2(topLeft + m_size),
pmath::Vec2(topLeft.x + m_size.x, topLeft.y)
} };
float left = 0.f,
right = 0.f,
bottom = 0.f,
top = 0.f;
for (auto& i : points)
{
// Add transform matrix first
i *= tf;
if (i.x < left)
left = i.x;
else if (i.x > right)
right = i.x;
if (i.y < top)
top = i.y;
else if (i.y > bottom)
bottom = i.y;
}
return pmath::Rect(left, top, right - left, bottom - top);
}
void Transform::SetTransform(const pmath::Mat4& modelTransform)
{
m_modelTransform = modelTransform;
}
void Transform::AddTransform(const pmath::Mat4& modelTransform)
{
updateTransform();
m_modelTransform = m_modelTransform * modelTransform;
}
const pmath::Mat4& Transform::GetTransform() const
{
updateTransform();
if (parent && (parent->HasParent<GameObject>()))
{
m_combinedTransform = parent->Parent<GameObject>()->transform.GetTransform() *
m_modelTransform;
return m_combinedTransform;
}
else if (parent && parent->HasParent<Layer>())
{
m_combinedTransform = parent->Parent<Layer>()->transform.GetTransform() *
m_modelTransform;
return m_combinedTransform;
}
return m_modelTransform;
}
// Private
void Transform::setSize(const pmath::Vec2& size)
{
this->m_size = size;
m_transformNeedsUpdate = true;
}
void Transform::setSize(const float width, const float height)
{
setSize(pmath::Vec2(width, height));
}
void Transform::updateTransform() const
{
if (!m_transformNeedsUpdate)
return;
m_modelTransform = pmath::Mat4();
if (m_position != pmath::Vec2(0.f, 0.f))
m_modelTransform = m_modelTransform * pmath::Mat4::createTranslation(m_position.x, m_position.y, 0.f);
if (m_angle != 0.f)
m_modelTransform = m_modelTransform * pmath::Mat4::createRotationZ(m_angle);
if (m_scale != pmath::Vec2(1.f, 1.f))
m_modelTransform = m_modelTransform * pmath::Mat4::createScaling(m_scale.x, m_scale.y, 1.f);
if (m_origin != pmath::Vec2(0.f, 0.f))
m_modelTransform = m_modelTransform * pmath::Mat4::createTranslation(-m_origin.x, -m_origin.y, 0.f);
m_transformNeedsUpdate = false;
}
<commit_msg>Fixed GetTransformedBounds<commit_after>#include <UtH/Engine/Transform.hpp>
#include <UtH/Engine/GameObject.hpp>
#include <cmath>
#include <array>
using namespace uth;
Transform::Transform(Object* p)
: parent(p),
m_position(0, 0),
m_size(0, 0),
m_scale(1, 1),
m_origin(0, 0),
m_angle(0),
m_transformNeedsUpdate(true)
{ }
Transform::~Transform()
{
}
// Public
void Transform::Move(const pmath::Vec2& offset)
{
m_position += offset;
m_transformNeedsUpdate = true;
}
void Transform::Move(const float offsetX, const float offsetY)
{
Move(pmath::Vec2(offsetX, offsetY));
}
void Transform::SetPosition(const pmath::Vec2& position)
{
this->m_position = position;
m_transformNeedsUpdate = true;
}
void Transform::SetPosition(const float posX, const float posY)
{
SetPosition(pmath::Vec2(posX, posY));
}
const pmath::Vec2& Transform::GetPosition() const
{
return m_position;
}
void Transform::SetSize(const pmath::Vec2& size)
{
ScaleToSize(size.x, size.y);
}
void Transform::SetSize(const float width, const float height)
{
ScaleToSize(width, height);
}
void Transform::ScaleToSize(const pmath::Vec2& size)
{
SetSize(size.x, size.y);
}
void Transform::ScaleToSize(const float width, const float height)
{
SetScale(width / m_size.x, height / m_size.y);
m_transformNeedsUpdate = true;
}
const pmath::Vec2& Transform::GetSize() const
{
return m_size;
}
void Transform::SetOrigin(const pmath::Vec2& origin)
{
this->m_origin = origin;
m_transformNeedsUpdate = true;
}
void Transform::SetOrigin(const int originPoint)
{
using namespace pmath;
switch (originPoint)
{
case Origin::Point::BottomLeft:
SetOrigin(Vec2(m_size.x * -0.5f, m_size.y * 0.5f));
break;
case Origin::Point::BottomCenter:
SetOrigin(Vec2(0.0f, m_size.y * 0.5f));
break;
case Origin::Point::BottomRight:
SetOrigin(Vec2(m_size.x * 0.5f, m_size.y * 0.5f));
break;
case Origin::Point::MidLeft:
SetOrigin(Vec2(m_size.x * -0.5f, 0.f));
break;
case Origin::Point::MidRight:
SetOrigin(Vec2(m_size.x * 0.5f, 0.f));
break;
case Origin::Point::TopLeft:
SetOrigin(Vec2(m_size.x * -0.5f, m_size.y * -0.5f));
break;
case Origin::Point::TopCenter:
SetOrigin(Vec2(0.0f, m_size.y * -0.5f));
break;
case Origin::Point::TopRight:
SetOrigin(Vec2(m_size.x * 0.5f, m_size.y * -0.5f));
break;
case Origin::Point::Center:
default:
SetOrigin(Vec2());
break;
}
}
const pmath::Vec2& Transform::GetOrigin() const
{
return m_origin;
}
void Transform::SetScale(const pmath::Vec2& scale)
{
this->m_scale = scale;
m_transformNeedsUpdate = true;
}
void Transform::SetScale(const float xScale, const float yScale)
{
SetScale(pmath::Vec2(xScale, yScale));
}
void Transform::SetScale(const float scale)
{
SetScale(pmath::Vec2(scale, scale));
}
const pmath::Vec2& Transform::GetScale() const
{
return m_scale;
}
void Transform::SetRotation(const float degrees)
{
this->m_angle = degrees;
m_transformNeedsUpdate = true;
}
const float Transform::GetRotation() const
{
return m_angle;
}
void Transform::Rotate(const float degrees)
{
this->m_angle += degrees;
m_transformNeedsUpdate = true;
}
pmath::Rect Transform::GetBounds() const
{
pmath::Vec2 scaled = m_size;
scaled.scale(m_scale);
pmath::Vec2 sOrig = m_origin;
sOrig.scale(m_scale);
return pmath::Rect((m_position - sOrig) - scaled / 2.f, scaled);
}
pmath::Rect Transform::GetTransformedBounds() const
{
const pmath::Vec2 topLeft(m_position - m_size / 2.f - m_origin);
const auto& tf = GetTransform();
std::array<pmath::Vec2, 4> points =
{ {
pmath::Vec2(topLeft),
pmath::Vec2(topLeft.x, topLeft.y + m_size.y),
pmath::Vec2(topLeft + m_size),
pmath::Vec2(topLeft.x + m_size.x, topLeft.y)
} };
float left = 0.f,
right = 0.f,
bottom = 0.f,
top = 0.f;
for (size_t i = 0; i < points.size(); ++i)
{
auto& point = points.at(i);
// Add transform matrix first
point *= tf;
// Initialize left, right, top and bottom with sensible values
// This is required so that the result will be correct
if (i == 0)
{
left = point.x;
right = point.x;
top = point.y;
bottom = point.y;
}
if (point.x < left)
left = point.x;
else if (point.x > right)
right = point.x;
if (point.y < top)
top = point.y;
else if (point.y > bottom)
bottom = point.y;
}
return pmath::Rect(left, top, right - left, bottom - top);
}
void Transform::SetTransform(const pmath::Mat4& modelTransform)
{
m_modelTransform = modelTransform;
}
void Transform::AddTransform(const pmath::Mat4& modelTransform)
{
updateTransform();
m_modelTransform = m_modelTransform * modelTransform;
}
const pmath::Mat4& Transform::GetTransform() const
{
updateTransform();
if (parent && (parent->HasParent<GameObject>()))
{
m_combinedTransform = parent->Parent<GameObject>()->transform.GetTransform() *
m_modelTransform;
return m_combinedTransform;
}
else if (parent && parent->HasParent<Layer>())
{
m_combinedTransform = parent->Parent<Layer>()->transform.GetTransform() *
m_modelTransform;
return m_combinedTransform;
}
return m_modelTransform;
}
// Private
void Transform::setSize(const pmath::Vec2& size)
{
this->m_size = size;
m_transformNeedsUpdate = true;
}
void Transform::setSize(const float width, const float height)
{
setSize(pmath::Vec2(width, height));
}
void Transform::updateTransform() const
{
if (!m_transformNeedsUpdate)
return;
m_modelTransform = pmath::Mat4();
if (m_position != pmath::Vec2(0.f, 0.f))
m_modelTransform = m_modelTransform * pmath::Mat4::createTranslation(m_position.x, m_position.y, 0.f);
if (m_angle != 0.f)
m_modelTransform = m_modelTransform * pmath::Mat4::createRotationZ(m_angle);
if (m_scale != pmath::Vec2(1.f, 1.f))
m_modelTransform = m_modelTransform * pmath::Mat4::createScaling(m_scale.x, m_scale.y, 1.f);
if (m_origin != pmath::Vec2(0.f, 0.f))
m_modelTransform = m_modelTransform * pmath::Mat4::createTranslation(-m_origin.x, -m_origin.y, 0.f);
m_transformNeedsUpdate = false;
}
<|endoftext|> |
<commit_before><commit_msg>quick spacing change, and test of git repo import<commit_after><|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "IECore/ChannelOp.h"
#include "IECore/TypeTraits.h"
#include "IECore/DespatchTypedData.h"
#include "IECore/CompoundParameter.h"
#include "boost/format.hpp"
using namespace IECore;
using namespace std;
using namespace boost;
ChannelOp::ChannelOp( const std::string &name, const std::string &description )
: ImagePrimitiveOp( name, description )
{
StringVectorDataPtr defaultChannels = new StringVectorData;
defaultChannels->writable().push_back( "R" );
defaultChannels->writable().push_back( "G" );
defaultChannels->writable().push_back( "B" );
m_channelNamesParameter = new StringVectorParameter(
"channels",
"The names of the channels to modify.",
defaultChannels
);
parameters()->addParameter( m_channelNamesParameter );
}
ChannelOp::~ChannelOp()
{
}
StringVectorParameterPtr ChannelOp::channelNamesParameter()
{
return m_channelNamesParameter;
}
ConstStringVectorParameterPtr ChannelOp::channelNamesParameter() const
{
return m_channelNamesParameter;
}
void ChannelOp::modifyTypedPrimitive( ImagePrimitivePtr image, ConstCompoundObjectPtr operands )
{
if( image->getDataWindow().isEmpty() )
{
return;
}
ChannelVector channels;
size_t numPixels = image->variableSize( PrimitiveVariable::Vertex );
const vector<string> channelNames = channelNamesParameter()->getTypedValue();
for( unsigned i=0; i<channelNames.size(); i++ )
{
PrimitiveVariableMap::iterator it = image->variables.find( channelNames[i] );
if( it==image->variables.end() )
{
throw Exception( str( format( "Channel \"%s\" does not exist." ) % channelNames[i] ) );
}
if( it->second.interpolation!=PrimitiveVariable::Vertex &&
it->second.interpolation!=PrimitiveVariable::Varying &&
it->second.interpolation!=PrimitiveVariable::FaceVarying )
{
throw Exception( str( format( "Primitive variable \"%s\" has inappropriate interpolation." ) % channelNames[i] ) );
}
if( !it->second.data->isInstanceOf( FloatVectorData::staticTypeId() ) &&
!it->second.data->isInstanceOf( HalfVectorData::staticTypeId() ) &&
!it->second.data->isInstanceOf( IntVectorData::staticTypeId() ) )
{
throw Exception( str( format( "Primitive variable \"%s\" has inappropriate type." ) % channelNames[i] ) );
}
size_t size = despatchTypedData<TypedDataSize>( it->second.data );
if( size!=numPixels )
{
throw Exception( str( format( "Primitive variable \"%s\" has wrong size (%d but should be %d)." ) % channelNames[i] % size % numPixels ) );
}
channels.push_back( it->second.data );
}
modifyChannels( image->getDisplayWindow(), image->getDataWindow(), channels );
}
<commit_msg>Added a todo and fixed a bug.<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "IECore/ChannelOp.h"
#include "IECore/TypeTraits.h"
#include "IECore/DespatchTypedData.h"
#include "IECore/CompoundParameter.h"
#include "boost/format.hpp"
using namespace IECore;
using namespace std;
using namespace boost;
ChannelOp::ChannelOp( const std::string &name, const std::string &description )
: ImagePrimitiveOp( name, description )
{
StringVectorDataPtr defaultChannels = new StringVectorData;
defaultChannels->writable().push_back( "R" );
defaultChannels->writable().push_back( "G" );
defaultChannels->writable().push_back( "B" );
m_channelNamesParameter = new StringVectorParameter(
"channels",
"The names of the channels to modify.",
defaultChannels
);
parameters()->addParameter( m_channelNamesParameter );
}
ChannelOp::~ChannelOp()
{
}
StringVectorParameterPtr ChannelOp::channelNamesParameter()
{
return m_channelNamesParameter;
}
ConstStringVectorParameterPtr ChannelOp::channelNamesParameter() const
{
return m_channelNamesParameter;
}
void ChannelOp::modifyTypedPrimitive( ImagePrimitivePtr image, ConstCompoundObjectPtr operands )
{
if( image->getDataWindow().isEmpty() )
{
return;
}
ChannelVector channels;
/// \todo Just use ImagePrimitive::channelValid. We don't want to do that right now
/// as it imposes loose restrictions on the channel datatype - in the future it should perhaps
/// impose the restrictions we have here (float, uint or half vector data).
size_t numPixels = image->variableSize( PrimitiveVariable::Vertex );
const vector<string> channelNames = channelNamesParameter()->getTypedValue();
for( unsigned i=0; i<channelNames.size(); i++ )
{
PrimitiveVariableMap::iterator it = image->variables.find( channelNames[i] );
if( it==image->variables.end() )
{
throw Exception( str( format( "Channel \"%s\" does not exist." ) % channelNames[i] ) );
}
if( it->second.interpolation!=PrimitiveVariable::Vertex &&
it->second.interpolation!=PrimitiveVariable::Varying &&
it->second.interpolation!=PrimitiveVariable::FaceVarying )
{
throw Exception( str( format( "Primitive variable \"%s\" has inappropriate interpolation." ) % channelNames[i] ) );
}
if( !it->second.data )
{
throw Exception( str( format( "Primitive variable \"%s\" has no data." ) % channelNames[i] ) );
}
if( !it->second.data->isInstanceOf( FloatVectorData::staticTypeId() ) &&
!it->second.data->isInstanceOf( HalfVectorData::staticTypeId() ) &&
!it->second.data->isInstanceOf( IntVectorData::staticTypeId() ) )
{
throw Exception( str( format( "Primitive variable \"%s\" has inappropriate type." ) % channelNames[i] ) );
}
size_t size = despatchTypedData<TypedDataSize>( it->second.data );
if( size!=numPixels )
{
throw Exception( str( format( "Primitive variable \"%s\" has wrong size (%d but should be %d)." ) % channelNames[i] % size % numPixels ) );
}
channels.push_back( it->second.data );
}
modifyChannels( image->getDisplayWindow(), image->getDataWindow(), channels );
}
<|endoftext|> |
<commit_before>//
// OCCAM
//
// Copyright (c) 2011-2018, SRI International
//
// 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 SRI International 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.
//
/**
* Intra-module specialization.
**/
#include "llvm/Pass.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/IR/CallSite.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
//#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "SpecializationTable.h"
#include "Specializer.h"
/* here specialization policies */
#include "AggressiveSpecPolicy.h"
#include "RecursiveGuardSpecPolicy.h"
using namespace llvm;
using namespace previrt;
static cl::opt<bool>
OptSpecialized("Ppeval-opt", cl::Hidden,
cl::init(false),
cl::desc("Optimize new specialized functions"));
static cl::opt<SpecializationPolicyType>
SpecPolicy("Ppeval-policy",
cl::desc("Intra-module specialization policy"),
cl::values
(clEnumValN (NOSPECIALIZE, "nospecialize",
"Skip intra-module specialization"),
clEnumValN (AGGRESSIVE, "aggressive",
"Specialize always if some constant argument"),
clEnumValN (NONRECURSIVE_WITH_AGGRESSIVE, "nonrec-aggressive",
"aggressive + non-recursive function")),
cl::init(NONRECURSIVE_WITH_AGGRESSIVE));
namespace previrt
{
/**
Return true if any callsite in f is specialized using policy.
**/
static bool trySpecializeFunction(Function* f, SpecializationTable& table,
SpecializationPolicy* policy,
std::vector<Function*>& to_add) {
std::vector<Instruction*> worklist;
for (BasicBlock& bb: *f) {
for (Instruction& I: bb) {
Instruction* ci = dyn_cast<CallInst>(&I);
if (!ci) ci = dyn_cast<InvokeInst>(&I);
if (!ci) continue;
CallSite call(ci);
Function* callee = call.getCalledFunction();
if (!callee) {
continue;
}
if (callee->isDeclaration() || callee->isVarArg()) {
continue;
}
if (callee->hasFnAttribute(Attribute::NoInline) ||
callee->hasFnAttribute(Attribute::OptimizeNone)) {
continue;
}
worklist.push_back(ci);
}
}
bool modified = false;
while (!worklist.empty()) {
Instruction* ci = worklist.back();
worklist.pop_back();
CallSite cs(ci);
Function* callee = cs.getCalledFunction();
assert(callee);
// specScheme[i] = nullptr if the i-th parameter of the callsite
// cannot be specialized.
// c if the i-th parameter of the callsite is a
// constant c
std::vector<Value*> specScheme;
bool specialize = policy->specializeOn(cs, specScheme);
#if 1
errs() << "Intra-specializing call to '" << callee->getName()
<< "' in function '" << ci->getParent()->getParent()->getName()
<< "' on arguments [";
for (unsigned int i = 0, cnt = 0; i < callee->arg_size(); ++i) {
if (specScheme[i] != NULL) {
if (cnt++ != 0)
errs() << ",";
Value* v = cs.getInstruction()->getOperand(i);
if (GlobalValue* gv = dyn_cast<GlobalValue>(v)) {
errs() << i << "=(@" << gv->getName() << ")";
} else {
errs() << i << "=(" << *cs.getInstruction()->getOperand(i) << ")";
}
}
}
errs() << "]\n";
#endif
if (!specialize) {
continue;
}
// --- build a specialized function if specScheme is more
// refined than all existing specialized versions.
Function* specializedVersion = nullptr;
std::vector<const SpecializationTable::Specialization*> versions;
table.getSpecializations(callee, specScheme, versions);
for (std::vector<const SpecializationTable::Specialization*>::iterator i =
versions.begin(), e = versions.end(); i != e; ++i) {
if (SpecializationTable::Specialization::refines(specScheme, (*i)->args)) {
specializedVersion = (*i)->handle;
break;
}
}
if (!specializedVersion) {
specializedVersion = specializeFunction(callee, specScheme);
if(!specializedVersion) {
continue;
}
table.addSpecialization(callee, specScheme, specializedVersion);
to_add.push_back(specializedVersion);
}
// -- build the specialized callsite
const unsigned int specialized_arg_count = specializedVersion->arg_size();
std::vector<unsigned> argPerm;
argPerm.reserve(specialized_arg_count);
for (unsigned from = 0; from < callee->arg_size(); from++) {
if (!specScheme[from])
argPerm.push_back(from);
}
assert(specialized_arg_count == argPerm.size());
Instruction* newInst = specializeCallSite(ci, specializedVersion, argPerm);
llvm::ReplaceInstWithInst(ci, newInst);
modified = true;
}
return modified;
}
/* Intra-module specialization */
class SpecializerPass : public llvm::ModulePass {
private:
bool optimize;
public:
static char ID;
SpecializerPass(bool);
virtual ~SpecializerPass();
virtual void getAnalysisUsage(llvm::AnalysisUsage &AU) const;
virtual bool runOnModule(llvm::Module &M);
virtual llvm::StringRef getPassName() const {
return "Intra-module specializer";
}
};
bool SpecializerPass::runOnModule(Module &M) {
// -- Create the specialization policy. Bail out if no policy.
SpecializationPolicy* policy = nullptr;
switch (SpecPolicy) {
case NOSPECIALIZE:
return false;
case AGGRESSIVE:
policy = new AggressiveSpecPolicy();
break;
case NONRECURSIVE_WITH_AGGRESSIVE: {
SpecializationPolicy* subpolicy = new AggressiveSpecPolicy();
CallGraph& cg = getAnalysis<CallGraphWrapperPass>().getCallGraph();
policy = new RecursiveGuardSpecPolicy(subpolicy, cg);
break;
}
}
// -- Specialize functions defined in M
std::vector<Function*> to_add;
SpecializationTable table(&M);
bool modified = false;
for (auto &f: M) {
if(f.isDeclaration()) continue;
modified |= trySpecializeFunction(&f, table, policy, to_add);
}
// -- Optimize new function and add it into the module
llvm::legacy::FunctionPassManager* optimizer = nullptr;
if (optimize) {
optimizer = new llvm::legacy::FunctionPassManager(&M);
//PassManagerBuilder builder;
//builder.OptLevel = 3;
//builder.populateFunctionPassManager(*optimizer);
}
while (!to_add.empty()) {
Function* f = to_add.back();
to_add.pop_back();
if (f->getParent() == &M || f->isDeclaration()) {
// The function was already in the module or
// has already been added in this round of
// specialization, no need to add it twice
continue;
}
if (optimizer) {
optimizer->run(*f);
}
M.getFunctionList().push_back(f);
}
if (modified) {
errs() << "...progress...\n";
} else {
errs() << "...no progress...\n";
}
if (policy) {
delete policy;
}
if (optimizer) {
delete optimizer;
}
return modified;
}
void SpecializerPass::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<CallGraphWrapperPass>();
AU.setPreservesAll();
}
SpecializerPass::SpecializerPass(bool opt)
: ModulePass(SpecializerPass::ID)
, optimize(opt) {
errs() << "SpecializerPass(" << optimize << ")\n";
}
SpecializerPass::~SpecializerPass() {}
class ParEvalOptPass : public SpecializerPass {
public:
ParEvalOptPass()
: SpecializerPass(OptSpecialized.getValue()) {}
};
char SpecializerPass::ID;
} // end namespace previrt
static RegisterPass<previrt::ParEvalOptPass>
X("Ppeval", "Intra-module partial evaluation", false, false);
<commit_msg>Print msg only if specialization happens<commit_after>//
// OCCAM
//
// Copyright (c) 2011-2018, SRI International
//
// 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 SRI International 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.
//
/**
* Intra-module specialization.
**/
#include "llvm/Pass.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/IR/CallSite.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
//#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "SpecializationTable.h"
#include "Specializer.h"
/* here specialization policies */
#include "AggressiveSpecPolicy.h"
#include "RecursiveGuardSpecPolicy.h"
using namespace llvm;
using namespace previrt;
static cl::opt<bool>
OptSpecialized("Ppeval-opt", cl::Hidden,
cl::init(false),
cl::desc("Optimize new specialized functions"));
static cl::opt<SpecializationPolicyType>
SpecPolicy("Ppeval-policy",
cl::desc("Intra-module specialization policy"),
cl::values
(clEnumValN (NOSPECIALIZE, "nospecialize",
"Skip intra-module specialization"),
clEnumValN (AGGRESSIVE, "aggressive",
"Specialize always if some constant argument"),
clEnumValN (NONRECURSIVE_WITH_AGGRESSIVE, "nonrec-aggressive",
"aggressive + non-recursive function")),
cl::init(NONRECURSIVE_WITH_AGGRESSIVE));
namespace previrt
{
/**
Return true if any callsite in f is specialized using policy.
**/
static bool trySpecializeFunction(Function* f, SpecializationTable& table,
SpecializationPolicy* policy,
std::vector<Function*>& to_add) {
std::vector<Instruction*> worklist;
for (BasicBlock& bb: *f) {
for (Instruction& I: bb) {
Instruction* ci = dyn_cast<CallInst>(&I);
if (!ci) ci = dyn_cast<InvokeInst>(&I);
if (!ci) continue;
CallSite call(ci);
Function* callee = call.getCalledFunction();
if (!callee) {
continue;
}
if (callee->isDeclaration() || callee->isVarArg()) {
continue;
}
if (callee->hasFnAttribute(Attribute::NoInline) ||
callee->hasFnAttribute(Attribute::OptimizeNone)) {
continue;
}
worklist.push_back(ci);
}
}
bool modified = false;
while (!worklist.empty()) {
Instruction* ci = worklist.back();
worklist.pop_back();
CallSite cs(ci);
Function* callee = cs.getCalledFunction();
assert(callee);
// specScheme[i] = nullptr if the i-th parameter of the callsite
// cannot be specialized.
// c if the i-th parameter of the callsite is a
// constant c
std::vector<Value*> specScheme;
bool specialize = policy->specializeOn(cs, specScheme);
if (!specialize) {
continue;
}
#if 1
errs() << "Intra-specializing call to '" << callee->getName()
<< "' in function '" << ci->getParent()->getParent()->getName()
<< "' on arguments [";
for (unsigned int i = 0, cnt = 0; i < callee->arg_size(); ++i) {
if (specScheme[i] != NULL) {
if (cnt++ != 0)
errs() << ",";
Value* v = cs.getInstruction()->getOperand(i);
if (GlobalValue* gv = dyn_cast<GlobalValue>(v)) {
errs() << i << "=(@" << gv->getName() << ")";
} else {
errs() << i << "=(" << *cs.getInstruction()->getOperand(i) << ")";
}
}
}
errs() << "]\n";
#endif
// --- build a specialized function if specScheme is more
// refined than all existing specialized versions.
Function* specializedVersion = nullptr;
std::vector<const SpecializationTable::Specialization*> versions;
table.getSpecializations(callee, specScheme, versions);
for (std::vector<const SpecializationTable::Specialization*>::iterator i =
versions.begin(), e = versions.end(); i != e; ++i) {
if (SpecializationTable::Specialization::refines(specScheme, (*i)->args)) {
specializedVersion = (*i)->handle;
break;
}
}
if (!specializedVersion) {
specializedVersion = specializeFunction(callee, specScheme);
if(!specializedVersion) {
continue;
}
table.addSpecialization(callee, specScheme, specializedVersion);
to_add.push_back(specializedVersion);
}
// -- build the specialized callsite
const unsigned int specialized_arg_count = specializedVersion->arg_size();
std::vector<unsigned> argPerm;
argPerm.reserve(specialized_arg_count);
for (unsigned from = 0; from < callee->arg_size(); from++) {
if (!specScheme[from])
argPerm.push_back(from);
}
assert(specialized_arg_count == argPerm.size());
Instruction* newInst = specializeCallSite(ci, specializedVersion, argPerm);
llvm::ReplaceInstWithInst(ci, newInst);
modified = true;
}
return modified;
}
/* Intra-module specialization */
class SpecializerPass : public llvm::ModulePass {
private:
bool optimize;
public:
static char ID;
SpecializerPass(bool);
virtual ~SpecializerPass();
virtual void getAnalysisUsage(llvm::AnalysisUsage &AU) const;
virtual bool runOnModule(llvm::Module &M);
virtual llvm::StringRef getPassName() const {
return "Intra-module specializer";
}
};
bool SpecializerPass::runOnModule(Module &M) {
// -- Create the specialization policy. Bail out if no policy.
SpecializationPolicy* policy = nullptr;
switch (SpecPolicy) {
case NOSPECIALIZE:
return false;
case AGGRESSIVE:
policy = new AggressiveSpecPolicy();
break;
case NONRECURSIVE_WITH_AGGRESSIVE: {
SpecializationPolicy* subpolicy = new AggressiveSpecPolicy();
CallGraph& cg = getAnalysis<CallGraphWrapperPass>().getCallGraph();
policy = new RecursiveGuardSpecPolicy(subpolicy, cg);
break;
}
}
// -- Specialize functions defined in M
std::vector<Function*> to_add;
SpecializationTable table(&M);
bool modified = false;
for (auto &f: M) {
if(f.isDeclaration()) continue;
modified |= trySpecializeFunction(&f, table, policy, to_add);
}
// -- Optimize new function and add it into the module
llvm::legacy::FunctionPassManager* optimizer = nullptr;
if (optimize) {
optimizer = new llvm::legacy::FunctionPassManager(&M);
//PassManagerBuilder builder;
//builder.OptLevel = 3;
//builder.populateFunctionPassManager(*optimizer);
}
while (!to_add.empty()) {
Function* f = to_add.back();
to_add.pop_back();
if (f->getParent() == &M || f->isDeclaration()) {
// The function was already in the module or
// has already been added in this round of
// specialization, no need to add it twice
continue;
}
if (optimizer) {
optimizer->run(*f);
}
M.getFunctionList().push_back(f);
}
if (modified) {
errs() << "...progress...\n";
} else {
errs() << "...no progress...\n";
}
if (policy) {
delete policy;
}
if (optimizer) {
delete optimizer;
}
return modified;
}
void SpecializerPass::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<CallGraphWrapperPass>();
AU.setPreservesAll();
}
SpecializerPass::SpecializerPass(bool opt)
: ModulePass(SpecializerPass::ID)
, optimize(opt) {
errs() << "SpecializerPass(" << optimize << ")\n";
}
SpecializerPass::~SpecializerPass() {}
class ParEvalOptPass : public SpecializerPass {
public:
ParEvalOptPass()
: SpecializerPass(OptSpecialized.getValue()) {}
};
char SpecializerPass::ID;
} // end namespace previrt
static RegisterPass<previrt::ParEvalOptPass>
X("Ppeval", "Intra-module partial evaluation", false, false);
<|endoftext|> |
<commit_before><?hh //strict
namespace hhpack\publisher;
use ReflectionClass;
use ReflectionMethod;
final class MessageSubscriber implements Subscriber<Message>
{
private Map<string, Vector<Subscription<Message>>> $subscriptions = Map {};
public function __construct(
private Subscribable<Message> $receiver
)
{
$class = new ReflectionClass($receiver);
$methods = $class->getMethods(ReflectionMethod::IS_PUBLIC);
foreach ($methods as $method) {
$parameters = $method->getParameters();
$parameter = $parameters[0];
$type = $parameter->getClass()->getName();
if ( !($type instanceof Message) ) {
continue;
}
$subscriptions = $this->subscriptions->get($type);
if ($subscriptions === null) {
$subscriptions = Vector {};
}
$subscriptions->add(new InvokeSubscription( Pair { $this->receiver, $method->getName() }));
$this->subscriptions->set($type, $subscriptions);
}
}
public function subscribe(Publicher<Message> $publicher) : void
{
$publicher->registerSubscriber($this);
}
public function receive(Message $message) : void
{
$nameOfType = get_class($message);
if ($this->subscriptions->containsKey($nameOfType)) {
return;
}
$subscriptions = $this->subscriptions->at($nameOfType);
foreach ($subscriptions->items() as $subscription) {
$subscription->receive($message);
}
}
}
<commit_msg>bugfix<commit_after><?hh //strict
namespace hhpack\publisher;
use ReflectionClass;
use ReflectionMethod;
final class MessageSubscriber implements Subscriber<Message>
{
private Map<string, Vector<Subscription<Message>>> $subscriptions = Map {};
public function __construct(
private Subscribable<Message> $receiver
)
{
$class = new ReflectionClass($receiver);
$methods = $class->getMethods(ReflectionMethod::IS_PUBLIC);
foreach ($methods as $method) {
$parameters = $method->getParameters();
$parameter = $parameters[0];
$type = $parameter->getClass();
$typeName = $parameter->getClass()->getName();
if ($type->implementsInterface(Message::class) === false) {
continue;
}
$subscriptions = $this->subscriptions->get($typeName);
if ($subscriptions === null) {
$subscriptions = Vector {};
}
$subscriptions->add(new InvokeSubscription( Pair { $this->receiver, $method->getName() }));
$this->subscriptions->set($typeName, $subscriptions);
}
}
public function subscribe(Publicher<Message> $publicher) : void
{
$publicher->registerSubscriber($this);
}
public function receive(Message $message) : void
{
$nameOfType = get_class($message);
if ($this->subscriptions->containsKey($nameOfType) === false) {
return;
}
$subscriptions = $this->subscriptions->at($nameOfType);
foreach ($subscriptions->items() as $subscription) {
$subscription->receive($message);
}
}
}
<|endoftext|> |
<commit_before>#include <WarManager.h>
#include <Regions.h>
#include <util.h>
#include <UnitsGroup.h>
#include "DefendChokeGoal.h"
#include "BorderManager.h"
using std::map;
using std::set;
using std::vector;
using std::list;
using namespace BWAPI;
using namespace BWTA;
WarManager::WarManager()
: BaseObject("WarManager")
{
this->defgroup = new UnitsGroup();
this->arbitrator = NULL;
this->regions = NULL;
}
WarManager::~WarManager()
{
//Broodwar->printf("INOUT WarManager::~WarManager()");
}
void WarManager::setDependencies(Arbitrator::Arbitrator<BWAPI::Unit*,double>* arb, Regions * reg){
this->arbitrator = arb;
this->regions = reg;
}
void WarManager::onStart(){
this->sendGroupToDefense(defgroup);
}
void WarManager::update()
{
//Suppress the list prompted to suppress
for each (UnitsGroup * ug in this->promptedRemove){
this->remove(ug);
ug->idle(); //Set target of units to their position so that they are now idling
ug->~UnitsGroup();
}
promptedRemove.clear();
//Set bid on appropriate units (not workers and not building)
std::set<BWAPI::Unit *> myUnits = BWAPI::Broodwar->self()->getUnits();
for(std::set<BWAPI::Unit *>::iterator it = myUnits.begin(); it != myUnits.end(); ++it){
if( !(*it)->getType().isBuilding() && !(*it)->getType().isWorker() ){
this->arbitrator->setBid(this,(*it),40);
}
}
//Update unitsgroup
defgroup->update();
if (unitsgroups.empty()) return;
UnitsGroup* ug;
for (std::list<UnitsGroup*>::iterator it = unitsgroups.begin(); it != unitsgroups.end(); it++)
{
ug = *it;
ug->update();
}
sout << "LOL" << sendl;
serr << "LOL" << sendl;
}
void WarManager::onOffer(std::set<BWAPI::Unit*> units)
{
for(std::set<BWAPI::Unit*>::iterator u = units.begin(); u != units.end(); u++)
{
if (!(*u)->getType().isWorker() && !(*u)->getType().isBuilding())
{
arbitrator->accept(this, *u);
defgroup->takeControl(*u);
//Broodwar->printf("New %s added to the micro manager", (*u)->getType().getName().c_str());
}
else
{
arbitrator->decline(this, *u, 0);
}
}
}
void WarManager::onRevoke(BWAPI::Unit* unit, double bid)
{
this->onUnitDestroy(unit);
}
std::string WarManager::getName() const
{
return "Micro Manager";
}
void WarManager::onUnitCreate(BWAPI::Unit* unit)
{
/*
if (!unit->getType().isWorker() && unit->getPlayer()==Broodwar->self() && !unit->getType().isBuilding() && unit->getType().canAttack())
arbitrator->setBid(this, unit, 100);
*/
}
void WarManager::onUnitDestroy(BWAPI::Unit* unit)
{
for (std::list<UnitsGroup*>::iterator it = unitsgroups.begin(); it != unitsgroups.end();)
{
(*it)->giveUpControl(unit);
if( (*it)->emptyUnits())
{
UnitsGroup* ug = *it;
it = unitsgroups.erase( it);
delete ug;
}
else
it++;
}
}
void WarManager::display()
{
for( std::list<UnitsGroup*>::iterator it = unitsgroups.begin(); it != unitsgroups.end(); it++)
(*it)->display();
}
void WarManager::sendGroupToAttack( UnitsGroup* ug)
{
// Get the nearest enemy position
bool found = false;
double minDist = 0xFFFF;
Position nearestEnemyLocation;
Unit* enemyUnit;
for (map<Region*, RegionData>::const_iterator itRegions = regions->regionsData.begin(); itRegions != regions->regionsData.end(); itRegions++)
{
for (map<Player*, vector<RegionsUnitData> >::const_iterator itBuildings = itRegions->second.buildings.begin(); itBuildings != itRegions->second.buildings.end(); itBuildings++)
{
if (itBuildings->first->isEnemy(Broodwar->self()))
{
for (vector<RegionsUnitData>::const_iterator itBD = itBuildings->second.begin(); itBD != itBuildings->second.end(); ++itBD)
{
double distance = getGroundDistance( ug->getCenter(), itBD->position);
if( distance < minDist)
{
minDist = distance;
nearestEnemyLocation = itBD->position;
enemyUnit = itBD->unit;
found = true;
}
}
}
}
}
if (!found) return;
// ug->addGoal(pGoal(new AttackGoal(nearestEnemyLocation)));
//Broodwar->printf( "Let's fight !!");
}
void WarManager::sendGroupToDefense( UnitsGroup* ug)
{
/*
// Go to the nearest choke point.
BaseLocation* startLoc = BWTA::getStartLocation(BWAPI::Broodwar->self());
BWAPI::Position chokePoint;
const std::set<Region*>& region = getRegions();
const std::set<Chokepoint*>& chocke = getChokepoints();
for( std::set<Region*>::const_iterator itRegion = region.begin(); itRegion != region.end(); itRegion++)
{
if( (*itRegion)->getPolygon().isInside(startLoc->getPosition()))
{
for( std::set<Chokepoint*>::const_iterator itChocke = chocke.begin(); itChocke != chocke.end(); itChocke++)
{
const std::pair<Region*,Region*>& border = (*itChocke)->getRegions();
if( border.first == *itRegion || border.second == *itRegion )
{
chokePoint = (*itChocke)->getCenter();
}
}
}
}*/
// Send the group defend the base
pGoal g = pGoal(new DefendChokeGoal(ug,(*BorderManager::Instance().getMyBorder().begin())));
ug->addGoal(g);
}
bool WarManager::remove(UnitsGroup* u){
for(std::list<UnitsGroup *>::iterator it = unitsgroups.begin(); it != unitsgroups.end(); it ++){
if( (*it) == u){
unitsgroups.erase(it);
return true;
}
}
return false;
}
void WarManager::promptRemove(UnitsGroup* ug){
this->promptedRemove.push_back(ug);
}
std::set<Unit*> WarManager::getEnemies()
{
std::set<BWAPI::Player*>::iterator iter = Broodwar->getPlayers().begin();
for(;iter != Broodwar->getPlayers().end() && !(*iter)->isEnemy(Broodwar->self());iter++);
return (*iter)->getUnits();
}
#ifdef BW_QT_DEBUG
QWidget* WarManager::createWidget(QWidget* parent) const
{
return new QLabel(QString("createWidget and refreshWidget undefined for this component."), parent);
}
void WarManager::refreshWidget(QWidget* widget) const
{
// TODO update your widget after having defined it in the previous method :)
}
#endif
<commit_msg>Added a unique unitsgroup for the warmanager that is idling(in def) or attacking<commit_after>#include <WarManager.h>
#include <Regions.h>
#include <util.h>
#include <UnitsGroup.h>
#include "DefendChokeGoal.h"
#include "BorderManager.h"
using std::map;
using std::set;
using std::vector;
using std::list;
using namespace BWAPI;
using namespace BWTA;
WarManager::WarManager()
: BaseObject("WarManager")
{
this->defgroup = new UnitsGroup();
this->arbitrator = NULL;
this->regions = NULL;
}
WarManager::~WarManager()
{
//Broodwar->printf("INOUT WarManager::~WarManager()");
}
void WarManager::setDependencies(Arbitrator::Arbitrator<BWAPI::Unit*,double>* arb, Regions * reg){
this->arbitrator = arb;
this->regions = reg;
}
void WarManager::onStart(){
this->ugIdle->addGoal(pGoal(new DefendChokeGoal(ugIdle, (*BaseManager::Instance().getAllBases().begin())->chokeToDef)));
}
void WarManager::update()
{
//Suppress the list prompted to suppress
for each (UnitsGroup * ug in this->promptedRemove){
this->remove(ug);
ug->idle(); //Set target of units to their position so that they are now idling
ug->~UnitsGroup();
}
promptedRemove.clear();
//Set bid on appropriate units (not workers and not building)
std::set<BWAPI::Unit *> myUnits = BWAPI::Broodwar->self()->getUnits();
for(std::set<BWAPI::Unit *>::iterator it = myUnits.begin(); it != myUnits.end(); ++it){
if( !(*it)->getType().isBuilding() && !(*it)->getType().isWorker() ){
this->arbitrator->setBid(this,(*it),20);
}
}
//Update unitsgroup
defgroup->update();
if (unitsgroups.empty()) return;
UnitsGroup* ug;
for (std::list<UnitsGroup*>::iterator it = unitsgroups.begin(); it != unitsgroups.end(); it++)
{
ug = *it;
ug->update();
}
/*
sout << "LOL" << sendl;
serr << "LOL" << sendl;
*/
}
void WarManager::onOffer(std::set<BWAPI::Unit*> units)
{
for(std::set<BWAPI::Unit*>::iterator u = units.begin(); u != units.end(); u++)
{
if (!(*u)->getType().isWorker() && !(*u)->getType().isBuilding())
{
arbitrator->accept(this, *u);
defgroup->takeControl(*u);
//Broodwar->printf("New %s added to the micro manager", (*u)->getType().getName().c_str());
}
else
{
arbitrator->decline(this, *u, 0);
}
}
}
void WarManager::onRevoke(BWAPI::Unit* unit, double bid)
{
this->onUnitDestroy(unit);
}
std::string WarManager::getName() const
{
return "Micro Manager";
}
void WarManager::onUnitCreate(BWAPI::Unit* unit)
{
/*
if (!unit->getType().isWorker() && unit->getPlayer()==Broodwar->self() && !unit->getType().isBuilding() && unit->getType().canAttack())
arbitrator->setBid(this, unit, 100);
*/
}
void WarManager::onUnitDestroy(BWAPI::Unit* unit)
{
for (std::list<UnitsGroup*>::iterator it = unitsgroups.begin(); it != unitsgroups.end();)
{
(*it)->giveUpControl(unit);
if( (*it)->emptyUnits())
{
UnitsGroup* ug = *it;
it = unitsgroups.erase( it);
delete ug;
}
else
it++;
}
}
void WarManager::display()
{
for( std::list<UnitsGroup*>::iterator it = unitsgroups.begin(); it != unitsgroups.end(); it++)
(*it)->display();
}
void WarManager::sendGroupToAttack( UnitsGroup* ug)
{
// Get the nearest enemy position
bool found = false;
double minDist = 0xFFFF;
Position nearestEnemyLocation;
Unit* enemyUnit;
for (map<Region*, RegionData>::const_iterator itRegions = regions->regionsData.begin(); itRegions != regions->regionsData.end(); itRegions++)
{
for (map<Player*, vector<RegionsUnitData> >::const_iterator itBuildings = itRegions->second.buildings.begin(); itBuildings != itRegions->second.buildings.end(); itBuildings++)
{
if (itBuildings->first->isEnemy(Broodwar->self()))
{
for (vector<RegionsUnitData>::const_iterator itBD = itBuildings->second.begin(); itBD != itBuildings->second.end(); ++itBD)
{
double distance = getGroundDistance( ug->getCenter(), itBD->position);
if( distance < minDist)
{
minDist = distance;
nearestEnemyLocation = itBD->position;
enemyUnit = itBD->unit;
found = true;
}
}
}
}
}
if (!found) return;
// ug->addGoal(pGoal(new AttackGoal(nearestEnemyLocation)));
//Broodwar->printf( "Let's fight !!");
}
void WarManager::sendGroupToDefense( UnitsGroup* ug)
{
/*
// Go to the nearest choke point.
BaseLocation* startLoc = BWTA::getStartLocation(BWAPI::Broodwar->self());
BWAPI::Position chokePoint;
const std::set<Region*>& region = getRegions();
const std::set<Chokepoint*>& chocke = getChokepoints();
for( std::set<Region*>::const_iterator itRegion = region.begin(); itRegion != region.end(); itRegion++)
{
if( (*itRegion)->getPolygon().isInside(startLoc->getPosition()))
{
for( std::set<Chokepoint*>::const_iterator itChocke = chocke.begin(); itChocke != chocke.end(); itChocke++)
{
const std::pair<Region*,Region*>& border = (*itChocke)->getRegions();
if( border.first == *itRegion || border.second == *itRegion )
{
chokePoint = (*itChocke)->getCenter();
}
}
}
}*/
// Send the group defend the base
// pGoal g = pGoal(new DefendChokeGoal(ug,(*BorderManager::Instance().getMyBorder().begin())));
// ug->addGoal(g);
}
bool WarManager::remove(UnitsGroup* u){
for(std::list<UnitsGroup *>::iterator it = unitsgroups.begin(); it != unitsgroups.end(); it ++){
if( (*it) == u){
unitsgroups.erase(it);
return true;
}
}
return false;
}
void WarManager::promptRemove(UnitsGroup* ug){
this->promptedRemove.push_back(ug);
}
std::set<Unit*> WarManager::getEnemies()
{
std::set<BWAPI::Player*>::iterator iter = Broodwar->getPlayers().begin();
for(;iter != Broodwar->getPlayers().end() && !(*iter)->isEnemy(Broodwar->self());iter++);
return (*iter)->getUnits();
}
#ifdef BW_QT_DEBUG
QWidget* WarManager::createWidget(QWidget* parent) const
{
return new QLabel(QString("createWidget and refreshWidget undefined for this component."), parent);
}
void WarManager::refreshWidget(QWidget* widget) const
{
// TODO update your widget after having defined it in the previous method :)
}
#endif
<|endoftext|> |
<commit_before>#include <QClipboard>
#include <QDateTime>
#include <QDebug>
#include <QFile>
#include <QFileDialog>
#include <QKeyEvent>
#include <QLineEdit>
#include <QMessageBox>
#include <QPoint>
#include <QSettings>
#include <QSize>
#include <QTextStream>
#include <algorithm>
#include <stdexcept>
#include <typeinfo>
#include "CorpusWidget.hh"
#include "SimpleDTD.hh"
#include "StatisticsWindow.hh"
#include "Query.hh"
#include "QueryModel.hh"
#include "PercentageCellDelegate.hh"
#include "ValidityColor.hh"
#include "XPathValidator.hh"
#include "XSLTransformer.hh"
#include "ui_StatisticsWindow.h"
StatisticsWindow::StatisticsWindow(QWidget *parent) :
CorpusWidget(parent),
d_ui(QSharedPointer<Ui::StatisticsWindow>(new Ui::StatisticsWindow)),
d_percentageCellDelegate(new PercentageCellDelegate)
{
d_ui->setupUi(this);
createActions();
readNodeAttributes();
readSettings();
// Pick a sane default attribute.
int idx = d_ui->attributeComboBox->findText("word");
if (idx != -1)
d_ui->attributeComboBox->setCurrentIndex(idx);
}
StatisticsWindow::~StatisticsWindow()
{
writeSettings();
}
void StatisticsWindow::attributeChanged(int index)
{
Q_UNUSED(index);
if (!d_model.isNull())
startQuery();
}
void StatisticsWindow::queryFailed(QString error)
{
progressStopped(0, 0);
QMessageBox::critical(this, tr("Error processing query"),
tr("Could not process query: ") + error,
QMessageBox::Ok);
}
void StatisticsWindow::switchCorpus(QSharedPointer<alpinocorpus::CorpusReader> corpusReader)
{
d_corpusReader = corpusReader;
emit saveStateChanged();
//d_xpathValidator->setCorpusReader(d_corpusReader);
setModel(new QueryModel(corpusReader));
// Ensure that percentage column is hidden when necessary.
showPercentageChanged();
}
void StatisticsWindow::setFilter(QString const &filter, QString const &raw_filter)
{
Q_UNUSED(raw_filter);
d_filter = filter;
startQuery();
}
void StatisticsWindow::setAggregateAttribute(QString const &detail)
{
// @TODO: update d_ui->attributeComboBox.currentIndex when changed from outside
// to reflect the current (changed) state of the window.
}
void StatisticsWindow::setModel(QueryModel *model)
{
d_model = QSharedPointer<QueryModel>(model);
d_ui->resultsTable->setModel(d_model.data());
d_ui->distinctValuesLabel->setText(QString(""));
d_ui->totalHitsLabel->setText(QString(""));
connect(d_model.data(), SIGNAL(queryFailed(QString)),
SLOT(queryFailed(QString)));
connect(d_model.data(), SIGNAL(queryEntryFound(QString)),
SLOT(updateResultsTotalCount()));
connect(d_model.data(), SIGNAL(queryStarted(int)),
SLOT(progressStarted(int)));
connect(d_model.data(), SIGNAL(queryStopped(int, int)),
SLOT(progressStopped(int, int)));
connect(d_model.data(), SIGNAL(queryFinished(int, int, QString, bool, bool)),
SLOT(progressStopped(int, int)));
connect(d_model.data(), SIGNAL(progressChanged(int)),
SLOT(progressChanged(int)));
}
void StatisticsWindow::updateResultsTotalCount()
{
d_ui->totalHitsLabel->setText(QString("%L1").arg(d_model->totalHits()));
d_ui->distinctValuesLabel->setText(QString("%L1").arg(d_model->rowCount(QModelIndex())));
}
void StatisticsWindow::applyValidityColor(QString const &)
{
::applyValidityColor(sender());
}
void StatisticsWindow::cancelQuery()
{
if (d_model)
d_model->cancelQuery();
}
void StatisticsWindow::saveAs()
{
if (d_model.isNull())
return;
int nlines = d_model->rowCount(QModelIndex());
if (nlines == 0)
return;
QString filename;
QStringList filenames;
QFileDialog fd(this, tr("Save"), QString("untitled"), tr("Microsoft Excel 2003 XML (*.xls);;Text (*.txt);;HTML (*.html *.htm);;CSV (*.csv)"));
fd.setAcceptMode(QFileDialog::AcceptSave);
fd.setConfirmOverwrite(true);
fd.setLabelText(QFileDialog::Accept, tr("Save"));
if (d_lastFilterChoice.size())
fd.selectNameFilter(d_lastFilterChoice);
if (fd.exec())
filenames = fd.selectedFiles();
else
return;
if (filenames.size() < 1)
return;
filename = filenames[0];
if (! filename.length())
return;
QSharedPointer<QFile> stylesheet;
d_lastFilterChoice = fd.selectedNameFilter();
if (d_lastFilterChoice.contains("*.txt"))
stylesheet = QSharedPointer<QFile>(new QFile(":/stylesheets/stats-text.xsl"));
else if (d_lastFilterChoice.contains("*.html"))
stylesheet = QSharedPointer<QFile>(new QFile(":/stylesheets/stats-html.xsl"));
else if (d_lastFilterChoice.contains("*.xls"))
stylesheet = QSharedPointer<QFile>(new QFile(":/stylesheets/stats-officexml.xsl"));
else
stylesheet = QSharedPointer<QFile>(new QFile(":/stylesheets/stats-csv.xsl"));
QFile data(filename);
if (!data.open(QFile::WriteOnly | QFile::Truncate)) {
QMessageBox::critical(this,
tr("Save file error"),
tr("Cannot save file %1 (error code %2)").arg(filename).arg(data.error()),
QMessageBox::Ok);
return;
}
QTextStream out(&data);
out.setCodec("UTF-8");
QString xmlStats = d_model->asXML();
XSLTransformer trans(*stylesheet);
out << trans.transform(xmlStats);
emit statusMessage(tr("File saved as %1").arg(filename));
}
void StatisticsWindow::copy()
{
QString csv;
QTextStream textstream(&csv, QIODevice::WriteOnly | QIODevice::Text);
selectionAsCSV(textstream, "\t");
if (!csv.isEmpty())
QApplication::clipboard()->setText(csv);
}
void StatisticsWindow::exportSelection()
{
QString filename(QFileDialog::getSaveFileName(this,
"Export selection",
QString(), "*.csv"));
if (filename.isNull())
return;
QFile file(filename);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
{
QMessageBox::critical(this,
tr("Error exporting selection"),
tr("Could open file for writing."),
QMessageBox::Ok);
return;
}
QTextStream textstream(&file);
textstream.setGenerateByteOrderMark(true);
selectionAsCSV(textstream, ";", true);
}
void StatisticsWindow::createActions()
{
// @TODO: move this non action related ui code to somewhere else. The .ui file preferably.
// Requires initialized UI.
//d_ui->resultsTable->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
d_ui->resultsTable->verticalHeader()->hide();
d_ui->resultsTable->sortByColumn(1, Qt::DescendingOrder);
d_ui->resultsTable->setItemDelegateForColumn(2, d_percentageCellDelegate.data());
// Only allow valid xpath queries to be submitted
//d_ui->filterLineEdit->setValidator(d_xpathValidator.data());
// When a row is activated, generate a query to be used in the main window to
// filter all the results so only the results which are accumulated in this
// row will be shown.
connect(d_ui->resultsTable, SIGNAL(activated(QModelIndex const &)),
SLOT(generateQuery(QModelIndex const &)));
// Toggle percentage column checkbox (is this needed?)
connect(d_ui->percentageCheckBox, SIGNAL(toggled(bool)),
SLOT(showPercentageChanged()));
connect(d_ui->yieldCheckBox, SIGNAL(toggled(bool)),
SLOT(showYieldChanged()));
connect(d_ui->attributeComboBox, SIGNAL(currentIndexChanged(int)),
SLOT(attributeChanged(int)));
}
void StatisticsWindow::generateQuery(QModelIndex const &index)
{
// Get the text from the first column, that is the found value
QString data = index.sibling(index.row(), 0).data(Qt::UserRole).toString();
if (data == QueryModel::MISSING_ATTRIBUTE)
return;
QString query = ::generateQuery(
d_filter,
d_ui->attributeComboBox->currentText(),
data);
emit entryActivated(data, query);
}
void StatisticsWindow::selectionAsCSV(QTextStream &output, QString const &separator, bool escape_quotes) const
{
// If there is no model attached (e.g. no corpus loaded) do nothing
if (!d_model)
return;
QModelIndexList rows = d_ui->resultsTable->selectionModel()->selectedRows();
// If there is nothing selected, do nothing
if (rows.isEmpty())
return;
foreach (QModelIndex const &row, rows)
{
// This only works if the selection behavior is SelectRows
if (escape_quotes)
output << '"' << d_model->data(row).toString().replace("\"", "\"\"") << '"'; // value
else
output << d_model->data(row).toString();
output
<< separator
<< d_model->data(row.sibling(row.row(), 1)).toString() // count
<< '\n';
}
}
void StatisticsWindow::startQuery()
{
setAggregateAttribute(d_ui->attributeComboBox->currentText());
d_ui->resultsTable->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
d_ui->resultsTable->horizontalHeader()->setResizeMode(1, QHeaderView::ResizeToContents);
d_ui->resultsTable->horizontalHeader()->setResizeMode(2, QHeaderView::Stretch);
d_ui->totalHitsLabel->clear();
d_ui->distinctValuesLabel->clear();
bool yield = d_ui->yieldCheckBox->isChecked();
d_model->runQuery(d_filter, d_ui->attributeComboBox->currentText(), yield);
emit saveStateChanged();
}
void StatisticsWindow::showPercentageChanged()
{
d_ui->resultsTable->setColumnHidden(2, !d_ui->percentageCheckBox->isChecked());
}
void StatisticsWindow::showYieldChanged()
{
if (!d_model.isNull())
startQuery();
}
void StatisticsWindow::progressStarted(int total)
{
d_ui->filterProgress->setMaximum(total);
d_ui->filterProgress->setDisabled(false);
d_ui->filterProgress->setVisible(true);
}
void StatisticsWindow::progressChanged(int percentage)
{
d_ui->filterProgress->setValue(percentage);
}
void StatisticsWindow::progressStopped(int n, int total)
{
d_ui->filterProgress->setVisible(false);
emit saveStateChanged();
}
void StatisticsWindow::closeEvent(QCloseEvent *event)
{
writeSettings();
event->accept();
}
void StatisticsWindow::readNodeAttributes()
{
QFile dtdFile(":/dtd/alpino_ds.dtd"); // XXX - hardcode?
if (!dtdFile.open(QFile::ReadOnly)) {
qWarning() << "StatisticsWindow::readNodeAttributes(): Could not read DTD.";
return;
}
QByteArray dtdData(dtdFile.readAll());
SimpleDTD sDTD(dtdData.constData());
// Should be safe to clear items now...
d_ui->attributeComboBox->clear();
// Do we have a node element?
ElementMap::const_iterator iter = sDTD.elementMap().find("node");
if (iter == sDTD.elementMap().end())
return;
std::set<std::string> attrs = iter->second;
QStringList attrList;
for (std::set<std::string>::const_iterator attrIter = attrs.begin();
attrIter != attrs.end(); ++ attrIter)
attrList.push_back(QString::fromUtf8(attrIter->c_str()));
std::sort(attrList.begin(), attrList.end());
d_ui->attributeComboBox->addItems(attrList);
}
bool StatisticsWindow::saveEnabled() const
{
if (d_model.isNull())
return false;
if (d_model->rowCount(QModelIndex()) == 0)
return false;
return true;
}
void StatisticsWindow::readSettings()
{
QSettings settings;
bool show = settings.value("query_show_percentage", true).toBool();
d_ui->percentageCheckBox->setChecked(show);
// Window geometry.
QPoint pos = settings.value("query_pos", QPoint(200, 200)).toPoint();
QSize size = settings.value("query_size", QSize(350, 400)).toSize();
resize(size);
// Move.
move(pos);
}
void StatisticsWindow::writeSettings()
{
QSettings settings;
settings.setValue("query_show_percentage", d_ui->percentageCheckBox->isChecked());
// Window geometry
settings.setValue("query_pos", pos());
settings.setValue("query_size", size());
}
<commit_msg>Ensure counts are shown when the query comes from cache.<commit_after>#include <QClipboard>
#include <QDateTime>
#include <QDebug>
#include <QFile>
#include <QFileDialog>
#include <QKeyEvent>
#include <QLineEdit>
#include <QMessageBox>
#include <QPoint>
#include <QSettings>
#include <QSize>
#include <QTextStream>
#include <algorithm>
#include <stdexcept>
#include <typeinfo>
#include "CorpusWidget.hh"
#include "SimpleDTD.hh"
#include "StatisticsWindow.hh"
#include "Query.hh"
#include "QueryModel.hh"
#include "PercentageCellDelegate.hh"
#include "ValidityColor.hh"
#include "XPathValidator.hh"
#include "XSLTransformer.hh"
#include "ui_StatisticsWindow.h"
StatisticsWindow::StatisticsWindow(QWidget *parent) :
CorpusWidget(parent),
d_ui(QSharedPointer<Ui::StatisticsWindow>(new Ui::StatisticsWindow)),
d_percentageCellDelegate(new PercentageCellDelegate)
{
d_ui->setupUi(this);
createActions();
readNodeAttributes();
readSettings();
// Pick a sane default attribute.
int idx = d_ui->attributeComboBox->findText("word");
if (idx != -1)
d_ui->attributeComboBox->setCurrentIndex(idx);
}
StatisticsWindow::~StatisticsWindow()
{
writeSettings();
}
void StatisticsWindow::attributeChanged(int index)
{
Q_UNUSED(index);
if (!d_model.isNull())
startQuery();
}
void StatisticsWindow::queryFailed(QString error)
{
progressStopped(0, 0);
QMessageBox::critical(this, tr("Error processing query"),
tr("Could not process query: ") + error,
QMessageBox::Ok);
}
void StatisticsWindow::switchCorpus(QSharedPointer<alpinocorpus::CorpusReader> corpusReader)
{
d_corpusReader = corpusReader;
emit saveStateChanged();
//d_xpathValidator->setCorpusReader(d_corpusReader);
setModel(new QueryModel(corpusReader));
// Ensure that percentage column is hidden when necessary.
showPercentageChanged();
}
void StatisticsWindow::setFilter(QString const &filter, QString const &raw_filter)
{
Q_UNUSED(raw_filter);
d_filter = filter;
startQuery();
}
void StatisticsWindow::setAggregateAttribute(QString const &detail)
{
// @TODO: update d_ui->attributeComboBox.currentIndex when changed from outside
// to reflect the current (changed) state of the window.
}
void StatisticsWindow::setModel(QueryModel *model)
{
d_model = QSharedPointer<QueryModel>(model);
d_ui->resultsTable->setModel(d_model.data());
d_ui->distinctValuesLabel->setText(QString(""));
d_ui->totalHitsLabel->setText(QString(""));
connect(d_model.data(), SIGNAL(queryFailed(QString)),
SLOT(queryFailed(QString)));
connect(d_model.data(), SIGNAL(queryEntryFound(QString)),
SLOT(updateResultsTotalCount()));
connect(d_model.data(), SIGNAL(queryStarted(int)),
SLOT(progressStarted(int)));
connect(d_model.data(), SIGNAL(queryStopped(int, int)),
SLOT(progressStopped(int, int)));
connect(d_model.data(), SIGNAL(queryFinished(int, int, QString, bool, bool)),
SLOT(progressStopped(int, int)));
connect(d_model.data(), SIGNAL(progressChanged(int)),
SLOT(progressChanged(int)));
}
void StatisticsWindow::updateResultsTotalCount()
{
d_ui->totalHitsLabel->setText(QString("%L1").arg(d_model->totalHits()));
d_ui->distinctValuesLabel->setText(QString("%L1").arg(d_model->rowCount(QModelIndex())));
}
void StatisticsWindow::applyValidityColor(QString const &)
{
::applyValidityColor(sender());
}
void StatisticsWindow::cancelQuery()
{
if (d_model)
d_model->cancelQuery();
}
void StatisticsWindow::saveAs()
{
if (d_model.isNull())
return;
int nlines = d_model->rowCount(QModelIndex());
if (nlines == 0)
return;
QString filename;
QStringList filenames;
QFileDialog fd(this, tr("Save"), QString("untitled"), tr("Microsoft Excel 2003 XML (*.xls);;Text (*.txt);;HTML (*.html *.htm);;CSV (*.csv)"));
fd.setAcceptMode(QFileDialog::AcceptSave);
fd.setConfirmOverwrite(true);
fd.setLabelText(QFileDialog::Accept, tr("Save"));
if (d_lastFilterChoice.size())
fd.selectNameFilter(d_lastFilterChoice);
if (fd.exec())
filenames = fd.selectedFiles();
else
return;
if (filenames.size() < 1)
return;
filename = filenames[0];
if (! filename.length())
return;
QSharedPointer<QFile> stylesheet;
d_lastFilterChoice = fd.selectedNameFilter();
if (d_lastFilterChoice.contains("*.txt"))
stylesheet = QSharedPointer<QFile>(new QFile(":/stylesheets/stats-text.xsl"));
else if (d_lastFilterChoice.contains("*.html"))
stylesheet = QSharedPointer<QFile>(new QFile(":/stylesheets/stats-html.xsl"));
else if (d_lastFilterChoice.contains("*.xls"))
stylesheet = QSharedPointer<QFile>(new QFile(":/stylesheets/stats-officexml.xsl"));
else
stylesheet = QSharedPointer<QFile>(new QFile(":/stylesheets/stats-csv.xsl"));
QFile data(filename);
if (!data.open(QFile::WriteOnly | QFile::Truncate)) {
QMessageBox::critical(this,
tr("Save file error"),
tr("Cannot save file %1 (error code %2)").arg(filename).arg(data.error()),
QMessageBox::Ok);
return;
}
QTextStream out(&data);
out.setCodec("UTF-8");
QString xmlStats = d_model->asXML();
XSLTransformer trans(*stylesheet);
out << trans.transform(xmlStats);
emit statusMessage(tr("File saved as %1").arg(filename));
}
void StatisticsWindow::copy()
{
QString csv;
QTextStream textstream(&csv, QIODevice::WriteOnly | QIODevice::Text);
selectionAsCSV(textstream, "\t");
if (!csv.isEmpty())
QApplication::clipboard()->setText(csv);
}
void StatisticsWindow::exportSelection()
{
QString filename(QFileDialog::getSaveFileName(this,
"Export selection",
QString(), "*.csv"));
if (filename.isNull())
return;
QFile file(filename);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
{
QMessageBox::critical(this,
tr("Error exporting selection"),
tr("Could open file for writing."),
QMessageBox::Ok);
return;
}
QTextStream textstream(&file);
textstream.setGenerateByteOrderMark(true);
selectionAsCSV(textstream, ";", true);
}
void StatisticsWindow::createActions()
{
// @TODO: move this non action related ui code to somewhere else. The .ui file preferably.
// Requires initialized UI.
//d_ui->resultsTable->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
d_ui->resultsTable->verticalHeader()->hide();
d_ui->resultsTable->sortByColumn(1, Qt::DescendingOrder);
d_ui->resultsTable->setItemDelegateForColumn(2, d_percentageCellDelegate.data());
// Only allow valid xpath queries to be submitted
//d_ui->filterLineEdit->setValidator(d_xpathValidator.data());
// When a row is activated, generate a query to be used in the main window to
// filter all the results so only the results which are accumulated in this
// row will be shown.
connect(d_ui->resultsTable, SIGNAL(activated(QModelIndex const &)),
SLOT(generateQuery(QModelIndex const &)));
// Toggle percentage column checkbox (is this needed?)
connect(d_ui->percentageCheckBox, SIGNAL(toggled(bool)),
SLOT(showPercentageChanged()));
connect(d_ui->yieldCheckBox, SIGNAL(toggled(bool)),
SLOT(showYieldChanged()));
connect(d_ui->attributeComboBox, SIGNAL(currentIndexChanged(int)),
SLOT(attributeChanged(int)));
}
void StatisticsWindow::generateQuery(QModelIndex const &index)
{
// Get the text from the first column, that is the found value
QString data = index.sibling(index.row(), 0).data(Qt::UserRole).toString();
if (data == QueryModel::MISSING_ATTRIBUTE)
return;
QString query = ::generateQuery(
d_filter,
d_ui->attributeComboBox->currentText(),
data);
emit entryActivated(data, query);
}
void StatisticsWindow::selectionAsCSV(QTextStream &output, QString const &separator, bool escape_quotes) const
{
// If there is no model attached (e.g. no corpus loaded) do nothing
if (!d_model)
return;
QModelIndexList rows = d_ui->resultsTable->selectionModel()->selectedRows();
// If there is nothing selected, do nothing
if (rows.isEmpty())
return;
foreach (QModelIndex const &row, rows)
{
// This only works if the selection behavior is SelectRows
if (escape_quotes)
output << '"' << d_model->data(row).toString().replace("\"", "\"\"") << '"'; // value
else
output << d_model->data(row).toString();
output
<< separator
<< d_model->data(row.sibling(row.row(), 1)).toString() // count
<< '\n';
}
}
void StatisticsWindow::startQuery()
{
setAggregateAttribute(d_ui->attributeComboBox->currentText());
d_ui->resultsTable->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
d_ui->resultsTable->horizontalHeader()->setResizeMode(1, QHeaderView::ResizeToContents);
d_ui->resultsTable->horizontalHeader()->setResizeMode(2, QHeaderView::Stretch);
d_ui->totalHitsLabel->clear();
d_ui->distinctValuesLabel->clear();
bool yield = d_ui->yieldCheckBox->isChecked();
d_model->runQuery(d_filter, d_ui->attributeComboBox->currentText(), yield);
emit saveStateChanged();
}
void StatisticsWindow::showPercentageChanged()
{
d_ui->resultsTable->setColumnHidden(2, !d_ui->percentageCheckBox->isChecked());
}
void StatisticsWindow::showYieldChanged()
{
if (!d_model.isNull())
startQuery();
}
void StatisticsWindow::progressStarted(int total)
{
d_ui->filterProgress->setMaximum(total);
d_ui->filterProgress->setDisabled(false);
d_ui->filterProgress->setVisible(true);
}
void StatisticsWindow::progressChanged(int percentage)
{
d_ui->filterProgress->setValue(percentage);
}
void StatisticsWindow::progressStopped(int n, int total)
{
updateResultsTotalCount();
d_ui->filterProgress->setVisible(false);
emit saveStateChanged();
}
void StatisticsWindow::closeEvent(QCloseEvent *event)
{
writeSettings();
event->accept();
}
void StatisticsWindow::readNodeAttributes()
{
QFile dtdFile(":/dtd/alpino_ds.dtd"); // XXX - hardcode?
if (!dtdFile.open(QFile::ReadOnly)) {
qWarning() << "StatisticsWindow::readNodeAttributes(): Could not read DTD.";
return;
}
QByteArray dtdData(dtdFile.readAll());
SimpleDTD sDTD(dtdData.constData());
// Should be safe to clear items now...
d_ui->attributeComboBox->clear();
// Do we have a node element?
ElementMap::const_iterator iter = sDTD.elementMap().find("node");
if (iter == sDTD.elementMap().end())
return;
std::set<std::string> attrs = iter->second;
QStringList attrList;
for (std::set<std::string>::const_iterator attrIter = attrs.begin();
attrIter != attrs.end(); ++ attrIter)
attrList.push_back(QString::fromUtf8(attrIter->c_str()));
std::sort(attrList.begin(), attrList.end());
d_ui->attributeComboBox->addItems(attrList);
}
bool StatisticsWindow::saveEnabled() const
{
if (d_model.isNull())
return false;
if (d_model->rowCount(QModelIndex()) == 0)
return false;
return true;
}
void StatisticsWindow::readSettings()
{
QSettings settings;
bool show = settings.value("query_show_percentage", true).toBool();
d_ui->percentageCheckBox->setChecked(show);
// Window geometry.
QPoint pos = settings.value("query_pos", QPoint(200, 200)).toPoint();
QSize size = settings.value("query_size", QSize(350, 400)).toSize();
resize(size);
// Move.
move(pos);
}
void StatisticsWindow::writeSettings()
{
QSettings settings;
settings.setValue("query_show_percentage", d_ui->percentageCheckBox->isChecked());
// Window geometry
settings.setValue("query_pos", pos());
settings.setValue("query_size", size());
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2018 - present Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <unordered_map>
#include <string>
#include "hip/hip_runtime.h"
#include "hip_hcc_internal.h"
#include "trace_helper.h"
constexpr unsigned __cudaFatMAGIC2 = 0x466243b1;
#define CLANG_OFFLOAD_BUNDLER_MAGIC "__CLANG_OFFLOAD_BUNDLE__"
#define AMDGCN_AMDHSA_TRIPLE "openmp-amdgcn--amdhsa"
struct __ClangOffloadBundleDesc {
uint64_t offset;
uint64_t size;
uint64_t tripleSize;
const char triple[1];
};
struct __ClangOffloadBundleHeader {
const char magic[sizeof(CLANG_OFFLOAD_BUNDLER_MAGIC) - 1];
uint64_t numBundles;
__ClangOffloadBundleDesc desc[1];
};
struct __CudaFatBinaryWrapper {
unsigned int magic;
unsigned int version;
__ClangOffloadBundleHeader* binary;
void* unused;
};
extern "C" std::vector<hipModule_t>*
__hipRegisterFatBinary(const void* data)
{
HIP_INIT();
const __CudaFatBinaryWrapper* fbwrapper = reinterpret_cast<const __CudaFatBinaryWrapper*>(data);
if (fbwrapper->magic != __cudaFatMAGIC2 || fbwrapper->version != 1) {
return nullptr;
}
const __ClangOffloadBundleHeader* header = fbwrapper->binary;
std::string magic(reinterpret_cast<const char*>(header), sizeof(CLANG_OFFLOAD_BUNDLER_MAGIC) - 1);
if (magic.compare(CLANG_OFFLOAD_BUNDLER_MAGIC)) {
return nullptr;
}
auto modules = new std::vector<hipModule_t>{g_deviceCnt};
if (!modules) {
return nullptr;
}
const __ClangOffloadBundleDesc* desc = &header->desc[0];
for (uint64_t i = 0; i < header->numBundles; ++i,
desc = reinterpret_cast<const __ClangOffloadBundleDesc*>(
reinterpret_cast<uintptr_t>(&desc->triple[0]) + desc->tripleSize)) {
std::string triple{&desc->triple[0], sizeof(AMDGCN_AMDHSA_TRIPLE) - 1};
if (triple.compare(AMDGCN_AMDHSA_TRIPLE))
continue;
std::string target{&desc->triple[sizeof(AMDGCN_AMDHSA_TRIPLE)],
desc->tripleSize - sizeof(AMDGCN_AMDHSA_TRIPLE)};
for (int deviceId = 0; deviceId < g_deviceCnt; ++deviceId) {
hsa_agent_t agent = g_allAgents[deviceId + 1];
char name[64] = {};
hsa_agent_get_info(agent, HSA_AGENT_INFO_NAME, name);
if (target.compare(name)) {
continue;
}
ihipModule_t* module = new ihipModule_t;
if (!module) {
continue;
}
hsa_executable_create_alt(HSA_PROFILE_FULL, HSA_DEFAULT_FLOAT_ROUNDING_MODE_DEFAULT, nullptr,
&module->executable);
std::string image{reinterpret_cast<const char*>(
reinterpret_cast<uintptr_t>(header) + desc->offset), desc->size};
module->executable = hip_impl::load_executable(image, module->executable, agent);
if (module->executable.handle) {
modules->at(deviceId) = module;
}
}
}
return modules;
}
std::map<const void*, std::vector<hipFunction_t>> g_functions;
extern "C" void __hipRegisterFunction(
std::vector<hipModule_t>* modules,
const void* hostFunction,
char* deviceFunction,
const char* deviceName,
unsigned int threadLimit,
uint3* tid,
uint3* bid,
dim3* blockDim,
dim3* gridDim,
int* wSize)
{
std::vector<hipFunction_t> functions{g_deviceCnt};
for (int deviceId = 0; deviceId < g_deviceCnt; ++deviceId) {
hipFunction_t function;
if (hipSuccess == hipModuleGetFunction(&function, modules->at(deviceId), deviceName)) {
functions[deviceId] = function;
}
}
g_functions.insert(std::make_pair(hostFunction, std::move(functions)));
}
extern "C" void __hipRegisterVar(
std::vector<hipModule_t>* modules,
char* hostVar,
char* deviceVar,
const char* deviceName,
int ext,
int size,
int constant,
int global)
{
}
extern "C" void __hipUnregisterFatBinary(std::vector<hipModule_t>* modules)
{
std::for_each(modules->begin(), modules->end(), [](hipModule_t module){ delete module; });
delete modules;
}
hipError_t hipConfigureCall(
dim3 gridDim,
dim3 blockDim,
size_t sharedMem,
hipStream_t stream)
{
auto ctx = ihipGetTlsDefaultCtx();
LockedAccessor_CtxCrit_t crit(ctx->criticalData());
crit->_execStack.push(ihipExec_t{gridDim, blockDim, sharedMem, stream});
return hipSuccess;
}
hipError_t hipSetupArgument(
const void *arg,
size_t size,
size_t offset)
{
auto ctx = ihipGetTlsDefaultCtx();
LockedAccessor_CtxCrit_t crit(ctx->criticalData());
auto& arguments = crit->_execStack.top()._arguments;
if (arguments.size() < offset + size) {
arguments.resize(offset + size);
}
::memcpy(&arguments[offset], arg, size);
return hipSuccess;
}
hipError_t hipLaunchByPtr(const void *hostFunction)
{
ihipExec_t exec;
{
auto ctx = ihipGetTlsDefaultCtx();
LockedAccessor_CtxCrit_t crit(ctx->criticalData());
exec = std::move(crit->_execStack.top());
crit->_execStack.pop();
}
int deviceId;
if (exec._hStream) {
deviceId = exec._hStream->getDevice()->_deviceId;
}
else if (ihipGetTlsDefaultCtx() && ihipGetTlsDefaultCtx()->getDevice()) {
deviceId = ihipGetTlsDefaultCtx()->getDevice()->_deviceId;
}
else {
deviceId = 0;
}
decltype(g_functions)::iterator it;
if ((it = g_functions.find(hostFunction)) == g_functions.end())
return hipErrorUnknown;
size_t size = exec._arguments.size();
void *extra[] = {
HIP_LAUNCH_PARAM_BUFFER_POINTER, &exec._arguments[0],
HIP_LAUNCH_PARAM_BUFFER_SIZE, &size,
HIP_LAUNCH_PARAM_END
};
return hipModuleLaunchKernel(it->second[deviceId],
exec._gridDim.x, exec._gridDim.y, exec._gridDim.z,
exec._blockDim.x, exec._blockDim.y, exec._blockDim.z,
exec._sharedMem, exec._hStream, nullptr, extra);
}
<commit_msg>Change HIP fat binary magic number<commit_after>/*
Copyright (c) 2018 - present Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <unordered_map>
#include <string>
#include "hip/hip_runtime.h"
#include "hip_hcc_internal.h"
#include "trace_helper.h"
constexpr unsigned __hipFatMAGIC2 = 0x48495046; // "HIPF"
#define CLANG_OFFLOAD_BUNDLER_MAGIC "__CLANG_OFFLOAD_BUNDLE__"
#define AMDGCN_AMDHSA_TRIPLE "hip-amdgcn-amd-amdhsa"
struct __ClangOffloadBundleDesc {
uint64_t offset;
uint64_t size;
uint64_t tripleSize;
const char triple[1];
};
struct __ClangOffloadBundleHeader {
const char magic[sizeof(CLANG_OFFLOAD_BUNDLER_MAGIC) - 1];
uint64_t numBundles;
__ClangOffloadBundleDesc desc[1];
};
struct __CudaFatBinaryWrapper {
unsigned int magic;
unsigned int version;
__ClangOffloadBundleHeader* binary;
void* unused;
};
extern "C" std::vector<hipModule_t>*
__hipRegisterFatBinary(const void* data)
{
HIP_INIT();
const __CudaFatBinaryWrapper* fbwrapper = reinterpret_cast<const __CudaFatBinaryWrapper*>(data);
if (fbwrapper->magic != __hipFatMAGIC2 || fbwrapper->version != 1) {
return nullptr;
}
const __ClangOffloadBundleHeader* header = fbwrapper->binary;
std::string magic(reinterpret_cast<const char*>(header), sizeof(CLANG_OFFLOAD_BUNDLER_MAGIC) - 1);
if (magic.compare(CLANG_OFFLOAD_BUNDLER_MAGIC)) {
return nullptr;
}
auto modules = new std::vector<hipModule_t>{g_deviceCnt};
if (!modules) {
return nullptr;
}
const __ClangOffloadBundleDesc* desc = &header->desc[0];
for (uint64_t i = 0; i < header->numBundles; ++i,
desc = reinterpret_cast<const __ClangOffloadBundleDesc*>(
reinterpret_cast<uintptr_t>(&desc->triple[0]) + desc->tripleSize)) {
std::string triple{&desc->triple[0], sizeof(AMDGCN_AMDHSA_TRIPLE) - 1};
if (triple.compare(AMDGCN_AMDHSA_TRIPLE))
continue;
std::string target{&desc->triple[sizeof(AMDGCN_AMDHSA_TRIPLE)],
desc->tripleSize - sizeof(AMDGCN_AMDHSA_TRIPLE)};
for (int deviceId = 0; deviceId < g_deviceCnt; ++deviceId) {
hsa_agent_t agent = g_allAgents[deviceId + 1];
char name[64] = {};
hsa_agent_get_info(agent, HSA_AGENT_INFO_NAME, name);
if (target.compare(name)) {
continue;
}
ihipModule_t* module = new ihipModule_t;
if (!module) {
continue;
}
hsa_executable_create_alt(HSA_PROFILE_FULL, HSA_DEFAULT_FLOAT_ROUNDING_MODE_DEFAULT, nullptr,
&module->executable);
std::string image{reinterpret_cast<const char*>(
reinterpret_cast<uintptr_t>(header) + desc->offset), desc->size};
module->executable = hip_impl::load_executable(image, module->executable, agent);
if (module->executable.handle) {
modules->at(deviceId) = module;
}
}
}
return modules;
}
std::map<const void*, std::vector<hipFunction_t>> g_functions;
extern "C" void __hipRegisterFunction(
std::vector<hipModule_t>* modules,
const void* hostFunction,
char* deviceFunction,
const char* deviceName,
unsigned int threadLimit,
uint3* tid,
uint3* bid,
dim3* blockDim,
dim3* gridDim,
int* wSize)
{
std::vector<hipFunction_t> functions{g_deviceCnt};
for (int deviceId = 0; deviceId < g_deviceCnt; ++deviceId) {
hipFunction_t function;
if (hipSuccess == hipModuleGetFunction(&function, modules->at(deviceId), deviceName)) {
functions[deviceId] = function;
}
}
g_functions.insert(std::make_pair(hostFunction, std::move(functions)));
}
extern "C" void __hipRegisterVar(
std::vector<hipModule_t>* modules,
char* hostVar,
char* deviceVar,
const char* deviceName,
int ext,
int size,
int constant,
int global)
{
}
extern "C" void __hipUnregisterFatBinary(std::vector<hipModule_t>* modules)
{
std::for_each(modules->begin(), modules->end(), [](hipModule_t module){ delete module; });
delete modules;
}
hipError_t hipConfigureCall(
dim3 gridDim,
dim3 blockDim,
size_t sharedMem,
hipStream_t stream)
{
auto ctx = ihipGetTlsDefaultCtx();
LockedAccessor_CtxCrit_t crit(ctx->criticalData());
crit->_execStack.push(ihipExec_t{gridDim, blockDim, sharedMem, stream});
return hipSuccess;
}
hipError_t hipSetupArgument(
const void *arg,
size_t size,
size_t offset)
{
auto ctx = ihipGetTlsDefaultCtx();
LockedAccessor_CtxCrit_t crit(ctx->criticalData());
auto& arguments = crit->_execStack.top()._arguments;
if (arguments.size() < offset + size) {
arguments.resize(offset + size);
}
::memcpy(&arguments[offset], arg, size);
return hipSuccess;
}
hipError_t hipLaunchByPtr(const void *hostFunction)
{
ihipExec_t exec;
{
auto ctx = ihipGetTlsDefaultCtx();
LockedAccessor_CtxCrit_t crit(ctx->criticalData());
exec = std::move(crit->_execStack.top());
crit->_execStack.pop();
}
int deviceId;
if (exec._hStream) {
deviceId = exec._hStream->getDevice()->_deviceId;
}
else if (ihipGetTlsDefaultCtx() && ihipGetTlsDefaultCtx()->getDevice()) {
deviceId = ihipGetTlsDefaultCtx()->getDevice()->_deviceId;
}
else {
deviceId = 0;
}
decltype(g_functions)::iterator it;
if ((it = g_functions.find(hostFunction)) == g_functions.end())
return hipErrorUnknown;
size_t size = exec._arguments.size();
void *extra[] = {
HIP_LAUNCH_PARAM_BUFFER_POINTER, &exec._arguments[0],
HIP_LAUNCH_PARAM_BUFFER_SIZE, &size,
HIP_LAUNCH_PARAM_END
};
return hipModuleLaunchKernel(it->second[deviceId],
exec._gridDim.x, exec._gridDim.y, exec._gridDim.z,
exec._blockDim.x, exec._blockDim.y, exec._blockDim.z,
exec._sharedMem, exec._hStream, nullptr, extra);
}
<|endoftext|> |
<commit_before>#include "hanse_depthengine/depth_engine.h"
DepthEngine::DepthEngine() :
depth_target_(0),
pressure_bias_(0),
pressure_current_(0),
pressure_init_(false),
emergency_stop_(false),
pids_enabled_(true),
depth_pid_enabled_(true),
motors_enabled_(true),
depth_output_(0)
{
// Initialisierung der Standard-Service Nachrichten.
enable_msg_.request.enable = true;
disable_msg_.request.enable = false;
// Registrierung der Publisher und Subscriber.
pub_depth_current_ = nh_.advertise<std_msgs::Float64>("/hanse/pid/depth/input", 1);
pub_depth_target_ = nh_.advertise<std_msgs::Float64>("/hanse/pid/depth/target",1);
pub_motor_up_ = nh_.advertise<hanse_msgs::sollSpeed>("/hanse/motors/up", 1);
sub_pressure_ = nh_.subscribe<hanse_msgs::pressure>("/hanse/pressure/depth", 10,
&DepthEngine::pressureCallback, this);
sub_depth_output_ = nh_.subscribe<std_msgs::Float64>(
"/hanse/pid/depth/output", 10, &DepthEngine::depthOutputCallback, this);
publish_timer_ = nh_.createTimer(ros::Duration(1),
&DepthEngine::publishTimerCallback, this);
gamepad_timer_ = nh_.createTimer(ros::Duration(300),
&DepthEngine::gamepadTimerCallback, this);
sub_mux_selected_ = nh_.subscribe<std_msgs::String>("/hanse/commands/cmd_vel_mux/selected",
1, &DepthEngine::muxSelectedCallback, this);
// Registrierung der Services.
srv_handle_engine_command_ = nh_.advertiseService("engine/depth/handleEngineCommand",
&DepthEngine::handleEngineCommand, this);
srv_enable_depth_pid_ = nh_.advertiseService("engine/depth/enableDepthPid",
&DepthEngine::enableDepthPid, this);
srv_enable_motors_ = nh_.advertiseService("engine/depth/enableMotors",
&DepthEngine::enableMotors, this);
srv_reset_zero_pressure_ = nh_.advertiseService("engine/depth/resetZeroPressure",
&DepthEngine::resetZeroPressure, this);
srv_set_emergency_stop_ = nh_.advertiseService("engine/depth/setEmergencyStop",
&DepthEngine::setEmergencyStop, this);
srv_set_depth_ = nh_.advertiseService("engine/depth/setDepth", &DepthEngine::setDepth, this);
srv_increment_depth_ = nh_.advertiseService("engine/depth/incDepth", &DepthEngine::incrementDepth, this);
dyn_reconfigure_cb_ = boost::bind(&DepthEngine::dynReconfigureCallback, this, _1, _2);
dyn_reconfigure_srv_.setCallback(dyn_reconfigure_cb_);
// Registrierung der Service Clients.
srv_client_depth_pid_ = nh_.serviceClient<hanse_srvs::Bool>("/hanse/pid/depth/enable");
// Aktivierung des Tiefen-PID-Regler.
if (config_.depth_pid_enabled_at_start)
{
if (callDepthPidEnableService(true))
{
ROS_INFO("Depth PID enabled.");
depth_pid_enabled_ = true;
}
else
{
ROS_ERROR("Depth PID couldn't be enabled. Shutdown.");
ros::shutdown();
}
}
ROS_INFO("Depth engine started.");
}
void DepthEngine::dynReconfigureCallback(hanse_depthengine::DepthengineConfig &config, uint32_t level)
{
ROS_INFO("got new parameters, level=%d", level);
config_ = config;
publish_timer_.setPeriod(ros::Duration(1.0/config.publish_frequency));
gamepad_timer_.setPeriod(ros::Duration(config.gamepad_timeout));
}
void DepthEngine::velocityCallback(const geometry_msgs::Twist::ConstPtr &twist)
{
gamepad_timeout_ = false;
if (gamepad_running_)
{
gamepad_timer_.stop();
}
if (twist->linear.z != 0)
{
depth_target_ = twist->linear.z;
if (depth_target_ < 0)
{
depth_target_ = 0;
}
}
if (gamepad_running_)
{
gamepad_timer_.start();
}
}
// Auswertung und Zwischenspeicherung der Eingabedaten des Drucksensors.
void DepthEngine::pressureCallback(
const hanse_msgs::pressure::ConstPtr& pressure)
{
if (!pressure_init_)
{
pressure_bias_ = pressure->data;
pressure_init_ = true;
}
pressure_current_ = pressure->data;
}
// Speicherung der Zieltiefe
bool DepthEngine::setDepth(
hanse_srvs::SetTarget::Request &req,
hanse_srvs::SetTarget::Response &res)
{
depth_target_ = req.target;
return true;
}
bool DepthEngine::incrementDepth(hanse_srvs::SetTarget::Request &req,
hanse_srvs::SetTarget::Response &res)
{
depth_target_ += req.target;
if (depth_target_ < 0)
{
depth_target_ = 0;
}
}
// Auswertung und Zwischenspeicherung der Ausgabedaten des Druck-PID-Reglers.
void DepthEngine::depthOutputCallback(
const std_msgs::Float64::ConstPtr& depthOutput)
{
this->depth_output_ = depthOutput->data;
}
void DepthEngine::muxSelectedCallback(const std_msgs::String::ConstPtr &topic)
{
if (topic->data.find("cmd_vel_joystick") != std::string::npos)
{
gamepad_running_ = true;
gamepad_timer_.start();
}
else
{
gamepad_running_ = false;
gamepad_timer_.stop();
}
}
void DepthEngine::gamepadTimerCallback(const ros::TimerEvent &e)
{
gamepad_timer_.stop();
gamepad_timeout_ = true;
depth_target_ = 0;
ROS_INFO("Gamepad connection lost. Come up.");
}
// Ausführung jeweils nach Ablauf des Timers. Wird verwendet, um sämtliche
// Ausgaben auf die vorgesehenen Topics zu schreiben.
void DepthEngine::publishTimerCallback(const ros::TimerEvent &e)
{
hanse_msgs::sollSpeed motor_height_msg;
motor_height_msg.header.stamp = ros::Time::now();
if(emergency_stop_ || gamepad_timeout_)
{
motor_height_msg.data = 64;
}
else
{
if (motors_enabled_)
{
// Tiefensteuerung.
std_msgs::Float64 depth_target_msg;
depth_target_msg.data = depth_target_ + pressure_bias_;
if (depth_target_msg.data < config_.min_depth_pressure)
{
depth_target_msg.data = config_.min_depth_pressure;
}
else if(depth_target_msg.data > config_.max_depth_pressure)
{
depth_target_msg.data = config_.max_depth_pressure;
}
pub_depth_target_.publish(depth_target_msg);
std_msgs::Float64 depth_current_msg;
depth_current_msg.data = pressure_current_;
pub_depth_current_.publish(depth_current_msg);
motor_height_msg.data = -depth_output_;
}
else
{
motor_height_msg.data = 0;
}
}
pub_motor_up_.publish(motor_height_msg);
}
bool DepthEngine::handleEngineCommand(hanse_srvs::EngineCommand::Request &req,
hanse_srvs::EngineCommand::Response &res)
{
if (req.setEmergencyStop && !emergency_stop_)
{
emergency_stop_ = true;
pids_enabled_ = false;
// Deaktivierung des Tiefen-PID-Reglers.
if(depth_pid_enabled_)
{
if (callDepthPidEnableService(false))
{
ROS_INFO("Depth PID disabled.");
}
else
{
ROS_ERROR("Depth PID couldn't be disabled.");
}
}
// Tiefe auf 0 setzen
depth_target_ = 0;
}
else if (!req.setEmergencyStop)
{
if (emergency_stop_)
{
emergency_stop_ = false;
pids_enabled_ = true;
if (req.enableDepthPid)
{
if (callDepthPidEnableService(true))
{
ROS_INFO("Depth PID enabled.");
}
else
{
ROS_ERROR("Depth PID couldn't be enabled.");
}
}
depth_pid_enabled_ = req.enableDepthPid;
}
else
{
if (!depth_pid_enabled_ && req.enableDepthPid)
{
if (callDepthPidEnableService(true))
{
ROS_INFO("Depth PID enabled.");
depth_pid_enabled_ = true;
}
else
{
ROS_ERROR("Depth PID couldn't be enabled.");
}
}
else if (depth_pid_enabled_ && !req.enableDepthPid)
{
if (callDepthPidEnableService(false))
{
ROS_INFO("Depth PID disabled.");
depth_pid_enabled_ = false;
}
else
{
ROS_ERROR("Depth PID couldn't be disabled.");
}
}
}
if (motors_enabled_ != req.enableMotors)
{
if (req.enableMotors)
{
ROS_INFO("Motors enabled.");
}
else
{
ROS_INFO("Motors disabled.");
}
motors_enabled_ = req.enableMotors;
}
if (req.resetZeroPressure)
{
ROS_INFO("Resetting zero pressure.");
pressure_init_ = false;
}
}
return true;
}
bool DepthEngine::enableDepthPid(hanse_srvs::Bool::Request &req,
hanse_srvs::Bool::Response &res)
{
if (pids_enabled_) {
if (!depth_pid_enabled_ && req.enable)
{
if (callDepthPidEnableService(true))
{
ROS_INFO("Depth PID enabled.");
depth_pid_enabled_ = true;
}
else
{
ROS_ERROR("Depth PID couldn't be enabled.");
}
}
else if (depth_pid_enabled_ && !req.enable)
{
if (callDepthPidEnableService(false))
{
ROS_INFO("Depth PID disabled.");
depth_pid_enabled_ = false;
}
else
{
ROS_ERROR("Depth PID couldn't be disabled.");
}
}
}
else
{
depth_pid_enabled_ = req.enable;
}
return true;
}
bool DepthEngine::enableMotors(hanse_srvs::Bool::Request &req,
hanse_srvs::Bool::Response &res)
{
motors_enabled_ = req.enable;
return true;
}
bool DepthEngine::resetZeroPressure(hanse_srvs::Empty::Request &req,
hanse_srvs::Empty::Response &res)
{
pressure_init_ = false;
return true;
}
bool DepthEngine::setEmergencyStop(hanse_srvs::Bool::Request &req,
hanse_srvs::Bool::Response &res)
{
if (req.enable && !emergency_stop_)
{
emergency_stop_ = true;
pids_enabled_ = false;
// Deaktivierung des Tiefen-PID-Reglers.
if(depth_pid_enabled_) {
if (callDepthPidEnableService(false))
{
ROS_INFO("Depth PID disabled.");
}
else
{
ROS_ERROR("Depth PID couldn't be disabled.");
}
}
// Tiefe auf 0 setzen
depth_target_ = 0;
}
else if (!req.enable && emergency_stop_)
{
emergency_stop_ = false;
pids_enabled_ = true;
// Aktivierung der zuvor aktivierten PID Regler
if (depth_pid_enabled_)
{
if (callDepthPidEnableService(true))
{
ROS_INFO("Depth PID enabled.");
}
else
{
ROS_ERROR("Depth PID couldn't be enabled.");
}
}
}
return true;
}
bool DepthEngine::callDepthPidEnableService(const bool msg)
{
int8_t counter = 0;
ros::Rate loop_rate(4);
bool success = false;
while(ros::ok() && counter < NUM_SERVICE_LOOPS)
{
if ((msg && srv_client_depth_pid_.call(enable_msg_)) ||
(!msg && srv_client_depth_pid_.call(disable_msg_)))
{
success = true;
break;
}
counter++;
loop_rate.sleep();
}
return success;
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "depthengine_node");
ros::start();
DepthEngine engine_control;
ros::spin();
}
<commit_msg>fixed setting depth in depth engine<commit_after>#include "hanse_depthengine/depth_engine.h"
DepthEngine::DepthEngine() :
depth_target_(0),
pressure_bias_(0),
pressure_current_(0),
pressure_init_(false),
emergency_stop_(false),
pids_enabled_(true),
depth_pid_enabled_(true),
motors_enabled_(true),
depth_output_(0)
{
// Initialisierung der Standard-Service Nachrichten.
enable_msg_.request.enable = true;
disable_msg_.request.enable = false;
// Registrierung der Publisher und Subscriber.
pub_depth_current_ = nh_.advertise<std_msgs::Float64>("/hanse/pid/depth/input", 1);
pub_depth_target_ = nh_.advertise<std_msgs::Float64>("/hanse/pid/depth/target",1);
pub_motor_up_ = nh_.advertise<hanse_msgs::sollSpeed>("/hanse/motors/up", 1);
sub_pressure_ = nh_.subscribe<hanse_msgs::pressure>("/hanse/pressure/depth", 10,
&DepthEngine::pressureCallback, this);
sub_depth_output_ = nh_.subscribe<std_msgs::Float64>(
"/hanse/pid/depth/output", 10, &DepthEngine::depthOutputCallback, this);
publish_timer_ = nh_.createTimer(ros::Duration(1),
&DepthEngine::publishTimerCallback, this);
gamepad_timer_ = nh_.createTimer(ros::Duration(300),
&DepthEngine::gamepadTimerCallback, this);
sub_mux_selected_ = nh_.subscribe<std_msgs::String>("/hanse/commands/cmd_vel_mux/selected",
1, &DepthEngine::muxSelectedCallback, this);
// Registrierung der Services.
srv_handle_engine_command_ = nh_.advertiseService("engine/depth/handleEngineCommand",
&DepthEngine::handleEngineCommand, this);
srv_enable_depth_pid_ = nh_.advertiseService("engine/depth/enableDepthPid",
&DepthEngine::enableDepthPid, this);
srv_enable_motors_ = nh_.advertiseService("engine/depth/enableMotors",
&DepthEngine::enableMotors, this);
srv_reset_zero_pressure_ = nh_.advertiseService("engine/depth/resetZeroPressure",
&DepthEngine::resetZeroPressure, this);
srv_set_emergency_stop_ = nh_.advertiseService("engine/depth/setEmergencyStop",
&DepthEngine::setEmergencyStop, this);
srv_set_depth_ = nh_.advertiseService("engine/depth/setDepth", &DepthEngine::setDepth, this);
srv_increment_depth_ = nh_.advertiseService("engine/depth/incDepth", &DepthEngine::incrementDepth, this);
dyn_reconfigure_cb_ = boost::bind(&DepthEngine::dynReconfigureCallback, this, _1, _2);
dyn_reconfigure_srv_.setCallback(dyn_reconfigure_cb_);
// Registrierung der Service Clients.
srv_client_depth_pid_ = nh_.serviceClient<hanse_srvs::Bool>("/hanse/pid/depth/enable");
// Aktivierung des Tiefen-PID-Regler.
if (config_.depth_pid_enabled_at_start)
{
if (callDepthPidEnableService(true))
{
ROS_INFO("Depth PID enabled.");
depth_pid_enabled_ = true;
}
else
{
ROS_ERROR("Depth PID couldn't be enabled. Shutdown.");
ros::shutdown();
}
}
ROS_INFO("Depth engine started.");
}
void DepthEngine::dynReconfigureCallback(hanse_depthengine::DepthengineConfig &config, uint32_t level)
{
ROS_INFO("got new parameters, level=%d", level);
config_ = config;
publish_timer_.setPeriod(ros::Duration(1.0/config.publish_frequency));
gamepad_timer_.setPeriod(ros::Duration(config.gamepad_timeout));
}
void DepthEngine::velocityCallback(const geometry_msgs::Twist::ConstPtr &twist)
{
gamepad_timeout_ = false;
if (gamepad_running_)
{
gamepad_timer_.stop();
}
if (twist->linear.z != 0)
{
depth_target_ = twist->linear.z;
if (depth_target_ < 0)
{
depth_target_ = 0;
}
}
if (gamepad_running_)
{
gamepad_timer_.start();
}
}
// Auswertung und Zwischenspeicherung der Eingabedaten des Drucksensors.
void DepthEngine::pressureCallback(
const hanse_msgs::pressure::ConstPtr& pressure)
{
if (!pressure_init_)
{
pressure_bias_ = pressure->data;
pressure_init_ = true;
}
pressure_current_ = pressure->data;
}
// Speicherung der Zieltiefe
bool DepthEngine::setDepth(
hanse_srvs::SetTarget::Request &req,
hanse_srvs::SetTarget::Response &res)
{
depth_target_ = req.target;
return true;
}
bool DepthEngine::incrementDepth(hanse_srvs::SetTarget::Request &req,
hanse_srvs::SetTarget::Response &res)
{
depth_target_ += req.target;
if (depth_target_ < 0)
{
depth_target_ = 0;
}
return true;
}
// Auswertung und Zwischenspeicherung der Ausgabedaten des Druck-PID-Reglers.
void DepthEngine::depthOutputCallback(
const std_msgs::Float64::ConstPtr& depth_output)
{
depth_output_ = depth_output->data;
}
void DepthEngine::muxSelectedCallback(const std_msgs::String::ConstPtr &topic)
{
if (topic->data.find("cmd_vel_joystick") != std::string::npos)
{
gamepad_running_ = true;
gamepad_timer_.start();
}
else
{
gamepad_timeout_ = false;
gamepad_running_ = false;
gamepad_timer_.stop();
}
}
void DepthEngine::gamepadTimerCallback(const ros::TimerEvent &e)
{
gamepad_timer_.stop();
gamepad_timeout_ = true;
depth_target_ = 0;
ROS_INFO("Gamepad connection lost. Come up.");
}
// Ausführung jeweils nach Ablauf des Timers. Wird verwendet, um sämtliche
// Ausgaben auf die vorgesehenen Topics zu schreiben.
void DepthEngine::publishTimerCallback(const ros::TimerEvent &e)
{
hanse_msgs::sollSpeed motor_height_msg;
motor_height_msg.header.stamp = ros::Time::now();
if(emergency_stop_ || gamepad_timeout_)
{
motor_height_msg.data = 64;
}
else
{
if (motors_enabled_)
{
// Tiefensteuerung.
std_msgs::Float64 depth_target_msg;
depth_target_msg.data = depth_target_ + pressure_bias_;
if (depth_target_msg.data < config_.min_depth_pressure)
{
depth_target_msg.data = config_.min_depth_pressure;
}
else if(depth_target_msg.data > config_.max_depth_pressure)
{
depth_target_msg.data = config_.max_depth_pressure;
}
pub_depth_target_.publish(depth_target_msg);
std_msgs::Float64 depth_current_msg;
depth_current_msg.data = pressure_current_;
pub_depth_current_.publish(depth_current_msg);
motor_height_msg.data = -depth_output_;
}
else
{
motor_height_msg.data = 0;
}
}
pub_motor_up_.publish(motor_height_msg);
}
bool DepthEngine::handleEngineCommand(hanse_srvs::EngineCommand::Request &req,
hanse_srvs::EngineCommand::Response &res)
{
if (req.setEmergencyStop && !emergency_stop_)
{
emergency_stop_ = true;
pids_enabled_ = false;
// Deaktivierung des Tiefen-PID-Reglers.
if(depth_pid_enabled_)
{
if (callDepthPidEnableService(false))
{
ROS_INFO("Depth PID disabled.");
}
else
{
ROS_ERROR("Depth PID couldn't be disabled.");
}
}
// Tiefe auf 0 setzen
depth_target_ = 0;
}
else if (!req.setEmergencyStop)
{
if (emergency_stop_)
{
emergency_stop_ = false;
pids_enabled_ = true;
if (req.enableDepthPid)
{
if (callDepthPidEnableService(true))
{
ROS_INFO("Depth PID enabled.");
}
else
{
ROS_ERROR("Depth PID couldn't be enabled.");
}
}
depth_pid_enabled_ = req.enableDepthPid;
}
else
{
if (!depth_pid_enabled_ && req.enableDepthPid)
{
if (callDepthPidEnableService(true))
{
ROS_INFO("Depth PID enabled.");
depth_pid_enabled_ = true;
}
else
{
ROS_ERROR("Depth PID couldn't be enabled.");
}
}
else if (depth_pid_enabled_ && !req.enableDepthPid)
{
if (callDepthPidEnableService(false))
{
ROS_INFO("Depth PID disabled.");
depth_pid_enabled_ = false;
}
else
{
ROS_ERROR("Depth PID couldn't be disabled.");
}
}
}
if (motors_enabled_ != req.enableMotors)
{
if (req.enableMotors)
{
ROS_INFO("Motors enabled.");
}
else
{
ROS_INFO("Motors disabled.");
}
motors_enabled_ = req.enableMotors;
}
if (req.resetZeroPressure)
{
ROS_INFO("Resetting zero pressure.");
pressure_init_ = false;
}
}
return true;
}
bool DepthEngine::enableDepthPid(hanse_srvs::Bool::Request &req,
hanse_srvs::Bool::Response &res)
{
if (pids_enabled_) {
if (!depth_pid_enabled_ && req.enable)
{
if (callDepthPidEnableService(true))
{
ROS_INFO("Depth PID enabled.");
depth_pid_enabled_ = true;
}
else
{
ROS_ERROR("Depth PID couldn't be enabled.");
}
}
else if (depth_pid_enabled_ && !req.enable)
{
if (callDepthPidEnableService(false))
{
ROS_INFO("Depth PID disabled.");
depth_pid_enabled_ = false;
}
else
{
ROS_ERROR("Depth PID couldn't be disabled.");
}
}
}
else
{
depth_pid_enabled_ = req.enable;
}
return true;
}
bool DepthEngine::enableMotors(hanse_srvs::Bool::Request &req,
hanse_srvs::Bool::Response &res)
{
motors_enabled_ = req.enable;
return true;
}
bool DepthEngine::resetZeroPressure(hanse_srvs::Empty::Request &req,
hanse_srvs::Empty::Response &res)
{
pressure_init_ = false;
return true;
}
bool DepthEngine::setEmergencyStop(hanse_srvs::Bool::Request &req,
hanse_srvs::Bool::Response &res)
{
if (req.enable && !emergency_stop_)
{
emergency_stop_ = true;
pids_enabled_ = false;
// Deaktivierung des Tiefen-PID-Reglers.
if(depth_pid_enabled_) {
if (callDepthPidEnableService(false))
{
ROS_INFO("Depth PID disabled.");
}
else
{
ROS_ERROR("Depth PID couldn't be disabled.");
}
}
// Tiefe auf 0 setzen
depth_target_ = 0;
}
else if (!req.enable && emergency_stop_)
{
emergency_stop_ = false;
pids_enabled_ = true;
// Aktivierung der zuvor aktivierten PID Regler
if (depth_pid_enabled_)
{
if (callDepthPidEnableService(true))
{
ROS_INFO("Depth PID enabled.");
}
else
{
ROS_ERROR("Depth PID couldn't be enabled.");
}
}
}
return true;
}
bool DepthEngine::callDepthPidEnableService(const bool msg)
{
int8_t counter = 0;
ros::Rate loop_rate(4);
bool success = false;
while(ros::ok() && counter < NUM_SERVICE_LOOPS)
{
if ((msg && srv_client_depth_pid_.call(enable_msg_)) ||
(!msg && srv_client_depth_pid_.call(disable_msg_)))
{
success = true;
break;
}
counter++;
loop_rate.sleep();
}
return success;
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "depthengine_node");
ros::start();
DepthEngine engine_control;
ros::spin();
}
<|endoftext|> |
<commit_before>// Filename: KrylovLinearSolver.C
// Created on 09 Sep 2003 by Boyce Griffith
//
// Copyright (c) 2002-2010, Boyce Griffith
// 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 New York 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 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 "KrylovLinearSolver.h"
/////////////////////////////// INCLUDES /////////////////////////////////////
#ifndef included_IBTK_config
#include <IBTK_config.h>
#define included_IBTK_config
#endif
#ifndef included_SAMRAI_config
#include <SAMRAI_config.h>
#define included_SAMRAI_config
#endif
// IBTK INCLUDES
#include <ibtk/namespaces.h>
/////////////////////////////// NAMESPACE ////////////////////////////////////
namespace IBTK
{
/////////////////////////////// STATIC ///////////////////////////////////////
/////////////////////////////// PUBLIC ///////////////////////////////////////
KrylovLinearSolver::KrylovLinearSolver(
const std::string& object_name,
bool homogeneous_bc)
: LinearSolver(object_name, homogeneous_bc),
d_A(NULL),
d_pc_solver(NULL),
d_x(NULL),
d_b(NULL)
{
// intentionally blank
return;
}// KrylovLinearSolver()
KrylovLinearSolver::~KrylovLinearSolver()
{
// intentionally blank
return;
}// ~KrylovLinearSolver()
void
KrylovLinearSolver::setHierarchyMathOps(
Pointer<HierarchyMathOps> hier_math_ops)
{
KrylovLinearSolver::setHierarchyMathOps(hier_math_ops);
if (!d_A.isNull()) d_A->setHierarchyMathOps(d_hier_math_ops);
if (!d_pc_solver.isNull()) d_pc_solver->setHierarchyMathOps(d_hier_math_ops);
return;
}// setHierarchyMathOps
void
KrylovLinearSolver::setOperator(
Pointer<LinearOperator> A)
{
Pointer<LinearOperator> A_old = d_A;
d_A = A;
d_A->setHomogeneousBc(d_homogeneous_bc);
d_A->setSolutionTime(d_solution_time);
d_A->setTimeInterval(d_current_time, d_new_time);
if (d_is_initialized && (d_A != A_old) && !d_A.isNull())
{
d_A->initializeOperatorState(*d_x, *d_b);
}
return;
}// setOperator
Pointer<LinearOperator>
KrylovLinearSolver::getOperator() const
{
return d_A;
}// getOperator
void
KrylovLinearSolver::setPreconditioner(
Pointer<LinearSolver> pc_solver)
{
Pointer<LinearSolver> pc_solver_old = d_pc_solver;
d_pc_solver = pc_solver;
d_pc_solver->setHomogeneousBc(true);
d_pc_solver->setSolutionTime(d_solution_time);
d_pc_solver->setTimeInterval(d_current_time, d_new_time);
if (d_is_initialized && (d_pc_solver != pc_solver_old) && !d_pc_solver.isNull())
{
d_pc_solver->initializeSolverState(*d_b, *d_b);
}
return;
}// setPreconditioner
Pointer<LinearSolver>
KrylovLinearSolver::getPreconditioner() const
{
return d_pc_solver;
}// getPreconditioner
/////////////////////////////// PRIVATE //////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
}// namespace IBTK
//////////////////////////////////////////////////////////////////////////////
<commit_msg>branch boyceg: fixed bug in KrylovLinearSolver::setHierarchyMathOps()<commit_after>// Filename: KrylovLinearSolver.C
// Created on 09 Sep 2003 by Boyce Griffith
//
// Copyright (c) 2002-2010, Boyce Griffith
// 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 New York 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 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 "KrylovLinearSolver.h"
/////////////////////////////// INCLUDES /////////////////////////////////////
#ifndef included_IBTK_config
#include <IBTK_config.h>
#define included_IBTK_config
#endif
#ifndef included_SAMRAI_config
#include <SAMRAI_config.h>
#define included_SAMRAI_config
#endif
// IBTK INCLUDES
#include <ibtk/namespaces.h>
/////////////////////////////// NAMESPACE ////////////////////////////////////
namespace IBTK
{
/////////////////////////////// STATIC ///////////////////////////////////////
/////////////////////////////// PUBLIC ///////////////////////////////////////
KrylovLinearSolver::KrylovLinearSolver(
const std::string& object_name,
bool homogeneous_bc)
: LinearSolver(object_name, homogeneous_bc),
d_A(NULL),
d_pc_solver(NULL),
d_x(NULL),
d_b(NULL)
{
// intentionally blank
return;
}// KrylovLinearSolver()
KrylovLinearSolver::~KrylovLinearSolver()
{
// intentionally blank
return;
}// ~KrylovLinearSolver()
void
KrylovLinearSolver::setHierarchyMathOps(
Pointer<HierarchyMathOps> hier_math_ops)
{
LinearSolver::setHierarchyMathOps(hier_math_ops);
if (!d_A.isNull()) d_A->setHierarchyMathOps(d_hier_math_ops);
if (!d_pc_solver.isNull()) d_pc_solver->setHierarchyMathOps(d_hier_math_ops);
return;
}// setHierarchyMathOps
void
KrylovLinearSolver::setOperator(
Pointer<LinearOperator> A)
{
Pointer<LinearOperator> A_old = d_A;
d_A = A;
d_A->setHomogeneousBc(d_homogeneous_bc);
d_A->setSolutionTime(d_solution_time);
d_A->setTimeInterval(d_current_time, d_new_time);
if (d_is_initialized && (d_A != A_old) && !d_A.isNull())
{
d_A->initializeOperatorState(*d_x, *d_b);
}
return;
}// setOperator
Pointer<LinearOperator>
KrylovLinearSolver::getOperator() const
{
return d_A;
}// getOperator
void
KrylovLinearSolver::setPreconditioner(
Pointer<LinearSolver> pc_solver)
{
Pointer<LinearSolver> pc_solver_old = d_pc_solver;
d_pc_solver = pc_solver;
d_pc_solver->setHomogeneousBc(true);
d_pc_solver->setSolutionTime(d_solution_time);
d_pc_solver->setTimeInterval(d_current_time, d_new_time);
if (d_is_initialized && (d_pc_solver != pc_solver_old) && !d_pc_solver.isNull())
{
d_pc_solver->initializeSolverState(*d_b, *d_b);
}
return;
}// setPreconditioner
Pointer<LinearSolver>
KrylovLinearSolver::getPreconditioner() const
{
return d_pc_solver;
}// getPreconditioner
/////////////////////////////// PRIVATE //////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
}// namespace IBTK
//////////////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>#include <algorithm>
#include <cassert>
#include <string>
#include "TimeWarpEventSet.hpp"
#include "utility/warnings.hpp"
namespace warped {
void TimeWarpEventSet::initialize (unsigned int num_of_objects,
unsigned int num_of_schedulers,
bool is_lp_migration_on,
unsigned int num_of_worker_threads) {
num_of_objects_ = num_of_objects;
num_of_schedulers_ = num_of_schedulers;
is_lp_migration_on_ = is_lp_migration_on;
/* Create the input and processed queues and their locks.
Also create the input queue-scheduler map and scheduled event pointer. */
input_queue_lock_ = make_unique<std::mutex []>(num_of_objects);
for (unsigned int obj_id = 0; obj_id < num_of_objects; obj_id++) {
input_queue_.push_back(
make_unique<std::multiset<std::shared_ptr<Event>, compareEvents>>());
processed_queue_.push_back(
make_unique<std::deque<std::shared_ptr<Event>>>());
scheduled_event_pointer_.push_back(nullptr);
input_queue_scheduler_map_.push_back(obj_id % num_of_schedulers);
}
/* Create the schedule queues and their locks. */
for (unsigned int scheduler_id = 0; scheduler_id < num_of_schedulers; scheduler_id++) {
schedule_queue_.push_back(
make_unique<std::multiset<std::shared_ptr<Event>, compareEvents>>());
}
schedule_queue_lock_ = make_unique<TicketLock []>(num_of_schedulers);
/* Map worker threads to schedule queues. */
for (unsigned int thread_id = 0;
thread_id < num_of_worker_threads; thread_id++) {
worker_thread_scheduler_map_.push_back(thread_id % num_of_schedulers);
}
}
void TimeWarpEventSet::acquireInputQueueLock (unsigned int obj_id) {
input_queue_lock_[obj_id].lock();
}
void TimeWarpEventSet::releaseInputQueueLock (unsigned int obj_id) {
input_queue_lock_[obj_id].unlock();
}
/*
* NOTE: caller must always have the input queue lock for the object with id obj_id
*
* NOTE: scheduled_event_pointer is also protected by the input queue lock
*/
void TimeWarpEventSet::insertEvent (unsigned int obj_id, std::shared_ptr<Event> event) {
// Always insert event into input queue
input_queue_[obj_id]->insert(event);
unsigned int scheduler_id = input_queue_scheduler_map_[obj_id];
if (scheduled_event_pointer_[obj_id] == nullptr) {
// If no event is currently scheduled. This can only happen if the thread that handles events
// for object with id obj_id has determined that there are no more events left in it's input
// queue
assert(input_queue_[obj_id]->size() == 1);
schedule_queue_lock_[scheduler_id].lock();
schedule_queue_[scheduler_id]->insert(event);
schedule_queue_lock_[scheduler_id].unlock();
scheduled_event_pointer_[obj_id] = event;
} else {
auto smallest_event = *input_queue_[obj_id]->begin();
if (smallest_event != scheduled_event_pointer_[obj_id]) {
// If the pointer comparison of the smallest event does not match scheduled event, well
// that means we should update the schedule queue...
schedule_queue_lock_[scheduler_id].lock();
if (auto num_erased = schedule_queue_[scheduler_id]->erase(scheduled_event_pointer_[obj_id])) {
// ...but only if the event was successfully erased from the schedule queue. If it is
// not then the event is already being processed and a rollback will have to occur.
assert(num_erased == 1);
unused(num_erased);
schedule_queue_[scheduler_id]->insert(smallest_event);
scheduled_event_pointer_[obj_id] = smallest_event;
}
schedule_queue_lock_[scheduler_id].unlock();
}
}
}
/*
* NOTE: caller must always have the input queue lock for the object with id obj_id
*/
std::shared_ptr<Event> TimeWarpEventSet::getEvent (unsigned int thread_id) {
unsigned int scheduler_id = worker_thread_scheduler_map_[thread_id];
schedule_queue_lock_[scheduler_id].lock();
auto event_iterator = schedule_queue_[scheduler_id]->begin();
auto event = (event_iterator != schedule_queue_[scheduler_id]->end()) ?
*event_iterator : nullptr;
if (event != nullptr) {
schedule_queue_[scheduler_id]->erase(event_iterator);
}
// NOTE: scheduled_event_pointer is not changed here so that other threads will not schedule new
// events and this thread can move events into processed queue and update schedule queue correctly.
// NOTE: Event also remains in input queue until processing done. If this a a negative event
// then, a rollback will bring the processed positive event back to input queue and they will
// be cancelled.
schedule_queue_lock_[scheduler_id].unlock();
return event;
}
/*
* NOTE: caller must have the input queue lock for the object with id obj_id
*/
std::shared_ptr<Event> TimeWarpEventSet::lastProcessedEvent (unsigned int obj_id) {
return ((processed_queue_[obj_id]->size()) ? processed_queue_[obj_id]->back() : nullptr);
}
/*
* NOTE: caller must have the input queue lock for the object with id obj_id
*/
void TimeWarpEventSet::rollback (unsigned int obj_id, std::shared_ptr<Event> straggler_event) {
// Every event GREATER OR EQUAL to straggler event must remove from the processed queue and
// reinserted back into input queue.
// EQUAL will ensure that a negative message will properly be cancelled out.
auto event_riterator = processed_queue_[obj_id]->rbegin(); // Starting with largest event
while (event_riterator != processed_queue_[obj_id]->rend() && (**event_riterator >= *straggler_event)){
auto event = processed_queue_[obj_id]->back(); // Starting from largest event
assert(event);
processed_queue_[obj_id]->pop_back();
input_queue_[obj_id]->insert(event);
event_riterator = processed_queue_[obj_id]->rbegin();
}
}
/*
* NOTE: caller must have the input queue lock for the object with id obj_id
*/
std::unique_ptr<std::vector<std::shared_ptr<Event>>>
TimeWarpEventSet::getEventsForCoastForward (
unsigned int obj_id,
std::shared_ptr<Event> straggler_event,
std::shared_ptr<Event> restored_state_event) {
// To avoid error if asserts are disabled
unused(straggler_event);
// Restored state event is the last event to contribute to the current state of the object.
// All events GREATER THAN this event but LESS THAN the straggler event must be "coast forwarded"
// so that the state remains consistent.
//
// It is assumed that all processed events GREATER THAN OR EQUAL to the straggler event have
// been moved from the processed queue to the input queue with a call to rollback().
//
// All coast forwared events remain in the processed queue.
// Create empty vector
auto events = make_unique<std::vector<std::shared_ptr<Event>>>();
auto event_riterator = processed_queue_[obj_id]->rbegin(); // Starting with largest event
while ((event_riterator != processed_queue_[obj_id]->rend()) && (**event_riterator > *restored_state_event)) {
assert(*event_riterator);
assert(**event_riterator < *straggler_event);
// Events are in order of LARGEST to SMALLEST
events->push_back(*event_riterator);
event_riterator++;
}
return (std::move(events));
}
/*
* NOTE: call must always have input queue lock for the object which corresponds to obj_id
*
* NOTE: This is called in the case of an negative message and no event is processed.
*
* NOTE: This can only be called by the thread that handles events for the object with id obj_id
*
*/
void TimeWarpEventSet::startScheduling (unsigned int obj_id) {
// Just simply add pointer to next event into the scheduler if input queue is not empty
// for the given object, otherwise set to nullptr
if (!input_queue_[obj_id]->empty()) {
scheduled_event_pointer_[obj_id] = *input_queue_[obj_id]->begin();
unsigned int scheduler_id = input_queue_scheduler_map_[obj_id];
schedule_queue_lock_[scheduler_id].lock();
schedule_queue_[scheduler_id]->insert(scheduled_event_pointer_[obj_id]);
schedule_queue_lock_[scheduler_id].unlock();
} else {
scheduled_event_pointer_[obj_id] = nullptr;
}
}
/*
* NOTE: This can only be called by the thread that handles event for the object with id obj_id
*
* NOTE: caller must always have the input queue lock for the object which corresponds to obj_id
*
* NOTE: the scheduled_event_pointer is also protected by input queue lock
*/
void TimeWarpEventSet::replenishScheduler (unsigned int obj_id) {
// Something is completely wrong if there is no scheduled event because we obviously just
// processed an event that was scheduled.
assert(scheduled_event_pointer_[obj_id]);
// Move the just processed event to the processed queue
auto num_erased = input_queue_[obj_id]->erase(scheduled_event_pointer_[obj_id]);
assert(num_erased == 1);
unused(num_erased);
processed_queue_[obj_id]->push_back(scheduled_event_pointer_[obj_id]);
// Map the object to the next schedule queue (cyclic order)
// This is supposed to balance the load across all the schedule queues
// Input queue lock is sufficient to ensure consistency
unsigned int scheduler_id = input_queue_scheduler_map_[obj_id];
if (is_lp_migration_on_) {
scheduler_id = (scheduler_id + 1) % num_of_schedulers_;
input_queue_scheduler_map_[obj_id] = scheduler_id;
}
// Update scheduler with new event for the object the previous event was executed for
// NOTE: A pointer to the scheduled event will remain in the input queue
if (!input_queue_[obj_id]->empty()) {
scheduled_event_pointer_[obj_id] = *input_queue_[obj_id]->begin();
schedule_queue_lock_[scheduler_id].lock();
schedule_queue_[scheduler_id]->insert(scheduled_event_pointer_[obj_id]);
schedule_queue_lock_[scheduler_id].unlock();
} else {
scheduled_event_pointer_[obj_id] = nullptr;
}
}
void TimeWarpEventSet::cancelEvent (unsigned int obj_id, std::shared_ptr<Event> cancel_event) {
auto neg_iterator = input_queue_[obj_id]->find(cancel_event);
assert(neg_iterator != input_queue_[obj_id]->end());
auto pos_iterator = std::next(neg_iterator);
assert(**pos_iterator == **neg_iterator);
assert((*pos_iterator)->event_type_ == EventType::POSITIVE);
input_queue_[obj_id]->erase(neg_iterator);
input_queue_[obj_id]->erase(pos_iterator);
}
// For debugging
void TimeWarpEventSet::printEvent(std::shared_ptr<Event> event) {
std::cout << "\tSender: " << event->sender_name_ << "\n"
<< "\tReceiver: " << event->receiverName() << "\n"
<< "\tSend time: " << event->send_time_ << "\n"
<< "\tRecv time: " << event->timestamp() << "\n"
<< "\tCounter: " << event->counter_ << "\n"
<< "\tType: " << (unsigned int)event->event_type_ << "\n";
}
unsigned int TimeWarpEventSet::fossilCollect (unsigned int fossil_collect_time, unsigned int obj_id) {
unsigned int count = 0;
auto event_iterator = processed_queue_[obj_id]->begin();
while ((event_iterator != processed_queue_[obj_id]->end()) &&
((*event_iterator)->timestamp() < fossil_collect_time)) {
processed_queue_[obj_id]->pop_front();
event_iterator = processed_queue_[obj_id]->begin();
count++;
}
return count;
}
} // namespace warped
<commit_msg>Make sure at least one event is left in processed queue<commit_after>#include <algorithm>
#include <cassert>
#include <string>
#include "TimeWarpEventSet.hpp"
#include "utility/warnings.hpp"
namespace warped {
void TimeWarpEventSet::initialize (unsigned int num_of_objects,
unsigned int num_of_schedulers,
bool is_lp_migration_on,
unsigned int num_of_worker_threads) {
num_of_objects_ = num_of_objects;
num_of_schedulers_ = num_of_schedulers;
is_lp_migration_on_ = is_lp_migration_on;
/* Create the input and processed queues and their locks.
Also create the input queue-scheduler map and scheduled event pointer. */
input_queue_lock_ = make_unique<std::mutex []>(num_of_objects);
for (unsigned int obj_id = 0; obj_id < num_of_objects; obj_id++) {
input_queue_.push_back(
make_unique<std::multiset<std::shared_ptr<Event>, compareEvents>>());
processed_queue_.push_back(
make_unique<std::deque<std::shared_ptr<Event>>>());
scheduled_event_pointer_.push_back(nullptr);
input_queue_scheduler_map_.push_back(obj_id % num_of_schedulers);
}
/* Create the schedule queues and their locks. */
for (unsigned int scheduler_id = 0; scheduler_id < num_of_schedulers; scheduler_id++) {
schedule_queue_.push_back(
make_unique<std::multiset<std::shared_ptr<Event>, compareEvents>>());
}
schedule_queue_lock_ = make_unique<TicketLock []>(num_of_schedulers);
/* Map worker threads to schedule queues. */
for (unsigned int thread_id = 0;
thread_id < num_of_worker_threads; thread_id++) {
worker_thread_scheduler_map_.push_back(thread_id % num_of_schedulers);
}
}
void TimeWarpEventSet::acquireInputQueueLock (unsigned int obj_id) {
input_queue_lock_[obj_id].lock();
}
void TimeWarpEventSet::releaseInputQueueLock (unsigned int obj_id) {
input_queue_lock_[obj_id].unlock();
}
/*
* NOTE: caller must always have the input queue lock for the object with id obj_id
*
* NOTE: scheduled_event_pointer is also protected by the input queue lock
*/
void TimeWarpEventSet::insertEvent (unsigned int obj_id, std::shared_ptr<Event> event) {
// Always insert event into input queue
input_queue_[obj_id]->insert(event);
unsigned int scheduler_id = input_queue_scheduler_map_[obj_id];
if (scheduled_event_pointer_[obj_id] == nullptr) {
// If no event is currently scheduled. This can only happen if the thread that handles events
// for object with id obj_id has determined that there are no more events left in it's input
// queue
assert(input_queue_[obj_id]->size() == 1);
schedule_queue_lock_[scheduler_id].lock();
schedule_queue_[scheduler_id]->insert(event);
schedule_queue_lock_[scheduler_id].unlock();
scheduled_event_pointer_[obj_id] = event;
} else {
auto smallest_event = *input_queue_[obj_id]->begin();
if (smallest_event != scheduled_event_pointer_[obj_id]) {
// If the pointer comparison of the smallest event does not match scheduled event, well
// that means we should update the schedule queue...
schedule_queue_lock_[scheduler_id].lock();
if (auto num_erased = schedule_queue_[scheduler_id]->erase(scheduled_event_pointer_[obj_id])) {
// ...but only if the event was successfully erased from the schedule queue. If it is
// not then the event is already being processed and a rollback will have to occur.
assert(num_erased == 1);
unused(num_erased);
schedule_queue_[scheduler_id]->insert(smallest_event);
scheduled_event_pointer_[obj_id] = smallest_event;
}
schedule_queue_lock_[scheduler_id].unlock();
}
}
}
/*
* NOTE: caller must always have the input queue lock for the object with id obj_id
*/
std::shared_ptr<Event> TimeWarpEventSet::getEvent (unsigned int thread_id) {
unsigned int scheduler_id = worker_thread_scheduler_map_[thread_id];
schedule_queue_lock_[scheduler_id].lock();
auto event_iterator = schedule_queue_[scheduler_id]->begin();
auto event = (event_iterator != schedule_queue_[scheduler_id]->end()) ?
*event_iterator : nullptr;
if (event != nullptr) {
schedule_queue_[scheduler_id]->erase(event_iterator);
}
// NOTE: scheduled_event_pointer is not changed here so that other threads will not schedule new
// events and this thread can move events into processed queue and update schedule queue correctly.
// NOTE: Event also remains in input queue until processing done. If this a a negative event
// then, a rollback will bring the processed positive event back to input queue and they will
// be cancelled.
schedule_queue_lock_[scheduler_id].unlock();
return event;
}
/*
* NOTE: caller must have the input queue lock for the object with id obj_id
*/
std::shared_ptr<Event> TimeWarpEventSet::lastProcessedEvent (unsigned int obj_id) {
return ((processed_queue_[obj_id]->size()) ? processed_queue_[obj_id]->back() : nullptr);
}
/*
* NOTE: caller must have the input queue lock for the object with id obj_id
*/
void TimeWarpEventSet::rollback (unsigned int obj_id, std::shared_ptr<Event> straggler_event) {
// Every event GREATER OR EQUAL to straggler event must remove from the processed queue and
// reinserted back into input queue.
// EQUAL will ensure that a negative message will properly be cancelled out.
auto event_riterator = processed_queue_[obj_id]->rbegin(); // Starting with largest event
while (event_riterator != processed_queue_[obj_id]->rend() && (**event_riterator >= *straggler_event)){
auto event = processed_queue_[obj_id]->back(); // Starting from largest event
assert(event);
processed_queue_[obj_id]->pop_back();
input_queue_[obj_id]->insert(event);
event_riterator = processed_queue_[obj_id]->rbegin();
}
}
/*
* NOTE: caller must have the input queue lock for the object with id obj_id
*/
std::unique_ptr<std::vector<std::shared_ptr<Event>>>
TimeWarpEventSet::getEventsForCoastForward (
unsigned int obj_id,
std::shared_ptr<Event> straggler_event,
std::shared_ptr<Event> restored_state_event) {
// To avoid error if asserts are disabled
unused(straggler_event);
// Restored state event is the last event to contribute to the current state of the object.
// All events GREATER THAN this event but LESS THAN the straggler event must be "coast forwarded"
// so that the state remains consistent.
//
// It is assumed that all processed events GREATER THAN OR EQUAL to the straggler event have
// been moved from the processed queue to the input queue with a call to rollback().
//
// All coast forwared events remain in the processed queue.
// Create empty vector
auto events = make_unique<std::vector<std::shared_ptr<Event>>>();
auto event_riterator = processed_queue_[obj_id]->rbegin(); // Starting with largest event
while ((event_riterator != processed_queue_[obj_id]->rend()) && (**event_riterator > *restored_state_event)) {
assert(*event_riterator);
assert(**event_riterator < *straggler_event);
// Events are in order of LARGEST to SMALLEST
events->push_back(*event_riterator);
event_riterator++;
}
return (std::move(events));
}
/*
* NOTE: call must always have input queue lock for the object which corresponds to obj_id
*
* NOTE: This is called in the case of an negative message and no event is processed.
*
* NOTE: This can only be called by the thread that handles events for the object with id obj_id
*
*/
void TimeWarpEventSet::startScheduling (unsigned int obj_id) {
// Just simply add pointer to next event into the scheduler if input queue is not empty
// for the given object, otherwise set to nullptr
if (!input_queue_[obj_id]->empty()) {
scheduled_event_pointer_[obj_id] = *input_queue_[obj_id]->begin();
unsigned int scheduler_id = input_queue_scheduler_map_[obj_id];
schedule_queue_lock_[scheduler_id].lock();
schedule_queue_[scheduler_id]->insert(scheduled_event_pointer_[obj_id]);
schedule_queue_lock_[scheduler_id].unlock();
} else {
scheduled_event_pointer_[obj_id] = nullptr;
}
}
/*
* NOTE: This can only be called by the thread that handles event for the object with id obj_id
*
* NOTE: caller must always have the input queue lock for the object which corresponds to obj_id
*
* NOTE: the scheduled_event_pointer is also protected by input queue lock
*/
void TimeWarpEventSet::replenishScheduler (unsigned int obj_id) {
// Something is completely wrong if there is no scheduled event because we obviously just
// processed an event that was scheduled.
assert(scheduled_event_pointer_[obj_id]);
// Move the just processed event to the processed queue
auto num_erased = input_queue_[obj_id]->erase(scheduled_event_pointer_[obj_id]);
assert(num_erased == 1);
unused(num_erased);
processed_queue_[obj_id]->push_back(scheduled_event_pointer_[obj_id]);
// Map the object to the next schedule queue (cyclic order)
// This is supposed to balance the load across all the schedule queues
// Input queue lock is sufficient to ensure consistency
unsigned int scheduler_id = input_queue_scheduler_map_[obj_id];
if (is_lp_migration_on_) {
scheduler_id = (scheduler_id + 1) % num_of_schedulers_;
input_queue_scheduler_map_[obj_id] = scheduler_id;
}
// Update scheduler with new event for the object the previous event was executed for
// NOTE: A pointer to the scheduled event will remain in the input queue
if (!input_queue_[obj_id]->empty()) {
scheduled_event_pointer_[obj_id] = *input_queue_[obj_id]->begin();
schedule_queue_lock_[scheduler_id].lock();
schedule_queue_[scheduler_id]->insert(scheduled_event_pointer_[obj_id]);
schedule_queue_lock_[scheduler_id].unlock();
} else {
scheduled_event_pointer_[obj_id] = nullptr;
}
}
void TimeWarpEventSet::cancelEvent (unsigned int obj_id, std::shared_ptr<Event> cancel_event) {
auto neg_iterator = input_queue_[obj_id]->find(cancel_event);
assert(neg_iterator != input_queue_[obj_id]->end());
auto pos_iterator = std::next(neg_iterator);
assert(pos_iterator != input_queue_[obj_id]->end());
assert(**pos_iterator == **neg_iterator);
input_queue_[obj_id]->erase(neg_iterator);
input_queue_[obj_id]->erase(pos_iterator);
}
// For debugging
void TimeWarpEventSet::printEvent(std::shared_ptr<Event> event) {
std::cout << "\tSender: " << event->sender_name_ << "\n"
<< "\tReceiver: " << event->receiverName() << "\n"
<< "\tSend time: " << event->send_time_ << "\n"
<< "\tRecv time: " << event->timestamp() << "\n"
<< "\tGeneratrion:" << event->generation_ << "\n"
<< "\tType: " << (unsigned int)event->event_type_ << "\n";
}
unsigned int TimeWarpEventSet::fossilCollect (unsigned int fossil_collect_time, unsigned int obj_id) {
unsigned int count = 0;
if (processed_queue_[obj_id]->empty()) {
return count;
}
if (fossil_collect_time == (unsigned int)-1) {
count = processed_queue_[obj_id]->size();
processed_queue_[obj_id]->clear();
return count;
}
auto event_iterator = processed_queue_[obj_id]->begin();
while ((event_iterator != std::prev(processed_queue_[obj_id]->end())) &&
((*event_iterator)->timestamp() < fossil_collect_time)) {
processed_queue_[obj_id]->pop_front();
event_iterator = processed_queue_[obj_id]->begin();
count++;
}
return count;
}
} // namespace warped
<|endoftext|> |
<commit_before>//******************************************************************
//
// Copyright 2016 Intel Corporation All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include "VirtualBusObject.h"
#include "Payload.h"
#include "Plugin.h"
#include <alljoyn/BusAttachment.h>
#include "ocpayload.h"
#include <algorithm>
#include <assert.h>
struct VirtualBusObject::ObserveContext
{
public:
ObserveContext(VirtualBusObject *obj, const char *iface)
: m_obj(obj), m_iface(iface), m_handle(NULL), m_result(OC_STACK_KEEP_TRANSACTION) { }
static void Deleter(void *ctx)
{
LOG(LOG_INFO, "[%p]", ctx);
ObserveContext *context = reinterpret_cast<ObserveContext *>(ctx);
{
std::lock_guard<std::mutex> lock(context->m_obj->m_mutex);
context->m_obj->m_observes.erase(context);
}
delete context;
}
VirtualBusObject *m_obj;
std::string m_iface;
OCDoHandle m_handle;
OCStackApplicationResult m_result;
};
struct VirtualBusObject::DoResourceContext
{
public:
DoResourceContext(VirtualBusObject *obj, VirtualBusObject::DoResourceHandler cb, ajn::Message &msg)
: m_obj(obj), m_cb(cb), m_msg(msg), m_handle(NULL) { }
VirtualBusObject *m_obj;
VirtualBusObject::DoResourceHandler m_cb;
ajn::Message m_msg;
OCDoHandle m_handle;
};
VirtualBusObject::VirtualBusObject(ajn::BusAttachment *bus, const char *uri, const char *host)
: ajn::BusObject(uri), m_bus(bus), m_host(host), m_pending(0)
{
LOG(LOG_INFO, "[%p] bus=%p,uri=%s,host=%s",
this, bus, uri, host);
}
VirtualBusObject::~VirtualBusObject()
{
LOG(LOG_INFO, "[%p]",
this);
std::unique_lock<std::mutex> lock(m_mutex);
while (m_pending > 0 && !m_observes.empty())
{
m_cond.wait(lock);
}
}
void VirtualBusObject::Stop()
{
std::vector<OCDoHandle> handles;
{
std::lock_guard<std::mutex> lock(m_mutex);
for (ObserveContext *context : m_observes)
{
context->m_result = OC_STACK_DELETE_TRANSACTION;
handles.push_back(context->m_handle);
}
}
for (OCDoHandle handle : handles)
{
OCStackResult result = Cancel(handle, OC_LOW_QOS);
if (result != OC_STACK_OK)
{
LOG(LOG_ERR, "Cancel - %d", result);
}
}
}
QStatus VirtualBusObject::AddInterface(const ajn::InterfaceDescription *iface)
{
LOG(LOG_INFO, "[%p] iface=%p",
this, iface);
QStatus status = ajn::BusObject::AddInterface(*iface, ajn::BusObject::ANNOUNCED);
if (status == ER_OK)
{
m_ifaces.push_back(iface);
}
else
{
LOG(LOG_ERR, "AddInterface - %s", QCC_StatusText(status));
}
return status;
}
void VirtualBusObject::Observe()
{
LOG(LOG_INFO, "[%p]",
this);
std::lock_guard<std::mutex> lock(m_mutex);
bool multipleRts = m_ifaces.size() > 1;
for (const ajn::InterfaceDescription *iface : m_ifaces)
{
qcc::String uri = m_host + GetPath();
if (multipleRts)
{
uri += qcc::String("?rt=") + iface->GetName();
}
ObserveContext *context = new ObserveContext(this, iface->GetName());
OCCallbackData cbData;
cbData.cb = VirtualBusObject::ObserveCB;
cbData.context = context;
cbData.cd = ObserveContext::Deleter;
OCStackResult result = ::DoResource(&context->m_handle, OC_REST_OBSERVE, uri.c_str(),
NULL, NULL, &cbData);
if (result == OC_STACK_OK)
{
m_observes.insert(context);
}
else
{
LOG(LOG_ERR, "DoResource - %d", result);
}
}
}
void VirtualBusObject::CancelObserve()
{
LOG(LOG_INFO, "[%p]",
this);
std::lock_guard<std::mutex> lock(m_mutex);
for (ObserveContext *context : m_observes)
{
context->m_result = OC_STACK_DELETE_TRANSACTION;
OCStackResult result = Cancel(context->m_handle, OC_HIGH_QOS);
if (result != OC_STACK_OK)
{
LOG(LOG_ERR, "Cancel - %d", result);
}
}
}
OCStackApplicationResult VirtualBusObject::ObserveCB(void *ctx, OCDoHandle handle,
OCClientResponse *response)
{
ObserveContext *context = reinterpret_cast<ObserveContext *>(ctx);
LOG(LOG_INFO, "[%p] ctx=%p,handle=%p,response=%p,{payload=%p,result=%d}",
context->m_obj, ctx, handle, response, response ? response->payload : 0, response ? response->result : 0);
std::lock_guard<std::mutex> lock(context->m_obj->m_mutex);
if (response && response->result == OC_STACK_OK && response->payload)
{
OCRepPayloadValue value;
memset(&value, 0, sizeof(value));
value.type = OCREP_PROP_OBJECT;
value.obj = (OCRepPayload *) response->payload;
ajn::MsgArg args[3];
args[0].Set("s", context->m_iface.c_str());
ToAJMsgArg(&args[1], "a{sv}", &value);
args[2].Set("as", 0, NULL);
const ajn::InterfaceDescription *iface = context->m_obj->m_bus->GetInterface(
ajn::org::freedesktop::DBus::Properties::InterfaceName);
assert(iface);
const ajn::InterfaceDescription::Member *member = iface->GetMember("PropertiesChanged");
assert(member);
QStatus status = context->m_obj->Signal(NULL, ajn::SESSION_ID_ALL_HOSTED,
*member,
args, 3);
if (status != ER_OK)
{
LOG(LOG_ERR, "Signal - %s", QCC_StatusText(status));
}
}
return context->m_result;
}
void VirtualBusObject::GetProp(const ajn::InterfaceDescription::Member *member, ajn::Message &msg)
{
LOG(LOG_INFO, "[%p] member=%p",
this, member);
std::lock_guard<std::mutex> lock(m_mutex);
bool multipleRts = m_ifaces.size() > 1;
qcc::String uri = GetPath();
if (multipleRts)
{
uri += qcc::String("?rt=") + msg->GetArg(0)->v_string.str;
}
DoResource(OC_REST_GET, uri.c_str(), NULL, msg, &VirtualBusObject::GetPropCB);
}
/* Called with m_mutex held. */
void VirtualBusObject::GetPropCB(ajn::Message &msg, OCRepPayload *payload)
{
LOG(LOG_INFO, "[%p]",
this);
ajn::MsgArg arg;
for (OCRepPayloadValue *value = payload->values; value; value = value->next)
{
if (!strcmp(value->name, msg->GetArg(1)->v_string.str))
{
ToAJMsgArg(&arg, "v", value);
break;
}
}
QStatus status = MethodReply(msg, &arg, 1);
if (status != ER_OK)
{
LOG(LOG_ERR, "MethodReply - %s", QCC_StatusText(status));
}
}
void VirtualBusObject::SetProp(const ajn::InterfaceDescription::Member *member, ajn::Message &msg)
{
LOG(LOG_INFO, "[%p] member=%p",
this, member);
std::lock_guard<std::mutex> lock(m_mutex);
qcc::String uri = GetPath();
OCRepPayload *payload = OCRepPayloadCreate();
const char *name = msg->GetArg(1)->v_string.str;
const ajn::MsgArg *arg = msg->GetArg(2);
ToOCPayload(payload, name, arg, arg->Signature().c_str());
DoResource(OC_REST_POST, uri.c_str(), payload, msg, &VirtualBusObject::SetPropCB);
}
/* Called with m_mutex held. */
void VirtualBusObject::SetPropCB(ajn::Message &msg, OCRepPayload *payload)
{
(void) payload;
LOG(LOG_INFO, "[%p]",
this);
QStatus status = MethodReply(msg);
if (status != ER_OK)
{
LOG(LOG_ERR, "MethodReply - %s", QCC_StatusText(status));
}
}
void VirtualBusObject::GetAllProps(const ajn::InterfaceDescription::Member *member,
ajn::Message &msg)
{
LOG(LOG_INFO, "[%p] member=%p",
this, member);
std::lock_guard<std::mutex> lock(m_mutex);
bool multipleRts = m_ifaces.size() > 1;
qcc::String uri = GetPath();
if (multipleRts)
{
uri += qcc::String("?rt=") + msg->GetArg(0)->v_string.str;
}
DoResource(OC_REST_GET, uri.c_str(), NULL, msg, &VirtualBusObject::GetAllPropsCB);
}
/* Called with m_mutex held. */
void VirtualBusObject::GetAllPropsCB(ajn::Message &msg, OCRepPayload *payload)
{
LOG(LOG_INFO, "[%p]",
this);
OCRepPayloadValue value;
memset(&value, 0, sizeof(value));
value.type = OCREP_PROP_OBJECT;
value.obj = payload;
ajn::MsgArg arg;
ToAJMsgArg(&arg, "a{sv}", &value);
QStatus status = MethodReply(msg, &arg, 1);
if (status != ER_OK)
{
LOG(LOG_ERR, "MethodReply - %s", QCC_StatusText(status));
}
}
/* This must be called with m_mutex held. */
void VirtualBusObject::DoResource(OCMethod method, const char *uri, OCRepPayload *payload,
ajn::Message &msg, DoResourceHandler cb)
{
LOG(LOG_INFO, "[%p] method=%d,uri=%s,payload=%p",
this, method, uri, payload);
DoResourceContext *context = new DoResourceContext(this, cb, msg);
char targetUri[MAX_URI_LENGTH] = { 0 };
snprintf(targetUri, MAX_URI_LENGTH, "%s%s", m_host.c_str(), uri);
OCCallbackData cbData;
cbData.cb = VirtualBusObject::DoResourceCB;
cbData.context = context;
cbData.cd = NULL;
OCStackResult result = ::DoResource(&context->m_handle, method, targetUri, NULL,
(OCPayload *) payload,
&cbData);
if (result == OC_STACK_OK)
{
++m_pending;
}
else
{
LOG(LOG_ERR, "DoResource - %d", result);
delete context;
QStatus status = MethodReply(msg, ER_FAIL);
if (status != ER_OK)
{
LOG(LOG_ERR, "MethodReply - %s", QCC_StatusText(status));
}
}
}
OCStackApplicationResult VirtualBusObject::DoResourceCB(void *ctx, OCDoHandle handle,
OCClientResponse *response)
{
DoResourceContext *context = reinterpret_cast<DoResourceContext *>(ctx);
LOG(LOG_INFO, "[%p] ctx=%p,handle=%p,response=%p,{payload=%p,result=%d}",
context->m_obj, ctx, handle, response, response ? response->payload : 0, response ? response->result : 0);
std::lock_guard<std::mutex> lock(context->m_obj->m_mutex);
if (!response || response->result != OC_STACK_OK || !response->payload)
{
QStatus status = context->m_obj->MethodReply(context->m_msg, ER_FAIL);
if (status != ER_OK)
{
LOG(LOG_ERR, "MethodReply - %s", QCC_StatusText(status));
}
}
else
{
OCRepPayload *payload = (OCRepPayload *) response->payload;
(context->m_obj->*(context->m_cb))(context->m_msg, payload);
}
--context->m_obj->m_pending;
context->m_obj->m_cond.notify_one();
delete context;
return OC_STACK_DELETE_TRANSACTION;
}
<commit_msg>Correctly handle all success status codes.<commit_after>//******************************************************************
//
// Copyright 2016 Intel Corporation All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include "VirtualBusObject.h"
#include "Payload.h"
#include "Plugin.h"
#include <alljoyn/BusAttachment.h>
#include "ocpayload.h"
#include <algorithm>
#include <assert.h>
struct VirtualBusObject::ObserveContext
{
public:
ObserveContext(VirtualBusObject *obj, const char *iface)
: m_obj(obj), m_iface(iface), m_handle(NULL), m_result(OC_STACK_KEEP_TRANSACTION) { }
static void Deleter(void *ctx)
{
LOG(LOG_INFO, "[%p]", ctx);
ObserveContext *context = reinterpret_cast<ObserveContext *>(ctx);
{
std::lock_guard<std::mutex> lock(context->m_obj->m_mutex);
context->m_obj->m_observes.erase(context);
}
delete context;
}
VirtualBusObject *m_obj;
std::string m_iface;
OCDoHandle m_handle;
OCStackApplicationResult m_result;
};
struct VirtualBusObject::DoResourceContext
{
public:
DoResourceContext(VirtualBusObject *obj, VirtualBusObject::DoResourceHandler cb, ajn::Message &msg)
: m_obj(obj), m_cb(cb), m_msg(msg), m_handle(NULL) { }
VirtualBusObject *m_obj;
VirtualBusObject::DoResourceHandler m_cb;
ajn::Message m_msg;
OCDoHandle m_handle;
};
VirtualBusObject::VirtualBusObject(ajn::BusAttachment *bus, const char *uri, const char *host)
: ajn::BusObject(uri), m_bus(bus), m_host(host), m_pending(0)
{
LOG(LOG_INFO, "[%p] bus=%p,uri=%s,host=%s",
this, bus, uri, host);
}
VirtualBusObject::~VirtualBusObject()
{
LOG(LOG_INFO, "[%p]",
this);
std::unique_lock<std::mutex> lock(m_mutex);
while (m_pending > 0 && !m_observes.empty())
{
m_cond.wait(lock);
}
}
void VirtualBusObject::Stop()
{
std::vector<OCDoHandle> handles;
{
std::lock_guard<std::mutex> lock(m_mutex);
for (ObserveContext *context : m_observes)
{
context->m_result = OC_STACK_DELETE_TRANSACTION;
handles.push_back(context->m_handle);
}
}
for (OCDoHandle handle : handles)
{
OCStackResult result = Cancel(handle, OC_LOW_QOS);
if (result != OC_STACK_OK)
{
LOG(LOG_ERR, "Cancel - %d", result);
}
}
}
QStatus VirtualBusObject::AddInterface(const ajn::InterfaceDescription *iface)
{
LOG(LOG_INFO, "[%p] iface=%p",
this, iface);
QStatus status = ajn::BusObject::AddInterface(*iface, ajn::BusObject::ANNOUNCED);
if (status == ER_OK)
{
m_ifaces.push_back(iface);
}
else
{
LOG(LOG_ERR, "AddInterface - %s", QCC_StatusText(status));
}
return status;
}
void VirtualBusObject::Observe()
{
LOG(LOG_INFO, "[%p]",
this);
std::lock_guard<std::mutex> lock(m_mutex);
bool multipleRts = m_ifaces.size() > 1;
for (const ajn::InterfaceDescription *iface : m_ifaces)
{
qcc::String uri = m_host + GetPath();
if (multipleRts)
{
uri += qcc::String("?rt=") + iface->GetName();
}
ObserveContext *context = new ObserveContext(this, iface->GetName());
OCCallbackData cbData;
cbData.cb = VirtualBusObject::ObserveCB;
cbData.context = context;
cbData.cd = ObserveContext::Deleter;
OCStackResult result = ::DoResource(&context->m_handle, OC_REST_OBSERVE, uri.c_str(),
NULL, NULL, &cbData);
if (result == OC_STACK_OK)
{
m_observes.insert(context);
}
else
{
LOG(LOG_ERR, "DoResource - %d", result);
}
}
}
void VirtualBusObject::CancelObserve()
{
LOG(LOG_INFO, "[%p]",
this);
std::lock_guard<std::mutex> lock(m_mutex);
for (ObserveContext *context : m_observes)
{
context->m_result = OC_STACK_DELETE_TRANSACTION;
OCStackResult result = Cancel(context->m_handle, OC_HIGH_QOS);
if (result != OC_STACK_OK)
{
LOG(LOG_ERR, "Cancel - %d", result);
}
}
}
OCStackApplicationResult VirtualBusObject::ObserveCB(void *ctx, OCDoHandle handle,
OCClientResponse *response)
{
ObserveContext *context = reinterpret_cast<ObserveContext *>(ctx);
LOG(LOG_INFO, "[%p] ctx=%p,handle=%p,response=%p,{payload=%p,result=%d}",
context->m_obj, ctx, handle, response, response ? response->payload : 0, response ? response->result : 0);
std::lock_guard<std::mutex> lock(context->m_obj->m_mutex);
if (response && response->result == OC_STACK_OK && response->payload)
{
OCRepPayloadValue value;
memset(&value, 0, sizeof(value));
value.type = OCREP_PROP_OBJECT;
value.obj = (OCRepPayload *) response->payload;
ajn::MsgArg args[3];
args[0].Set("s", context->m_iface.c_str());
ToAJMsgArg(&args[1], "a{sv}", &value);
args[2].Set("as", 0, NULL);
const ajn::InterfaceDescription *iface = context->m_obj->m_bus->GetInterface(
ajn::org::freedesktop::DBus::Properties::InterfaceName);
assert(iface);
const ajn::InterfaceDescription::Member *member = iface->GetMember("PropertiesChanged");
assert(member);
QStatus status = context->m_obj->Signal(NULL, ajn::SESSION_ID_ALL_HOSTED,
*member,
args, 3);
if (status != ER_OK)
{
LOG(LOG_ERR, "Signal - %s", QCC_StatusText(status));
}
}
return context->m_result;
}
void VirtualBusObject::GetProp(const ajn::InterfaceDescription::Member *member, ajn::Message &msg)
{
LOG(LOG_INFO, "[%p] member=%p",
this, member);
std::lock_guard<std::mutex> lock(m_mutex);
bool multipleRts = m_ifaces.size() > 1;
qcc::String uri = GetPath();
if (multipleRts)
{
uri += qcc::String("?rt=") + msg->GetArg(0)->v_string.str;
}
DoResource(OC_REST_GET, uri.c_str(), NULL, msg, &VirtualBusObject::GetPropCB);
}
/* Called with m_mutex held. */
void VirtualBusObject::GetPropCB(ajn::Message &msg, OCRepPayload *payload)
{
LOG(LOG_INFO, "[%p]",
this);
ajn::MsgArg arg;
for (OCRepPayloadValue *value = payload->values; value; value = value->next)
{
if (!strcmp(value->name, msg->GetArg(1)->v_string.str))
{
ToAJMsgArg(&arg, "v", value);
break;
}
}
QStatus status = MethodReply(msg, &arg, 1);
if (status != ER_OK)
{
LOG(LOG_ERR, "MethodReply - %s", QCC_StatusText(status));
}
}
void VirtualBusObject::SetProp(const ajn::InterfaceDescription::Member *member, ajn::Message &msg)
{
LOG(LOG_INFO, "[%p] member=%p",
this, member);
std::lock_guard<std::mutex> lock(m_mutex);
qcc::String uri = GetPath();
OCRepPayload *payload = OCRepPayloadCreate();
const char *name = msg->GetArg(1)->v_string.str;
const ajn::MsgArg *arg = msg->GetArg(2);
ToOCPayload(payload, name, arg, arg->Signature().c_str());
DoResource(OC_REST_POST, uri.c_str(), payload, msg, &VirtualBusObject::SetPropCB);
}
/* Called with m_mutex held. */
void VirtualBusObject::SetPropCB(ajn::Message &msg, OCRepPayload *payload)
{
(void) payload;
LOG(LOG_INFO, "[%p]",
this);
QStatus status = MethodReply(msg);
if (status != ER_OK)
{
LOG(LOG_ERR, "MethodReply - %s", QCC_StatusText(status));
}
}
void VirtualBusObject::GetAllProps(const ajn::InterfaceDescription::Member *member,
ajn::Message &msg)
{
LOG(LOG_INFO, "[%p] member=%p",
this, member);
std::lock_guard<std::mutex> lock(m_mutex);
bool multipleRts = m_ifaces.size() > 1;
qcc::String uri = GetPath();
if (multipleRts)
{
uri += qcc::String("?rt=") + msg->GetArg(0)->v_string.str;
}
DoResource(OC_REST_GET, uri.c_str(), NULL, msg, &VirtualBusObject::GetAllPropsCB);
}
/* Called with m_mutex held. */
void VirtualBusObject::GetAllPropsCB(ajn::Message &msg, OCRepPayload *payload)
{
LOG(LOG_INFO, "[%p]",
this);
OCRepPayloadValue value;
memset(&value, 0, sizeof(value));
value.type = OCREP_PROP_OBJECT;
value.obj = payload;
ajn::MsgArg arg;
ToAJMsgArg(&arg, "a{sv}", &value);
QStatus status = MethodReply(msg, &arg, 1);
if (status != ER_OK)
{
LOG(LOG_ERR, "MethodReply - %s", QCC_StatusText(status));
}
}
/* This must be called with m_mutex held. */
void VirtualBusObject::DoResource(OCMethod method, const char *uri, OCRepPayload *payload,
ajn::Message &msg, DoResourceHandler cb)
{
LOG(LOG_INFO, "[%p] method=%d,uri=%s,payload=%p",
this, method, uri, payload);
DoResourceContext *context = new DoResourceContext(this, cb, msg);
char targetUri[MAX_URI_LENGTH] = { 0 };
snprintf(targetUri, MAX_URI_LENGTH, "%s%s", m_host.c_str(), uri);
OCCallbackData cbData;
cbData.cb = VirtualBusObject::DoResourceCB;
cbData.context = context;
cbData.cd = NULL;
OCStackResult result = ::DoResource(&context->m_handle, method, targetUri, NULL,
(OCPayload *) payload,
&cbData);
if (result == OC_STACK_OK)
{
++m_pending;
}
else
{
LOG(LOG_ERR, "DoResource - %d", result);
delete context;
QStatus status = MethodReply(msg, ER_FAIL);
if (status != ER_OK)
{
LOG(LOG_ERR, "MethodReply - %s", QCC_StatusText(status));
}
}
}
OCStackApplicationResult VirtualBusObject::DoResourceCB(void *ctx, OCDoHandle handle,
OCClientResponse *response)
{
DoResourceContext *context = reinterpret_cast<DoResourceContext *>(ctx);
LOG(LOG_INFO, "[%p] ctx=%p,handle=%p,response=%p,{payload=%p,result=%d}",
context->m_obj, ctx, handle, response, response ? response->payload : 0, response ? response->result : 0);
std::lock_guard<std::mutex> lock(context->m_obj->m_mutex);
if (!response || response->result > OC_STACK_RESOURCE_CHANGED || !response->payload)
{
QStatus status = context->m_obj->MethodReply(context->m_msg, ER_FAIL);
if (status != ER_OK)
{
LOG(LOG_ERR, "MethodReply - %s", QCC_StatusText(status));
}
}
else
{
OCRepPayload *payload = (OCRepPayload *) response->payload;
(context->m_obj->*(context->m_cb))(context->m_msg, payload);
}
--context->m_obj->m_pending;
context->m_obj->m_cond.notify_one();
delete context;
return OC_STACK_DELETE_TRANSACTION;
}
<|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: vendorbase.hxx,v $
* $Revision: 1.14 $
*
* 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.
*
************************************************************************/
#if !defined INCLUDED_JFW_PLUGIN_VENDORBASE_HXX
#define INCLUDED_JFW_PLUGIN_VENDORBASE_HXX
#include "rtl/ustring.hxx"
#include "rtl/ref.hxx"
#include "osl/endian.h"
#include "salhelper/simplereferenceobject.hxx"
#include <vector>
namespace jfw_plugin
{
//Used by subclasses of VendorBase to build paths to Java runtime
#if defined(__sparcv9)
#define JFW_PLUGIN_ARCH "sparcv9"
#elif defined SPARC
#define JFW_PLUGIN_ARCH "sparc"
#elif defined X86_64
#define JFW_PLUGIN_ARCH "amd64"
#elif defined INTEL
#define JFW_PLUGIN_ARCH "i386"
#elif defined POWERPC64
#define JFW_PLUGIN_ARCH "ppc64"
#elif defined POWERPC
#define JFW_PLUGIN_ARCH "ppc"
#elif defined MIPS
#ifdef OSL_BIGENDIAN
# define JFW_PLUGIN_ARCH "mips"
#else
# define JFW_PLUGIN_ARCH "mips32"
#endif
#elif defined S390X
#define JFW_PLUGIN_ARCH "s390x"
#elif defined S390
#define JFW_PLUGIN_ARCH "s390"
#elif defined ARM
#define JFW_PLUGIN_ARCH "arm"
#elif defined IA64
#define JFW_PLUGIN_ARCH "ia64"
#else // SPARC, INTEL, POWERPC, MIPS, ARM
#error unknown plattform
#endif // SPARC, INTEL, POWERPC, MIPS, ARM
class MalformedVersionException
{
public:
MalformedVersionException();
MalformedVersionException(const MalformedVersionException &);
virtual ~MalformedVersionException();
MalformedVersionException & operator =(const MalformedVersionException &);
};
class VendorBase: public salhelper::SimpleReferenceObject
{
public:
VendorBase();
/* returns relativ paths to the java executable as
file URLs.
For example "bin/java.exe". You need
to implement this function in a derived class, if
the paths differ. this implmentation provides for
Windows "bin/java.exe" and for Unix "bin/java".
The paths are relative file URLs. That is, they always
contain '/' even on windows. The paths are relative
to the installation directory of a JRE.
The signature of this function must correspond to
getJavaExePaths_func.
*/
static char const* const * getJavaExePaths(int* size);
/* creates an instance of this class. MUST be overridden
in a derived class.
####################################################
OVERRIDE in derived class
###################################################
@param
Key - value pairs of the system properties of the JRE.
*/
static rtl::Reference<VendorBase> createInstance();
/* called automatically on the instance created by createInstance.
@return
true - the object could completely initialize.
false - the object could not completly initialize. In this case
it will be discarded by the caller.
*/
virtual bool initialize(
std::vector<std::pair<rtl::OUString, rtl::OUString> > props);
/* returns relative file URLs to the runtime library.
For example "/bin/client/jvm.dll"
*/
virtual char const* const* getRuntimePaths(int* size);
virtual char const* const* getLibraryPaths(int* size);
virtual const rtl::OUString & getVendor() const;
virtual const rtl::OUString & getVersion() const;
virtual const rtl::OUString & getHome() const;
virtual const rtl::OUString & getRuntimeLibrary() const;
virtual const rtl::OUString & getLibraryPaths() const;
virtual bool supportsAccessibility() const;
/* determines if prior to running java something has to be done,
like setting the LD_LIBRARY_PATH. This implementation checks
if an LD_LIBRARY_PATH (getLD_LIBRARY_PATH) needs to be set and
if so, needsRestart returns true.
*/
virtual bool needsRestart() const;
/* compares versions of this vendor. MUST be overridden
in a derived class.
####################################################
OVERRIDE in derived class
###################################################
@return
0 this.version == sSecond
1 this.version > sSecond
-1 this.version < sSEcond
@throw
MalformedVersionException if the version string was not recognized.
*/
virtual int compareVersions(const rtl::OUString& sSecond) const;
protected:
rtl::OUString m_sVendor;
rtl::OUString m_sVersion;
rtl::OUString m_sHome;
rtl::OUString m_sRuntimeLibrary;
rtl::OUString m_sLD_LIBRARY_PATH;
bool m_bAccessibility;
typedef rtl::Reference<VendorBase> (* createInstance_func) ();
friend rtl::Reference<VendorBase> createInstance(
createInstance_func pFunc,
std::vector<std::pair<rtl::OUString, rtl::OUString> > properties);
};
}
#endif
<commit_msg>INTEGRATION: CWS m68kport01 (1.13.10); FILE MERGED 2008/06/11 07:59:07 cmc 1.13.10.1: #i90600# jvmfwk support for m68k<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: vendorbase.hxx,v $
* $Revision: 1.15 $
*
* 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.
*
************************************************************************/
#if !defined INCLUDED_JFW_PLUGIN_VENDORBASE_HXX
#define INCLUDED_JFW_PLUGIN_VENDORBASE_HXX
#include "rtl/ustring.hxx"
#include "rtl/ref.hxx"
#include "osl/endian.h"
#include "salhelper/simplereferenceobject.hxx"
#include <vector>
namespace jfw_plugin
{
//Used by subclasses of VendorBase to build paths to Java runtime
#if defined(__sparcv9)
#define JFW_PLUGIN_ARCH "sparcv9"
#elif defined SPARC
#define JFW_PLUGIN_ARCH "sparc"
#elif defined X86_64
#define JFW_PLUGIN_ARCH "amd64"
#elif defined INTEL
#define JFW_PLUGIN_ARCH "i386"
#elif defined POWERPC64
#define JFW_PLUGIN_ARCH "ppc64"
#elif defined POWERPC
#define JFW_PLUGIN_ARCH "ppc"
#elif defined MIPS
#ifdef OSL_BIGENDIAN
# define JFW_PLUGIN_ARCH "mips"
#else
# define JFW_PLUGIN_ARCH "mips32"
#endif
#elif defined S390X
#define JFW_PLUGIN_ARCH "s390x"
#elif defined S390
#define JFW_PLUGIN_ARCH "s390"
#elif defined ARM
#define JFW_PLUGIN_ARCH "arm"
#elif defined IA64
#define JFW_PLUGIN_ARCH "ia64"
#elif defined M68K
#define JFW_PLUGIN_ARCH "m68k"
#else // SPARC, INTEL, POWERPC, MIPS, ARM, IA64, M68K
#error unknown plattform
#endif // SPARC, INTEL, POWERPC, MIPS, ARM
class MalformedVersionException
{
public:
MalformedVersionException();
MalformedVersionException(const MalformedVersionException &);
virtual ~MalformedVersionException();
MalformedVersionException & operator =(const MalformedVersionException &);
};
class VendorBase: public salhelper::SimpleReferenceObject
{
public:
VendorBase();
/* returns relativ paths to the java executable as
file URLs.
For example "bin/java.exe". You need
to implement this function in a derived class, if
the paths differ. this implmentation provides for
Windows "bin/java.exe" and for Unix "bin/java".
The paths are relative file URLs. That is, they always
contain '/' even on windows. The paths are relative
to the installation directory of a JRE.
The signature of this function must correspond to
getJavaExePaths_func.
*/
static char const* const * getJavaExePaths(int* size);
/* creates an instance of this class. MUST be overridden
in a derived class.
####################################################
OVERRIDE in derived class
###################################################
@param
Key - value pairs of the system properties of the JRE.
*/
static rtl::Reference<VendorBase> createInstance();
/* called automatically on the instance created by createInstance.
@return
true - the object could completely initialize.
false - the object could not completly initialize. In this case
it will be discarded by the caller.
*/
virtual bool initialize(
std::vector<std::pair<rtl::OUString, rtl::OUString> > props);
/* returns relative file URLs to the runtime library.
For example "/bin/client/jvm.dll"
*/
virtual char const* const* getRuntimePaths(int* size);
virtual char const* const* getLibraryPaths(int* size);
virtual const rtl::OUString & getVendor() const;
virtual const rtl::OUString & getVersion() const;
virtual const rtl::OUString & getHome() const;
virtual const rtl::OUString & getRuntimeLibrary() const;
virtual const rtl::OUString & getLibraryPaths() const;
virtual bool supportsAccessibility() const;
/* determines if prior to running java something has to be done,
like setting the LD_LIBRARY_PATH. This implementation checks
if an LD_LIBRARY_PATH (getLD_LIBRARY_PATH) needs to be set and
if so, needsRestart returns true.
*/
virtual bool needsRestart() const;
/* compares versions of this vendor. MUST be overridden
in a derived class.
####################################################
OVERRIDE in derived class
###################################################
@return
0 this.version == sSecond
1 this.version > sSecond
-1 this.version < sSEcond
@throw
MalformedVersionException if the version string was not recognized.
*/
virtual int compareVersions(const rtl::OUString& sSecond) const;
protected:
rtl::OUString m_sVendor;
rtl::OUString m_sVersion;
rtl::OUString m_sHome;
rtl::OUString m_sRuntimeLibrary;
rtl::OUString m_sLD_LIBRARY_PATH;
bool m_bAccessibility;
typedef rtl::Reference<VendorBase> (* createInstance_func) ();
friend rtl::Reference<VendorBase> createInstance(
createInstance_func pFunc,
std::vector<std::pair<rtl::OUString, rtl::OUString> > properties);
};
}
#endif
<|endoftext|> |
<commit_before>/*
* V1.cpp
*
* Created on: Jul 30, 2008
* Author: rasmussn
*/
#include "../include/pv_common.h"
#include "../include/default_params.h"
#include "../connections/PVConnection.h"
#include "HyPerLayer.hpp"
#include "V1.hpp"
#include <assert.h>
#include <float.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
namespace PV
{
V1Params V1DefaultParams =
{
V_REST, V_EXC, V_INH, V_INHB, // V (mV)
TAU_VMEM, TAU_EXC, TAU_INH, TAU_INHB,
VTH_REST, TAU_VTH, DELTA_VTH, // tau (ms)
250, NOISE_AMP*( 1.0/TAU_EXC ) * ( ( TAU_INH * (V_REST-V_INH) + TAU_INHB * (V_REST-V_INHB) ) / (V_EXC-V_REST) ),
250, NOISE_AMP*1.0,
250, NOISE_AMP*1.0 // noise (G)
};
V1::V1(const char* name, HyPerCol * hc)
: HyPerLayer(name, hc)
{
initialize(TypeV1Simple);
}
V1::V1(const char* name, HyPerCol * hc, PVLayerType type)
: HyPerLayer(name, hc)
{
initialize(type);
}
int V1::initialize(PVLayerType type)
{
float time = 0.0f;
setParams(parent->parameters(), &V1DefaultParams);
pvlayer_setFuncs(clayer, (INIT_FN) &LIF2_init, (UPDATE_FN) &LIF2_update_exact_linear);
this->clayer->layerType = type;
parent->addLayer(this);
if (parent->parameters()->value(name, "restart", 0) != 0) {
readState(name, &time);
}
return 0;
}
int V1::setParams(PVParams * params, V1Params * p)
{
float dt = .001 * parent->getDeltaTime(); // seconds
clayer->params = (float *) malloc(sizeof(*p));
assert(clayer->params != NULL);
memcpy(clayer->params, p, sizeof(*p));
clayer->numParams = sizeof(*p) / sizeof(float);
assert(clayer->numParams == 17);
V1Params * cp = (V1Params *) clayer->params;
if (params->present(name, "Vrest")) cp->Vrest = params->value(name, "Vrest");
if (params->present(name, "Vexc")) cp->Vexc = params->value(name, "Vexc");
if (params->present(name, "Vinh")) cp->Vinh = params->value(name, "Vinh");
if (params->present(name, "VinhB")) cp->VinhB = params->value(name, "VinhB");
if (params->present(name, "tau")) cp->tau = params->value(name, "tau");
if (params->present(name, "tauE")) cp->tauE = params->value(name, "tauE");
if (params->present(name, "tauI")) cp->tauI = params->value(name, "tauI");
if (params->present(name, "tauIB")) cp->tauIB = params->value(name, "tauIB");
if (params->present(name, "VthRest")) cp->VthRest = params->value(name, "VthRest");
if (params->present(name, "tauVth")) cp->tauVth = params->value(name, "tauVth");
if (params->present(name, "deltaVth")) cp->deltaVth = params->value(name, "deltaVth");
if (params->present(name, "noiseAmpE")) cp->noiseAmpE = params->value(name, "noiseAmpE");
if (params->present(name, "noiseAmpI")) cp->noiseAmpI = params->value(name, "noiseAmpI");
if (params->present(name, "noiseAmpIB")) cp->noiseAmpIB = params->value(name, "noiseAmpIB");
if (params->present(name, "noiseFreqE")) {
cp->noiseFreqE = params->value(name, "noiseFreqE");
if (dt * cp->noiseFreqE > 1.0) cp->noiseFreqE = 1.0 / dt;
}
if (params->present(name, "noiseFreqI")) {
cp->noiseFreqI = params->value(name, "noiseFreqI");
if (dt * cp->noiseFreqI > 1.0) cp->noiseFreqI = 1.0 / dt;
}
if (params->present(name, "noiseFreqIB")) {
cp->noiseFreqIB = params->value(name, "noiseFreqIB");
if (dt * cp->noiseFreqIB > 1.0) cp->noiseFreqIB = 1.0 / dt;
}
return 0;
}
int V1::updateState(float time, float dt)
{
PVParams * params = parent->parameters();
pv_debug_info("[%d]: V1::updateState:", clayer->columnId);
int spikingFlag = (int) params->value(name, "spikingFlag", 1);
if (spikingFlag != 0) {
return LIF2_update_exact_linear(clayer, dt);
}
// just copy accumulation buffer to membrane potential
// and activity buffer (nonspiking)
const int nx = clayer->loc.nx;
const int ny = clayer->loc.ny;
const int nf = clayer->numFeatures;
const int marginWidth = clayer->loc.nPad;
pvdata_t * V = clayer->V;
pvdata_t * phiExc = clayer->phi[PHI_EXC];
pvdata_t * phiInh = clayer->phi[PHI_INH];
pvdata_t * activity = clayer->activity->data;
// make sure activity in border is zero
//
for (int k = 0; k < clayer->numExtended; k++) {
activity[k] = 0.0;
}
for (int k = 0; k < clayer->numNeurons; k++) {
int kex = kIndexExtended(k, nx, ny, nf, marginWidth);
V[k] = phiExc[k] - phiInh[k];
activity[kex] = V[k];
// reset accumulation buffers
phiExc[k] = 0.0;
phiInh[k] = 0.0;
}
return 0;
}
int V1::writeState(const char * path, float time)
{
HyPerLayer::writeState(path, time);
#ifdef DEBUG_OUTPUT
// print activity at center of image
int sx = clayer->numFeatures;
int sy = sx*clayer->loc.nx;
pvdata_t * a = clayer->activity->data;
int n = (int) (sy*(clayer->loc.ny/2 - 1) + sx*(clayer->loc.nx/2));
for (int f = 0; f < clayer->numFeatures; f++) {
printf("f = %d, a[%d] = %f\n", f, n, a[n]);
n += 1;
}
printf("\n");
n = (int) (sy*(clayer->loc.ny/2 - 1) + sx*(clayer->loc.nx/2));
n -= 8;
for (int f = 0; f < clayer->numFeatures; f++) {
printf("f = %d, a[%d] = %f\n", f, n, a[n]);
n += 1;
}
#endif
return 0;
}
int V1::findPostSynaptic(int dim, int maxSize, int col,
// input: which layer, which neuron
HyPerLayer *lSource, float pos[],
// output: how many of our neurons are connected.
// an array with their indices.
// an array with their feature vectors.
int* nNeurons, int nConnectedNeurons[], float *vPos)
{
return 0;
}
} // namespace PV
<commit_msg>Set noise off be default.<commit_after>/*
* V1.cpp
*
* Created on: Jul 30, 2008
* Author: rasmussn
*/
#include "../include/pv_common.h"
#include "../include/default_params.h"
#include "../connections/PVConnection.h"
#include "HyPerLayer.hpp"
#include "V1.hpp"
#include <assert.h>
#include <float.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
namespace PV
{
V1Params V1DefaultParams =
{
V_REST, V_EXC, V_INH, V_INHB, // V (mV)
TAU_VMEM, TAU_EXC, TAU_INH, TAU_INHB,
VTH_REST, TAU_VTH, DELTA_VTH, // tau (ms)
250, 0*NOISE_AMP*( 1.0/TAU_EXC ) * ( ( TAU_INH * (V_REST-V_INH) + TAU_INHB * (V_REST-V_INHB) ) / (V_EXC-V_REST) ),
250, 0*NOISE_AMP*1.0,
250, 0*NOISE_AMP*1.0 // noise (G)
};
V1::V1(const char* name, HyPerCol * hc)
: HyPerLayer(name, hc)
{
initialize(TypeV1Simple);
}
V1::V1(const char* name, HyPerCol * hc, PVLayerType type)
: HyPerLayer(name, hc)
{
initialize(type);
}
int V1::initialize(PVLayerType type)
{
float time = 0.0f;
setParams(parent->parameters(), &V1DefaultParams);
pvlayer_setFuncs(clayer, (INIT_FN) &LIF2_init, (UPDATE_FN) &LIF2_update_exact_linear);
this->clayer->layerType = type;
parent->addLayer(this);
if (parent->parameters()->value(name, "restart", 0) != 0) {
readState(name, &time);
}
return 0;
}
int V1::setParams(PVParams * params, V1Params * p)
{
float dt = .001 * parent->getDeltaTime(); // seconds
clayer->params = (float *) malloc(sizeof(*p));
assert(clayer->params != NULL);
memcpy(clayer->params, p, sizeof(*p));
clayer->numParams = sizeof(*p) / sizeof(float);
assert(clayer->numParams == 17);
V1Params * cp = (V1Params *) clayer->params;
if (params->present(name, "Vrest")) cp->Vrest = params->value(name, "Vrest");
if (params->present(name, "Vexc")) cp->Vexc = params->value(name, "Vexc");
if (params->present(name, "Vinh")) cp->Vinh = params->value(name, "Vinh");
if (params->present(name, "VinhB")) cp->VinhB = params->value(name, "VinhB");
if (params->present(name, "tau")) cp->tau = params->value(name, "tau");
if (params->present(name, "tauE")) cp->tauE = params->value(name, "tauE");
if (params->present(name, "tauI")) cp->tauI = params->value(name, "tauI");
if (params->present(name, "tauIB")) cp->tauIB = params->value(name, "tauIB");
if (params->present(name, "VthRest")) cp->VthRest = params->value(name, "VthRest");
if (params->present(name, "tauVth")) cp->tauVth = params->value(name, "tauVth");
if (params->present(name, "deltaVth")) cp->deltaVth = params->value(name, "deltaVth");
if (params->present(name, "noiseAmpE")) cp->noiseAmpE = params->value(name, "noiseAmpE");
if (params->present(name, "noiseAmpI")) cp->noiseAmpI = params->value(name, "noiseAmpI");
if (params->present(name, "noiseAmpIB")) cp->noiseAmpIB = params->value(name, "noiseAmpIB");
if (params->present(name, "noiseFreqE")) {
cp->noiseFreqE = params->value(name, "noiseFreqE");
if (dt * cp->noiseFreqE > 1.0) cp->noiseFreqE = 1.0 / dt;
}
if (params->present(name, "noiseFreqI")) {
cp->noiseFreqI = params->value(name, "noiseFreqI");
if (dt * cp->noiseFreqI > 1.0) cp->noiseFreqI = 1.0 / dt;
}
if (params->present(name, "noiseFreqIB")) {
cp->noiseFreqIB = params->value(name, "noiseFreqIB");
if (dt * cp->noiseFreqIB > 1.0) cp->noiseFreqIB = 1.0 / dt;
}
return 0;
}
int V1::updateState(float time, float dt)
{
PVParams * params = parent->parameters();
pv_debug_info("[%d]: V1::updateState:", clayer->columnId);
int spikingFlag = (int) params->value(name, "spikingFlag", 1);
if (spikingFlag != 0) {
return LIF2_update_exact_linear(clayer, dt);
}
// just copy accumulation buffer to membrane potential
// and activity buffer (nonspiking)
const int nx = clayer->loc.nx;
const int ny = clayer->loc.ny;
const int nf = clayer->numFeatures;
const int marginWidth = clayer->loc.nPad;
pvdata_t * V = clayer->V;
pvdata_t * phiExc = clayer->phi[PHI_EXC];
pvdata_t * phiInh = clayer->phi[PHI_INH];
pvdata_t * activity = clayer->activity->data;
// make sure activity in border is zero
//
for (int k = 0; k < clayer->numExtended; k++) {
activity[k] = 0.0;
}
for (int k = 0; k < clayer->numNeurons; k++) {
int kex = kIndexExtended(k, nx, ny, nf, marginWidth);
V[k] = phiExc[k] - phiInh[k];
activity[kex] = V[k];
// reset accumulation buffers
phiExc[k] = 0.0;
phiInh[k] = 0.0;
}
return 0;
}
int V1::writeState(const char * path, float time)
{
HyPerLayer::writeState(path, time);
#ifdef DEBUG_OUTPUT
// print activity at center of image
int sx = clayer->numFeatures;
int sy = sx*clayer->loc.nx;
pvdata_t * a = clayer->activity->data;
int n = (int) (sy*(clayer->loc.ny/2 - 1) + sx*(clayer->loc.nx/2));
for (int f = 0; f < clayer->numFeatures; f++) {
printf("f = %d, a[%d] = %f\n", f, n, a[n]);
n += 1;
}
printf("\n");
n = (int) (sy*(clayer->loc.ny/2 - 1) + sx*(clayer->loc.nx/2));
n -= 8;
for (int f = 0; f < clayer->numFeatures; f++) {
printf("f = %d, a[%d] = %f\n", f, n, a[n]);
n += 1;
}
#endif
return 0;
}
int V1::findPostSynaptic(int dim, int maxSize, int col,
// input: which layer, which neuron
HyPerLayer *lSource, float pos[],
// output: how many of our neurons are connected.
// an array with their indices.
// an array with their feature vectors.
int* nNeurons, int nConnectedNeurons[], float *vPos)
{
return 0;
}
} // namespace PV
<|endoftext|> |
<commit_before>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <af/exception.h>
#include <af/device.h>
#include <err_common.hpp>
#include <type_util.hpp>
#include <util.hpp>
#include <string>
#include <sstream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#if defined(WITH_GRAPHICS) && !defined(AF_UNIFIED)
#include <graphics_common.hpp>
#endif
using std::string;
using std::stringstream;
AfError::AfError(const char * const func,
const char * const file,
const int line,
const char * const message, af_err err)
: logic_error (message),
functionName (func),
fileName (file),
lineNumber(line),
error(err)
{}
AfError::AfError(string func,
string file,
const int line,
string message, af_err err)
: logic_error (message),
functionName (func),
fileName (file),
lineNumber(line),
error(err)
{}
const string&
AfError::getFunctionName() const
{
return functionName;
}
const string&
AfError::getFileName() const
{
return fileName;
}
int
AfError::getLine() const
{
return lineNumber;
}
af_err
AfError::getError() const
{
return error;
}
AfError::~AfError() throw() {}
TypeError::TypeError(const char * const func,
const char * const file,
const int line,
const int index, const af_dtype type)
: AfError (func, file, line, "Invalid data type", AF_ERR_TYPE),
argIndex(index),
errTypeName(getName(type))
{}
const string& TypeError::getTypeName() const
{
return errTypeName;
}
int TypeError::getArgIndex() const
{
return argIndex;
}
ArgumentError::ArgumentError(const char * const func,
const char * const file,
const int line,
const int index,
const char * const expectString)
: AfError(func, file, line, "Invalid argument", AF_ERR_ARG),
argIndex(index),
expected(expectString)
{
}
const string& ArgumentError::getExpectedCondition() const
{
return expected;
}
int ArgumentError::getArgIndex() const
{
return argIndex;
}
SupportError::SupportError(const char * const func,
const char * const file,
const int line,
const char * const back)
: AfError(func, file, line, "Unsupported Error", AF_ERR_NOT_SUPPORTED),
backend(back)
{}
const string& SupportError::getBackendName() const
{
return backend;
}
DimensionError::DimensionError(const char * const func,
const char * const file,
const int line,
const int index,
const char * const expectString)
: AfError(func, file, line, "Invalid size", AF_ERR_SIZE),
argIndex(index),
expected(expectString)
{
}
const string& DimensionError::getExpectedCondition() const
{
return expected;
}
int DimensionError::getArgIndex() const
{
return argIndex;
}
static const int MAX_ERR_SIZE = 1024;
static std::string global_err_string;
void
print_error(const string &msg)
{
std::string perr = getEnvVar("AF_PRINT_ERRORS");
if(!perr.empty()) {
if(perr != "0")
fprintf(stderr, "%s\n", msg.c_str());
}
global_err_string = msg;
}
void af_get_last_error(char **str, dim_t *len)
{
*len = std::min(MAX_ERR_SIZE, (int)global_err_string.size());
if (*len == 0) {
*str = NULL;
}
af_alloc_host((void**)str, sizeof(char) * (*len + 1));
global_err_string.copy(*str, *len);
(*str)[*len] = '\0';
global_err_string = std::string("");
}
const char *af_err_to_string(const af_err err)
{
switch (err) {
case AF_SUCCESS: return "Success";
case AF_ERR_INTERNAL: return "Internal error";
case AF_ERR_NO_MEM: return "Device out of memory";
case AF_ERR_DRIVER: return "Driver not available or incompatible";
case AF_ERR_RUNTIME: return "Runtime error ";
case AF_ERR_INVALID_ARRAY: return "Invalid array";
case AF_ERR_ARG: return "Invalid input argument";
case AF_ERR_SIZE: return "Invalid input size";
case AF_ERR_DIFF_TYPE: return "Input types are not the same";
case AF_ERR_NOT_SUPPORTED: return "Function not supported";
case AF_ERR_NOT_CONFIGURED: return "Function not configured to build";
case AF_ERR_TYPE: return "Function does not support this data type";
case AF_ERR_NO_DBL: return "Double precision not supported for this device";
case AF_ERR_LOAD_LIB: return "Failed to load dynamic library. See http://www.arrayfire.com/docs/unifiedbackend.htm for instructions to set up environment for Unified backend";
case AF_ERR_LOAD_SYM: return "Failed to load symbol";
case AF_ERR_ARR_BKND_MISMATCH :
return "There was a mismatch between an array and the current backend";
case AF_ERR_UNKNOWN:
default:
return "Unknown error";
}
}
af_err processException()
{
stringstream ss;
af_err err= AF_ERR_INTERNAL;
try {
throw;
} catch (const DimensionError &ex) {
ss << "In function " << ex.getFunctionName() << "\n"
<< "In file " << ex.getFileName() << ":" << ex.getLine() << "\n"
<< "Invalid dimension for argument " << ex.getArgIndex() << "\n"
<< "Expected: " << ex.getExpectedCondition() << "\n";
print_error(ss.str());
err = AF_ERR_SIZE;
} catch (const ArgumentError &ex) {
ss << "In function " << ex.getFunctionName() << "\n"
<< "In file " << ex.getFileName() << ":" << ex.getLine() << "\n"
<< "Invalid argument at index " << ex.getArgIndex() << "\n"
<< "Expected: " << ex.getExpectedCondition() << "\n";
print_error(ss.str());
err = AF_ERR_ARG;
} catch (const SupportError &ex) {
ss << ex.getFunctionName()
<< " not supported for " << ex.getBackendName()
<< " backend\n";
print_error(ss.str());
err = AF_ERR_NOT_SUPPORTED;
} catch (const TypeError &ex) {
ss << "In function " << ex.getFunctionName() << "\n"
<< "In file " << ex.getFileName() << ":" << ex.getLine() << "\n"
<< "Invalid type for argument " << ex.getArgIndex() << "\n";
print_error(ss.str());
err = AF_ERR_TYPE;
} catch (const AfError &ex) {
ss << "In function " << ex.getFunctionName() << "\n"
<< "In file " << ex.getFileName() << ":" << ex.getLine() << "\n"
<< ex.what() << "\n";
print_error(ss.str());
err = ex.getError();
#if defined(WITH_GRAPHICS) && !defined(AF_UNIFIED)
} catch (const fg::Error &ex) {
ss << ex << "\n";
print_error(ss.str());
err = AF_ERR_INTERNAL;
#endif
} catch (...) {
print_error(ss.str());
err = AF_ERR_UNKNOWN;
}
return err;
}
<commit_msg>Add missing af_err to string<commit_after>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <af/exception.h>
#include <af/device.h>
#include <err_common.hpp>
#include <type_util.hpp>
#include <util.hpp>
#include <string>
#include <sstream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#if defined(WITH_GRAPHICS) && !defined(AF_UNIFIED)
#include <graphics_common.hpp>
#endif
using std::string;
using std::stringstream;
AfError::AfError(const char * const func,
const char * const file,
const int line,
const char * const message, af_err err)
: logic_error (message),
functionName (func),
fileName (file),
lineNumber(line),
error(err)
{}
AfError::AfError(string func,
string file,
const int line,
string message, af_err err)
: logic_error (message),
functionName (func),
fileName (file),
lineNumber(line),
error(err)
{}
const string&
AfError::getFunctionName() const
{
return functionName;
}
const string&
AfError::getFileName() const
{
return fileName;
}
int
AfError::getLine() const
{
return lineNumber;
}
af_err
AfError::getError() const
{
return error;
}
AfError::~AfError() throw() {}
TypeError::TypeError(const char * const func,
const char * const file,
const int line,
const int index, const af_dtype type)
: AfError (func, file, line, "Invalid data type", AF_ERR_TYPE),
argIndex(index),
errTypeName(getName(type))
{}
const string& TypeError::getTypeName() const
{
return errTypeName;
}
int TypeError::getArgIndex() const
{
return argIndex;
}
ArgumentError::ArgumentError(const char * const func,
const char * const file,
const int line,
const int index,
const char * const expectString)
: AfError(func, file, line, "Invalid argument", AF_ERR_ARG),
argIndex(index),
expected(expectString)
{
}
const string& ArgumentError::getExpectedCondition() const
{
return expected;
}
int ArgumentError::getArgIndex() const
{
return argIndex;
}
SupportError::SupportError(const char * const func,
const char * const file,
const int line,
const char * const back)
: AfError(func, file, line, "Unsupported Error", AF_ERR_NOT_SUPPORTED),
backend(back)
{}
const string& SupportError::getBackendName() const
{
return backend;
}
DimensionError::DimensionError(const char * const func,
const char * const file,
const int line,
const int index,
const char * const expectString)
: AfError(func, file, line, "Invalid size", AF_ERR_SIZE),
argIndex(index),
expected(expectString)
{
}
const string& DimensionError::getExpectedCondition() const
{
return expected;
}
int DimensionError::getArgIndex() const
{
return argIndex;
}
static const int MAX_ERR_SIZE = 1024;
static std::string global_err_string;
void
print_error(const string &msg)
{
std::string perr = getEnvVar("AF_PRINT_ERRORS");
if(!perr.empty()) {
if(perr != "0")
fprintf(stderr, "%s\n", msg.c_str());
}
global_err_string = msg;
}
void af_get_last_error(char **str, dim_t *len)
{
*len = std::min(MAX_ERR_SIZE, (int)global_err_string.size());
if (*len == 0) {
*str = NULL;
}
af_alloc_host((void**)str, sizeof(char) * (*len + 1));
global_err_string.copy(*str, *len);
(*str)[*len] = '\0';
global_err_string = std::string("");
}
const char *af_err_to_string(const af_err err)
{
switch (err) {
case AF_SUCCESS: return "Success";
case AF_ERR_NO_MEM: return "Device out of memory";
case AF_ERR_DRIVER: return "Driver not available or incompatible";
case AF_ERR_RUNTIME: return "Runtime error ";
case AF_ERR_INVALID_ARRAY: return "Invalid array";
case AF_ERR_ARG: return "Invalid input argument";
case AF_ERR_SIZE: return "Invalid input size";
case AF_ERR_TYPE: return "Function does not support this data type";
case AF_ERR_DIFF_TYPE: return "Input types are not the same";
case AF_ERR_BATCH: return "Invalid batch configuration";
case AF_ERR_NOT_SUPPORTED: return "Function not supported";
case AF_ERR_NOT_CONFIGURED: return "Function not configured to build";
case AF_ERR_NONFREE: return "Function unavailable."
"ArrayFire compiled without Non-Free algorithms support";
case AF_ERR_NO_DBL: return "Double precision not supported for this device";
case AF_ERR_NO_GFX: return "Graphics functionality unavailable."
"ArrayFire compiled without Graphics support";
case AF_ERR_LOAD_LIB: return "Failed to load dynamic library."
"See http://www.arrayfire.com/docs/unifiedbackend.htm"
"for instructions to set up environment for Unified backend";
case AF_ERR_LOAD_SYM: return "Failed to load symbol";
case AF_ERR_ARR_BKND_MISMATCH: return "There was a mismatch between an array and the current backend";
case AF_ERR_INTERNAL: return "Internal error";
case AF_ERR_UNKNOWN:
default: return "Unknown error";
}
}
af_err processException()
{
stringstream ss;
af_err err= AF_ERR_INTERNAL;
try {
throw;
} catch (const DimensionError &ex) {
ss << "In function " << ex.getFunctionName() << "\n"
<< "In file " << ex.getFileName() << ":" << ex.getLine() << "\n"
<< "Invalid dimension for argument " << ex.getArgIndex() << "\n"
<< "Expected: " << ex.getExpectedCondition() << "\n";
print_error(ss.str());
err = AF_ERR_SIZE;
} catch (const ArgumentError &ex) {
ss << "In function " << ex.getFunctionName() << "\n"
<< "In file " << ex.getFileName() << ":" << ex.getLine() << "\n"
<< "Invalid argument at index " << ex.getArgIndex() << "\n"
<< "Expected: " << ex.getExpectedCondition() << "\n";
print_error(ss.str());
err = AF_ERR_ARG;
} catch (const SupportError &ex) {
ss << ex.getFunctionName()
<< " not supported for " << ex.getBackendName()
<< " backend\n";
print_error(ss.str());
err = AF_ERR_NOT_SUPPORTED;
} catch (const TypeError &ex) {
ss << "In function " << ex.getFunctionName() << "\n"
<< "In file " << ex.getFileName() << ":" << ex.getLine() << "\n"
<< "Invalid type for argument " << ex.getArgIndex() << "\n";
print_error(ss.str());
err = AF_ERR_TYPE;
} catch (const AfError &ex) {
ss << "In function " << ex.getFunctionName() << "\n"
<< "In file " << ex.getFileName() << ":" << ex.getLine() << "\n"
<< ex.what() << "\n";
print_error(ss.str());
err = ex.getError();
#if defined(WITH_GRAPHICS) && !defined(AF_UNIFIED)
} catch (const fg::Error &ex) {
ss << ex << "\n";
print_error(ss.str());
err = AF_ERR_INTERNAL;
#endif
} catch (...) {
print_error(ss.str());
err = AF_ERR_UNKNOWN;
}
return err;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.