text stringlengths 54 60.6k |
|---|
<commit_before>// uatraits is a simple tool for user agent detection
// Copyright (C) 2011 Yandex <highpower@yandex-team.ru>
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#ifndef UATRAITS_DETAILS_BRANCH_HPP_INCLUDED
#define UATRAITS_DETAILS_BRANCH_HPP_INCLUDED
#include <list>
#include <iostream>
#include <algorithm>
#include "uatraits/config.hpp"
#include "uatraits/shared.hpp"
#include "uatraits/shared_ptr.hpp"
#include "uatraits/details/definition.hpp"
#include "uatraits/details/functors.hpp"
#include "uatraits/details/pcre_utils.hpp"
namespace uatraits { namespace details {
template <typename Traits>
class branch : public shared {
public:
branch(char const *xpath);
virtual ~branch();
typedef branch<Traits> type;
typedef definition<Traits> definition_type;
bool is_common() const;
void set_common(bool value);
bool is_default() const;
void set_default(bool value);
void add_match(char const *pattern);
void add_child(shared_ptr<type> const &child);
void add_definition(shared_ptr<definition_type> const &value);
void add_regex_match(char const *pattern);
void trigger(char const *begin, char const *end, Traits &traits) const;
virtual bool matched(char const *begin, char const *end) const;
private:
branch(branch const &);
branch& operator = (branch const &);
typedef shared_ptr<type> pointer;
typedef shared_ptr<definition_type> definition_pointer;
typedef std::pair<pcre*, pcre_extra*> regex_data;
private:
std::string xpath_;
bool common_, default_;
std::list<pointer> children_;
std::list<definition_pointer> definitions_;
std::list<regex_data> regex_matches_;
std::list<std::string> string_matches_;
};
template <typename Traits>
class root_branch : public branch<Traits> {
public:
root_branch();
virtual bool matched(char const *begin, char const *end) const;
};
template <typename Traits> inline
branch<Traits>::branch(char const *xpath) :
xpath_(xpath), common_(false), default_(false)
{
}
template <typename Traits> inline
branch<Traits>::~branch() {
for (std::list<regex_data>::iterator i = regex_matches_.begin(), end = regex_matches_.end(); i != end; ++i) {
pcre_free_regex(*i);
}
}
template <typename Traits> inline bool
branch<Traits>::is_common() const {
return common_;
}
template <typename Traits> inline void
branch<Traits>::set_common(bool value) {
common_ = value;
}
template <typename Traits> inline bool
branch<Traits>::is_default() const {
return default_;
}
template <typename Traits> inline void
branch<Traits>::set_default(bool value) {
default_ = value;
}
template <typename Traits> inline void
branch<Traits>::add_match(char const *pattern) {
string_matches_.push_back(std::string(pattern));
}
template <typename Traits> inline void
branch<Traits>::add_child(shared_ptr<type> const &child) {
children_.push_back(child);
}
template <typename Traits> inline void
branch<Traits>::add_definition(shared_ptr<definition_type> const &value) {
definitions_.push_back(value);
}
template <typename Traits> inline void
branch<Traits>::add_regex_match(char const *pattern) {
regex_matches_.push_back(pcre_compile_regex(pattern));
}
template <typename Traits> inline void
branch<Traits>::trigger(char const *begin, char const *end, Traits &traits) const {
for (typename std::list<definition_pointer>::const_iterator i = definitions_.begin(), list_end = definitions_.end(); i != list_end; ++i) {
(*i)->trigger(begin, end, traits);
}
bool worked = false;
pointer default_branch;
for (typename std::list<pointer>::const_iterator i = children_.begin(), list_end = children_.end(); i != list_end; ++i) {
if ((*i)->is_default()) {
default_branch = *i;
}
else if ((*i)->is_common()) {
(*i)->trigger(begin, end, traits);
}
else if (!worked && (*i)->matched(begin, end)) {
worked = true;
(*i)->trigger(begin, end, traits);
}
}
if (!worked && default_branch) {
default_branch->trigger(begin, end, traits);
}
}
template <typename Traits> inline bool
branch<Traits>::matched(char const *begin, char const *end) const {
for (std::list<std::string>::const_iterator i = string_matches_.begin(), list_end = string_matches_.end(); i != list_end; ++i) {
if (std::search(begin, end, i->begin(), i->end(), ci_equal<char>()) != end) {
return true;
}
}
for (std::list<regex_data>::const_iterator i = regex_matches_.begin(), list_end = regex_matches_.end(); i != list_end; ++i) {
if (0 == pcre_exec(i->first, i->second, begin, end - begin, 0, 0, 0, 0)) {
return true;
}
}
return false;
}
template <typename Traits> inline
root_branch<Traits>::root_branch() :
branch<Traits>("")
{
}
template <typename Traits> inline bool
root_branch<Traits>::matched(char const *begin, char const *end) const {
(void) begin; (void) end;
return true;
}
}} // namespaces
#endif // UATRAITS_DETAILS_BRANCH_HPP_INCLUDED
<commit_msg>threadsafe trigger(); beautiful tabs ;)<commit_after>// uatraits is a simple tool for user agent detection
// Copyright (C) 2011 Yandex <highpower@yandex-team.ru>
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#ifndef UATRAITS_DETAILS_BRANCH_HPP_INCLUDED
#define UATRAITS_DETAILS_BRANCH_HPP_INCLUDED
#include <list>
#include <iostream>
#include <algorithm>
#include "uatraits/config.hpp"
#include "uatraits/shared.hpp"
#include "uatraits/shared_ptr.hpp"
#include "uatraits/details/definition.hpp"
#include "uatraits/details/functors.hpp"
#include "uatraits/details/pcre_utils.hpp"
namespace uatraits { namespace details {
template <typename Traits>
class branch : public shared {
public:
branch(char const *xpath);
virtual ~branch();
typedef branch<Traits> type;
typedef definition<Traits> definition_type;
bool is_common() const;
void set_common(bool value);
bool is_default() const;
void set_default(bool value);
void add_match(char const *pattern);
void add_child(shared_ptr<type> const &child);
void add_definition(shared_ptr<definition_type> const &value);
void add_regex_match(char const *pattern);
void trigger(char const *begin, char const *end, Traits &traits) const;
virtual bool matched(char const *begin, char const *end) const;
private:
branch(branch const &);
branch& operator = (branch const &);
typedef shared_ptr<type> pointer;
typedef shared_ptr<definition_type> definition_pointer;
typedef std::pair<pcre*, pcre_extra*> regex_data;
private:
std::string xpath_;
bool common_, default_;
std::list<pointer> children_;
std::list<definition_pointer> definitions_;
std::list<regex_data> regex_matches_;
std::list<std::string> string_matches_;
};
template <typename Traits>
class root_branch : public branch<Traits> {
public:
root_branch();
virtual bool matched(char const *begin, char const *end) const;
};
template <typename Traits> inline
branch<Traits>::branch(char const *xpath) :
xpath_(xpath), common_(false), default_(false)
{
}
template <typename Traits> inline
branch<Traits>::~branch() {
for (std::list<regex_data>::iterator i = regex_matches_.begin(), end = regex_matches_.end(); i != end; ++i) {
pcre_free_regex(*i);
}
}
template <typename Traits> inline bool
branch<Traits>::is_common() const {
return common_;
}
template <typename Traits> inline void
branch<Traits>::set_common(bool value) {
common_ = value;
}
template <typename Traits> inline bool
branch<Traits>::is_default() const {
return default_;
}
template <typename Traits> inline void
branch<Traits>::set_default(bool value) {
default_ = value;
}
template <typename Traits> inline void
branch<Traits>::add_match(char const *pattern) {
string_matches_.push_back(std::string(pattern));
}
template <typename Traits> inline void
branch<Traits>::add_child(shared_ptr<type> const &child) {
children_.push_back(child);
}
template <typename Traits> inline void
branch<Traits>::add_definition(shared_ptr<definition_type> const &value) {
definitions_.push_back(value);
}
template <typename Traits> inline void
branch<Traits>::add_regex_match(char const *pattern) {
regex_matches_.push_back(pcre_compile_regex(pattern));
}
template <typename Traits> inline void
branch<Traits>::trigger(char const *begin, char const *end, Traits &traits) const {
for (typename std::list<definition_pointer>::const_iterator i = definitions_.begin(), list_end = definitions_.end(); i != list_end; ++i) {
(*i)->trigger(begin, end, traits);
}
bool worked = false;
typename std::list<pointer>::const_iterator default_branch_iterator = children_.end();
for (typename std::list<pointer>::const_iterator i = children_.begin(), list_end = children_.end(); i != list_end; ++i) {
pointer const &ptr = *i;
if (ptr->is_default()) {
default_branch_iterator = i;
}
else if (ptr->is_common()) {
ptr->trigger(begin, end, traits);
}
else if (!worked && ptr->matched(begin, end)) {
worked = true;
ptr->trigger(begin, end, traits);
}
}
if (!worked && default_branch_iterator != children_.end()) {
(*default_branch_iterator)->trigger(begin, end, traits);
}
}
template <typename Traits> inline bool
branch<Traits>::matched(char const *begin, char const *end) const {
for (std::list<std::string>::const_iterator i = string_matches_.begin(), list_end = string_matches_.end(); i != list_end; ++i) {
if (std::search(begin, end, i->begin(), i->end(), ci_equal<char>()) != end) {
return true;
}
}
for (std::list<regex_data>::const_iterator i = regex_matches_.begin(), list_end = regex_matches_.end(); i != list_end; ++i) {
if (0 == pcre_exec(i->first, i->second, begin, end - begin, 0, 0, 0, 0)) {
return true;
}
}
return false;
}
template <typename Traits> inline
root_branch<Traits>::root_branch() :
branch<Traits>("")
{
}
template <typename Traits> inline bool
root_branch<Traits>::matched(char const *begin, char const *end) const {
(void) begin; (void) end;
return true;
}
}} // namespaces
#endif // UATRAITS_DETAILS_BRANCH_HPP_INCLUDED
<|endoftext|> |
<commit_before>/**
* The Locality Sensitive Hashing (LSH) library is part of the SEEKS project and
* does provide several locality sensitive hashing schemes for pattern matching over
* continuous and discrete spaces.
* Copyright (C) 2009 Emmanuel Benazera, juban@free.fr
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "mrf.h"
#include <algorithm>
#include <iostream>
//#define DEBUG
namespace lsh
{
/*-- str_chain --*/
str_chain::str_chain(const std::string &str,
const int &radius)
:_radius(radius),_skip(false)
{
add_token(str);
if (str == "<skip>")
_skip = true;
}
str_chain::str_chain(const str_chain &sc)
:_chain(sc.get_chain()),_radius(sc.get_radius()),
_skip(sc.has_skip())
{
}
void str_chain::add_token(const std::string &str)
{
_chain.push_back(str);
}
str_chain str_chain::rank_alpha() const
{
str_chain cchain = *this;
#ifdef DEBUG
/* std::cout << "cchain: ";
cchain.print(std::cout); */
#endif
std::sort(cchain.get_chain_noconst().begin(),cchain.get_chain_noconst().end());
#ifdef DEBUG
/* std::cout << "sorted chain: ";
cchain.print(std::cout); */
#endif
return cchain;
}
std::ostream& str_chain::print(std::ostream &output) const
{
for (size_t i=0;i<_chain.size();i++)
output << _chain.at(i) << " ";
output << std::endl;
return output;
}
/*-- mrf --*/
std::string mrf::_default_delims = " ";
uint32_t mrf::_skip_token = 0xDEADBEEF;
uint32_t mrf::_window_length_default = 8;
uint32_t mrf::_window_length = 8;
uint32_t mrf::_hctable[] = { 1, 3, 5, 11, 23, 47, 97, 197, 397, 797 };
double mrf::_epsilon = 1e-6; // infinitesimal.
void mrf::tokenize(const std::string &str,
std::vector<std::string> &tokens,
const std::string &delim)
{
// Skip delimiters at beginning.
std::string::size_type lastPos = str.find_first_not_of(delim, 0);
// Find first "non-delimiter".
std::string::size_type pos = str.find_first_of(delim, lastPos);
while (std::string::npos != pos || std::string::npos != lastPos)
{
// Found a token, add it to the vector.
tokens.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = str.find_first_not_of(delim, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delim, lastPos);
}
}
uint32_t mrf::mrf_single_feature(const std::string &str)
{
std::vector<std::string> tokens;
mrf::tokenize(str,tokens,mrf::_default_delims);
return mrf::mrf_hash(tokens);
}
void mrf::mrf_features(const std::string &str,
std::vector<uint32_t> &features,
const int &min_radius,
const int &max_radius)
{
std::vector<std::string> tokens;
mrf::tokenize(str,tokens,mrf::_default_delims);
int gen_radius = 0;
while(!tokens.empty())
{
mrf::mrf_build(tokens,features,
min_radius,max_radius,
gen_radius);
tokens.erase(tokens.begin());
++gen_radius;
}
std::sort(features.begin(),features.end());
}
void mrf::mrf_build(const std::vector<std::string> &tokens,
std::vector<uint32_t> &features,
const int &min_radius,
const int &max_radius,
const int &gen_radius)
{
// scale the field's window size.
if (tokens.size() < mrf::_window_length_default)
mrf::_window_length = tokens.size();
int tok = 0;
std::queue<str_chain> chains;
mrf::mrf_build(tokens,tok,chains,features,
min_radius,max_radius,gen_radius);
// reset the field's window size.
mrf::_window_length = mrf::_window_length_default;
}
void mrf::mrf_build(const std::vector<std::string> &tokens,
int &tok,
std::queue<str_chain> &chains,
std::vector<uint32_t> &features,
const int &min_radius, const int &max_radius,
const int &gen_radius)
{
if (chains.empty())
{
int radius_chain = gen_radius+tokens.size()-1;
str_chain chain(tokens.at(tok),radius_chain);
if (radius_chain >= min_radius
&& radius_chain <= max_radius)
{
//hash chain and add it to features set.
uint32_t h = mrf::mrf_hash(chain);
features.push_back(h);
#ifdef DEBUG
//debug
std::cout << tokens.at(tok) << std::endl;
std::cout << std::hex << h << std::endl;
std::cout << std::endl;
//debug
#endif
}
chains.push(chain);
mrf::mrf_build(tokens,tok,chains,features,
min_radius,max_radius,gen_radius);
}
else
{
++tok;
std::queue<str_chain> nchains;
while(!chains.empty())
{
str_chain chain = chains.front();
chains.pop();
if (chain.size() < mrf::_window_length)
{
// first generated chain: add a token.
str_chain chain1(chain);
chain1.add_token(tokens.at(tok));
chain1.decr_radius();
if (chain1.get_radius() >= min_radius
&& chain1.get_radius() <= max_radius)
{
// hash it and add it to features.
uint32_t h = mrf::mrf_hash(chain1);
features.push_back(h);
#ifdef DEBUG
//debug
chain1.print(std::cout);
std::cout << std::hex << h << std::endl;
std::cout << std::endl;
//debug
#endif
}
// second generated chain: add a 'skip' token.
str_chain chain2 = chain;
chain2.add_token("<skip>");
chain2.set_skip();
nchains.push(chain1);
nchains.push(chain2);
}
}
if (!nchains.empty())
mrf::mrf_build(tokens,tok,nchains,features,
min_radius,max_radius,gen_radius);
}
}
uint32_t mrf::mrf_hash(const str_chain &chain)
{
// rank chains which do not contain any skipped token (i.e. no
// order preservation).
str_chain cchain(chain);
if (!chain.has_skip())
cchain = chain.rank_alpha();
uint32_t h = 0;
size_t csize = std::min(10,(int)cchain.size()); // beware: hctable may be too small...
for (size_t i=0;i<csize;i++)
{
std::string token = cchain.at(i);
uint32_t hashed_token = mrf::_skip_token;
if (token != "<skip>")
hashed_token= mrf::SuperFastHash(token.c_str(),token.size());
#ifdef DEBUG
//debug
//std::cout << "hashed token: " << hashed_token << std::endl;
//debug
#endif
h += hashed_token * mrf::_hctable[i]; // beware...
}
return h;
}
uint32_t mrf::mrf_hash(const std::vector<std::string> &tokens)
{
uint32_t h = 0;
size_t csize = std::min(10,(int)tokens.size());
for (size_t i=0;i<csize;i++)
{
std::string token = tokens.at(i);
uint32_t hashed_token= mrf::SuperFastHash(token.c_str(),token.size());
#ifdef DEBUG
//debug
//std::cout << "hashed token: " << hashed_token << std::endl;
//debug
#endif
h += hashed_token * mrf::_hctable[i]; // beware...
}
return h;
}
// Paul Hsieh's super fast hash function.
#include "stdint.h"
#undef get16bits
#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \
|| defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__)
#define get16bits(d) (*((const uint16_t *) (d)))
#endif
#if !defined (get16bits)
#define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)\
+(uint32_t)(((const uint8_t *)(d))[0]) )
#endif
uint32_t mrf::SuperFastHash (const char * data, uint32_t len) {
uint32_t hash = len, tmp;
int rem;
if (len <= 0 || data == NULL) return 0;
rem = len & 3;
len >>= 2;
/* Main loop */
for (;len > 0; len--) {
hash += get16bits (data);
tmp = (get16bits (data+2) << 11) ^ hash;
hash = (hash << 16) ^ tmp;
data += 2*sizeof (uint16_t);
hash += hash >> 11;
}
/* Handle end cases */
switch (rem) {
case 3: hash += get16bits (data);
hash ^= hash << 16;
hash ^= data[sizeof (uint16_t)] << 18;
hash += hash >> 11;
break;
case 2: hash += get16bits (data);
hash ^= hash << 11;
hash += hash >> 17;
break;
case 1: hash += *data;
hash ^= hash << 10;
hash += hash >> 1;
}
/* Force "avalanching" of final 127 bits */
hash ^= hash << 3;
hash += hash >> 5;
hash ^= hash << 4;
hash += hash >> 17;
hash ^= hash << 25;
hash += hash >> 6;
return hash;
}
int mrf::hash_compare(const uint32_t &a, const uint32_t &b)
{
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
// for convenience only.
double mrf::radiance(const std::string &query1,
const std::string &query2)
{
return mrf::radiance(query1,query2,0,mrf::_window_length_default);
}
double mrf::radiance(const std::string &query1,
const std::string &query2,
const int &min_radius,
const int &max_radius)
{
// mrf call.
std::vector<uint32_t> features1;
mrf::mrf_features(query1,features1,min_radius,max_radius);
std::vector<uint32_t> features2;
mrf::mrf_features(query2,features2,min_radius,max_radius);
return mrf::radiance(features1,features2);
}
double mrf::radiance(const std::vector<uint32_t> &sorted_features1,
const std::vector<uint32_t> &sorted_features2)
{
// distance computation.
int common_features = 0;
int nsf1 = sorted_features1.size();
int nsf2 = sorted_features2.size();
int cfeat1 = 0; // feature counter.
int cfeat2 = 0;
while(cfeat1<nsf1)
{
int cmp = mrf::hash_compare(sorted_features1.at(cfeat1),
sorted_features2.at(cfeat2));
if (cmp > 0)
{
++cfeat2; // keep on moving in set 2.
if (cfeat2 >= nsf2)
break;
}
else if (cmp < 0)
{
++cfeat1;
}
else
{
common_features++;
++cfeat1;
++cfeat2;
if (cfeat2 >= nsf2)
break;
}
}
double found_only_in_set1 = nsf1 - common_features;
double found_only_in_set2 = nsf2 - common_features;
double distance = found_only_in_set1 + found_only_in_set2;
#ifdef DEBUG
//debug
std::cout << "nsf1: " << nsf1 << " -- nsf2: " << nsf2 << std::endl;
std::cout << "common features: " << common_features << std::endl;
std::cout << "found only in set1: " << found_only_in_set1 << std::endl;
std::cout << "found only in set2: " << found_only_in_set2 << std::endl;
//debug
#endif
// radiance.
double radiance = (common_features * common_features) / (distance + mrf::_epsilon);
return radiance;
}
} /* end of namespace. */
<commit_msg>cleanup<commit_after>/**
* The Locality Sensitive Hashing (LSH) library is part of the SEEKS project and
* does provide several locality sensitive hashing schemes for pattern matching over
* continuous and discrete spaces.
* Copyright (C) 2009 Emmanuel Benazera, juban@free.fr
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "mrf.h"
#include <algorithm>
#include <iostream>
//#define DEBUG
namespace lsh
{
/*-- str_chain --*/
str_chain::str_chain(const std::string &str,
const int &radius)
:_radius(radius),_skip(false)
{
add_token(str);
if (str == "<skip>")
_skip = true;
}
str_chain::str_chain(const str_chain &sc)
:_chain(sc.get_chain()),_radius(sc.get_radius()),
_skip(sc.has_skip())
{
}
void str_chain::add_token(const std::string &str)
{
_chain.push_back(str);
}
str_chain str_chain::rank_alpha() const
{
str_chain cchain = *this;
#ifdef DEBUG
/* std::cout << "cchain: ";
cchain.print(std::cout); */
#endif
std::sort(cchain.get_chain_noconst().begin(),cchain.get_chain_noconst().end());
#ifdef DEBUG
/* std::cout << "sorted chain: ";
cchain.print(std::cout); */
#endif
return cchain;
}
std::ostream& str_chain::print(std::ostream &output) const
{
for (size_t i=0;i<_chain.size();i++)
output << _chain.at(i) << " ";
output << std::endl;
return output;
}
/*-- mrf --*/
std::string mrf::_default_delims = " ";
uint32_t mrf::_skip_token = 0xDEADBEEF;
uint32_t mrf::_window_length_default = 8;
uint32_t mrf::_window_length = 8;
uint32_t mrf::_hctable[] = { 1, 3, 5, 11, 23, 47, 97, 197, 397, 797 };
double mrf::_epsilon = 1e-6; // infinitesimal.
void mrf::tokenize(const std::string &str,
std::vector<std::string> &tokens,
const std::string &delim)
{
// Skip delimiters at beginning.
std::string::size_type lastPos = str.find_first_not_of(delim, 0);
// Find first "non-delimiter".
std::string::size_type pos = str.find_first_of(delim, lastPos);
while (std::string::npos != pos || std::string::npos != lastPos)
{
// Found a token, add it to the vector.
tokens.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = str.find_first_not_of(delim, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delim, lastPos);
}
}
uint32_t mrf::mrf_single_feature(const std::string &str)
{
std::vector<std::string> tokens;
mrf::tokenize(str,tokens,mrf::_default_delims);
return mrf::mrf_hash(tokens);
}
void mrf::mrf_features(const std::string &str,
std::vector<uint32_t> &features,
const int &min_radius,
const int &max_radius)
{
std::vector<std::string> tokens;
mrf::tokenize(str,tokens,mrf::_default_delims);
int gen_radius = 0;
while(!tokens.empty())
{
mrf::mrf_build(tokens,features,
min_radius,max_radius,
gen_radius);
tokens.erase(tokens.begin());
++gen_radius;
}
std::sort(features.begin(),features.end());
}
void mrf::mrf_build(const std::vector<std::string> &tokens,
std::vector<uint32_t> &features,
const int &min_radius,
const int &max_radius,
const int &gen_radius)
{
// scale the field's window size.
if (tokens.size() < mrf::_window_length_default)
mrf::_window_length = tokens.size();
int tok = 0;
std::queue<str_chain> chains;
mrf::mrf_build(tokens,tok,chains,features,
min_radius,max_radius,gen_radius);
// reset the field's window size.
mrf::_window_length = mrf::_window_length_default;
}
void mrf::mrf_build(const std::vector<std::string> &tokens,
int &tok,
std::queue<str_chain> &chains,
std::vector<uint32_t> &features,
const int &min_radius, const int &max_radius,
const int &gen_radius)
{
if (chains.empty())
{
int radius_chain = gen_radius+tokens.size()-1;
str_chain chain(tokens.at(tok),radius_chain);
if (radius_chain >= min_radius
&& radius_chain <= max_radius)
{
//hash chain and add it to features set.
uint32_t h = mrf::mrf_hash(chain);
features.push_back(h);
#ifdef DEBUG
//debug
std::cout << tokens.at(tok) << std::endl;
std::cout << std::hex << h << std::endl;
std::cout << std::endl;
//debug
#endif
}
chains.push(chain);
mrf::mrf_build(tokens,tok,chains,features,
min_radius,max_radius,gen_radius);
}
else
{
++tok;
std::queue<str_chain> nchains;
while(!chains.empty())
{
str_chain chain = chains.front();
chains.pop();
if (chain.size() < mrf::_window_length)
{
// first generated chain: add a token.
str_chain chain1(chain);
chain1.add_token(tokens.at(tok));
chain1.decr_radius();
if (chain1.get_radius() >= min_radius
&& chain1.get_radius() <= max_radius)
{
// hash it and add it to features.
uint32_t h = mrf::mrf_hash(chain1);
features.push_back(h);
#ifdef DEBUG
//debug
chain1.print(std::cout);
std::cout << std::hex << h << std::endl;
std::cout << std::endl;
//debug
#endif
}
// second generated chain: add a 'skip' token.
str_chain chain2 = chain;
chain2.add_token("<skip>");
chain2.set_skip();
nchains.push(chain1);
nchains.push(chain2);
}
}
if (!nchains.empty())
mrf::mrf_build(tokens,tok,nchains,features,
min_radius,max_radius,gen_radius);
}
}
uint32_t mrf::mrf_hash(const str_chain &chain)
{
// rank chains which do not contain any skipped token (i.e. no
// order preservation).
str_chain cchain(chain);
if (!chain.has_skip())
cchain = chain.rank_alpha();
uint32_t h = 0;
size_t csize = std::min(10,(int)cchain.size()); // beware: hctable may be too small...
for (size_t i=0;i<csize;i++)
{
std::string token = cchain.at(i);
uint32_t hashed_token = mrf::_skip_token;
if (token != "<skip>")
hashed_token= mrf::SuperFastHash(token.c_str(),token.size());
#ifdef DEBUG
//debug
//std::cout << "hashed token: " << hashed_token << std::endl;
//debug
#endif
h += hashed_token * mrf::_hctable[i]; // beware...
}
return h;
}
uint32_t mrf::mrf_hash(const std::vector<std::string> &tokens)
{
uint32_t h = 0;
size_t csize = std::min(10,(int)tokens.size());
for (size_t i=0;i<csize;i++)
{
std::string token = tokens.at(i);
uint32_t hashed_token= mrf::SuperFastHash(token.c_str(),token.size());
#ifdef DEBUG
//debug
//std::cout << "hashed token: " << hashed_token << std::endl;
//debug
#endif
h += hashed_token * mrf::_hctable[i]; // beware...
}
return h;
}
// Paul Hsieh's super fast hash function.
#include "stdint.h"
#undef get16bits
#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \
|| defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__)
#define get16bits(d) (*((const uint16_t *) (d)))
#endif
#if !defined (get16bits)
#define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)\
+(uint32_t)(((const uint8_t *)(d))[0]) )
#endif
uint32_t mrf::SuperFastHash (const char * data, uint32_t len) {
uint32_t hash = len, tmp;
int rem;
if (len <= 0 || data == NULL) return 0;
rem = len & 3;
len >>= 2;
/* Main loop */
for (;len > 0; len--) {
hash += get16bits (data);
tmp = (get16bits (data+2) << 11) ^ hash;
hash = (hash << 16) ^ tmp;
data += 2*sizeof (uint16_t);
hash += hash >> 11;
}
/* Handle end cases */
switch (rem) {
case 3: hash += get16bits (data);
hash ^= hash << 16;
hash ^= data[sizeof (uint16_t)] << 18;
hash += hash >> 11;
break;
case 2: hash += get16bits (data);
hash ^= hash << 11;
hash += hash >> 17;
break;
case 1: hash += *data;
hash ^= hash << 10;
hash += hash >> 1;
}
/* Force "avalanching" of final 127 bits */
hash ^= hash << 3;
hash += hash >> 5;
hash ^= hash << 4;
hash += hash >> 17;
hash ^= hash << 25;
hash += hash >> 6;
return hash;
}
int mrf::hash_compare(const uint32_t &a, const uint32_t &b)
{
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
double mrf::radiance(const std::string &query1,
const std::string &query2)
{
return mrf::radiance(query1,query2,0,mrf::_window_length_default);
}
double mrf::radiance(const std::string &query1,
const std::string &query2,
const int &min_radius,
const int &max_radius)
{
// mrf call.
std::vector<uint32_t> features1;
mrf::mrf_features(query1,features1,min_radius,max_radius);
std::vector<uint32_t> features2;
mrf::mrf_features(query2,features2,min_radius,max_radius);
return mrf::radiance(features1,features2);
}
double mrf::radiance(const std::vector<uint32_t> &sorted_features1,
const std::vector<uint32_t> &sorted_features2)
{
// distance computation.
int common_features = 0;
int nsf1 = sorted_features1.size();
int nsf2 = sorted_features2.size();
int cfeat1 = 0; // feature counter.
int cfeat2 = 0;
while(cfeat1<nsf1)
{
int cmp = mrf::hash_compare(sorted_features1.at(cfeat1),
sorted_features2.at(cfeat2));
if (cmp > 0)
{
++cfeat2; // keep on moving in set 2.
if (cfeat2 >= nsf2)
break;
}
else if (cmp < 0)
{
++cfeat1;
}
else
{
common_features++;
++cfeat1;
++cfeat2;
if (cfeat2 >= nsf2)
break;
}
}
double found_only_in_set1 = nsf1 - common_features;
double found_only_in_set2 = nsf2 - common_features;
double distance = found_only_in_set1 + found_only_in_set2;
#ifdef DEBUG
//debug
std::cout << "nsf1: " << nsf1 << " -- nsf2: " << nsf2 << std::endl;
std::cout << "common features: " << common_features << std::endl;
std::cout << "found only in set1: " << found_only_in_set1 << std::endl;
std::cout << "found only in set2: " << found_only_in_set2 << std::endl;
//debug
#endif
// radiance.
double radiance = (common_features * common_features) / (distance + mrf::_epsilon);
return radiance;
}
} /* end of namespace. */
<|endoftext|> |
<commit_before>/* Base class for envelope follower instruments
John Gibson <johgibso at indiana dot edu>, 1/5/03. Rev for v4, 7/12/04
*/
//#define DEBUG
#include "FOLLOWER_BASE.h"
/* --------------------------------------------------------- FOLLOWER_BASE -- */
FOLLOWER_BASE :: FOLLOWER_BASE()
{
branch = 0;
in = NULL;
amp_table = NULL;
}
/* -------------------------------------------------------- ~FOLLOWER_BASE -- */
FOLLOWER_BASE :: ~FOLLOWER_BASE()
{
delete [] in;
delete amp_table;
delete gauge;
delete smoother;
}
/* ------------------------------------------------------------------ init -- */
int FOLLOWER_BASE :: init(double p[], int n_args)
{
nargs = n_args;
float outskip = p[0];
float inskip = p[1];
dur = p[2];
// apply conversion to normal range [-1, 1] for modulator input now
modamp = p[4] * (1.0 / 32768.0);
int window_len = (int) p[5];
if (window_len < 1)
return die(instname(), "Window length must be at least 1 sample.");
smoothness = p[6];
if (smoothness < 0.0 || smoothness > 1.0)
return die(instname(), "Smoothness must be between 0 and 1.");
smoothness = -1.0; // force first update
if (pre_init(p, n_args) != 0)
return DONT_SCHEDULE;
if (rtsetoutput(outskip, dur, this) == -1)
return DONT_SCHEDULE;
if (outputChannels() > 2)
return die(instname(), "Output must be either mono or stereo.");
if (rtsetinput(inskip, this) == -1)
return DONT_SCHEDULE;
if (inputChannels() != 2)
return die(instname(),
"Must use 2 input channels: 'left' for carrier; 'right' for modulator.");
double *function = floc(1);
if (function) {
int len = fsize(1);
amp_table = new TableL(SR, dur, function, len);
}
gauge = new RMS(SR);
gauge->setWindowSize(window_len);
smoother = new OnePole(SR);
skip = (int) (SR / (float) resetval);
if (post_init(p, n_args) != 0)
return DONT_SCHEDULE;
return nSamps();
}
/* ------------------------------------------------------------- configure -- */
int FOLLOWER_BASE :: configure()
{
in = new float [RTBUFSAMPS * inputChannels()];
return in ? 0 : -1;
}
/* ------------------------------------------------------- update_smoother -- */
inline void FOLLOWER_BASE :: update_smoother(double p[])
{
if (p[6] != smoothness) {
smoothness = p[6];
if (smoothness < 0.0)
smoothness = 0.0;
else if (smoothness > 1.0)
smoothness = 1.0;
// Filter pole coefficient is non-linear -- very sensitive near 1,
// and not very sensitive below .5, so we use a log to reduce this
// nonlinearity for the user. Constrain to range [1, 100], then
// take log10.
float smooth = (float) log10((double) ((smoothness * 99) + 1)) * 0.5f;
if (smooth > 0.9999) // 1.0 results in all zeros for power signal
smooth = 0.9999;
smoother->setPole(smooth);
}
}
/* ------------------------------------------------------------------- run -- */
int FOLLOWER_BASE :: run()
{
const int samps = framesToRun() * inputChannels();
rtgetin(in, this, samps);
for (int i = 0; i < samps; i += inputChannels()) {
if (--branch <= 0) {
double p[nargs];
update(p, nargs);
caramp = p[3];
if (amp_table)
caramp *= amp_table->tick(currentFrame(), 1.0);
if (p[4] != modamp) {
// apply conversion to normal range [-1, 1]
modamp = p[4] * (1.0 / 32768.0);
}
update_smoother(p);
update_params(p);
branch = skip;
}
float carsig = in[i] * caramp;
float modsig = in[i + 1] * modamp;
float power = gauge->tick(modsig);
power = smoother->tick(power);
float outsig = process_sample(carsig, power);
float out[2];
if (outputChannels() == 2) {
out[0] = outsig * pctleft;
out[1] = outsig * (1.0 - pctleft);
}
rtaddout(out);
increment();
}
return framesToRun();
}
<commit_msg>Fix for silent mono output; optimization for changing modamp values; minor debug print addition.<commit_after>/* Base class for envelope follower instruments
John Gibson <johgibso at indiana dot edu>, 1/5/03. Rev for v4, 7/12/04
*/
//#define DEBUG
#include "FOLLOWER_BASE.h"
#include <float.h>
/* --------------------------------------------------------- FOLLOWER_BASE -- */
FOLLOWER_BASE :: FOLLOWER_BASE()
: branch(0), in(NULL), rawmodamp(-FLT_MAX), amp_table(NULL)
{
}
/* -------------------------------------------------------- ~FOLLOWER_BASE -- */
FOLLOWER_BASE :: ~FOLLOWER_BASE()
{
delete [] in;
delete amp_table;
delete gauge;
delete smoother;
}
/* ------------------------------------------------------------------ init -- */
int FOLLOWER_BASE :: init(double p[], int n_args)
{
nargs = n_args;
float outskip = p[0];
float inskip = p[1];
dur = p[2];
int window_len = (int) p[5];
if (window_len < 1)
return die(instname(), "Window length must be at least 1 sample.");
smoothness = p[6];
if (smoothness < 0.0 || smoothness > 1.0)
return die(instname(), "Smoothness must be between 0 and 1.");
smoothness = -1.0; // force first update
if (pre_init(p, n_args) != 0)
return DONT_SCHEDULE;
if (rtsetoutput(outskip, dur, this) == -1)
return DONT_SCHEDULE;
if (outputChannels() > 2)
return die(instname(), "Output must be either mono or stereo.");
if (rtsetinput(inskip, this) == -1)
return DONT_SCHEDULE;
if (inputChannels() != 2)
return die(instname(),
"Must use 2 input channels: 'left' for carrier; 'right' for modulator.");
double *function = floc(1);
if (function) {
int len = fsize(1);
amp_table = new TableL(SR, dur, function, len);
}
gauge = new RMS(SR);
gauge->setWindowSize(window_len);
smoother = new OnePole(SR);
if (post_init(p, n_args) != 0)
return DONT_SCHEDULE;
return nSamps();
}
/* ------------------------------------------------------------- configure -- */
int FOLLOWER_BASE :: configure()
{
in = new float [RTBUFSAMPS * inputChannels()];
return in ? 0 : -1;
}
/* ------------------------------------------------------- update_smoother -- */
inline void FOLLOWER_BASE :: update_smoother(double p[])
{
if (p[6] != smoothness) {
smoothness = p[6];
if (smoothness < 0.0)
smoothness = 0.0;
else if (smoothness > 1.0)
smoothness = 1.0;
// Filter pole coefficient is non-linear -- very sensitive near 1,
// and not very sensitive below .5, so we use a log to reduce this
// nonlinearity for the user. Constrain to range [1, 100], then
// take log10.
float smooth = (float) log10((double) ((smoothness * 99) + 1)) * 0.5f;
if (smooth > 0.9999) // 1.0 results in all zeros for power signal
smooth = 0.9999;
smoother->setPole(smooth);
}
}
/* ------------------------------------------------------------------- run -- */
int FOLLOWER_BASE :: run()
{
const int samps = framesToRun() * inputChannels();
rtgetin(in, this, samps);
for (int i = 0; i < samps; i += inputChannels()) {
if (--branch <= 0) {
double p[nargs];
update(p, nargs);
caramp = p[3];
if (amp_table)
caramp *= amp_table->tick(currentFrame(), 1.0);
if (p[4] != rawmodamp) {
rawmodamp = p[4];
// apply conversion to normal range [-1, 1]
modamp = rawmodamp * (1.0 / 32768.0);
}
update_smoother(p);
update_params(p);
branch = getSkip();
}
float carsig = in[i] * caramp;
float modsig = in[i + 1] * modamp;
float power = gauge->tick(modsig);
power = smoother->tick(power);
float outsig = process_sample(carsig, power);
float out[2];
if (outputChannels() == 2) {
out[0] = outsig * pctleft;
out[1] = outsig * (1.0 - pctleft);
}
else
out[0] = outsig;
rtaddout(out);
increment();
}
return framesToRun();
}
<|endoftext|> |
<commit_before>/**************************************************************************
*
* Copyright 2010-2011 VMware, 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 <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <pthread.h>
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif
#include "os.hpp"
namespace OS {
static pthread_mutex_t
mutex = PTHREAD_MUTEX_INITIALIZER;
void
AcquireMutex(void)
{
pthread_mutex_lock(&mutex);
}
void
ReleaseMutex(void)
{
pthread_mutex_unlock(&mutex);
}
bool
GetProcessName(char *str, size_t size)
{
char szProcessPath[PATH_MAX + 1];
char *lpProcessName;
// http://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe
#ifdef __APPLE__
uint32_t len = sizeof szProcessPath;
if (_NSGetExecutablePath(szProcessPath, &len) != 0) {
*str = 0;
return false;
}
#else
ssize_t len;
len = readlink("/proc/self/exe", szProcessPath, sizeof(szProcessPath) - 1);
if (len == -1) {
// /proc/self/exe is not available on setuid processes, so fallback to
// /proc/self/cmdline.
int fd = open("/proc/self/cmdline", O_RDONLY);
if (fd >= 0) {
len = read(fd, szProcessPath, sizeof(szProcessPath) - 1);
close(fd);
}
}
if (len <= 0) {
snprintf(str, size, "%i", (int)getpid());
return true;
}
#endif
szProcessPath[len] = 0;
lpProcessName = strrchr(szProcessPath, '/');
lpProcessName = lpProcessName ? lpProcessName + 1 : szProcessPath;
strncpy(str, lpProcessName, size);
if (size)
str[size - 1] = 0;
return true;
}
bool
GetCurrentDir(char *str, size_t size)
{
char *ret;
ret = getcwd(str, size);
str[size - 1] = 0;
return ret ? true : false;
}
void
DebugMessage(const char *format, ...)
{
va_list ap;
va_start(ap, format);
fflush(stdout);
vfprintf(stderr, format, ap);
va_end(ap);
}
long long GetTime(void)
{
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_usec + tv.tv_sec*1000000LL;
}
void
Abort(void)
{
exit(0);
}
} /* namespace OS */
<commit_msg>Add missing headers.<commit_after>/**************************************************************************
*
* Copyright 2010-2011 VMware, 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 <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <pthread.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif
#include "os.hpp"
namespace OS {
static pthread_mutex_t
mutex = PTHREAD_MUTEX_INITIALIZER;
void
AcquireMutex(void)
{
pthread_mutex_lock(&mutex);
}
void
ReleaseMutex(void)
{
pthread_mutex_unlock(&mutex);
}
bool
GetProcessName(char *str, size_t size)
{
char szProcessPath[PATH_MAX + 1];
char *lpProcessName;
// http://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe
#ifdef __APPLE__
uint32_t len = sizeof szProcessPath;
if (_NSGetExecutablePath(szProcessPath, &len) != 0) {
*str = 0;
return false;
}
#else
ssize_t len;
len = readlink("/proc/self/exe", szProcessPath, sizeof(szProcessPath) - 1);
if (len == -1) {
// /proc/self/exe is not available on setuid processes, so fallback to
// /proc/self/cmdline.
int fd = open("/proc/self/cmdline", O_RDONLY);
if (fd >= 0) {
len = read(fd, szProcessPath, sizeof(szProcessPath) - 1);
close(fd);
}
}
if (len <= 0) {
snprintf(str, size, "%i", (int)getpid());
return true;
}
#endif
szProcessPath[len] = 0;
lpProcessName = strrchr(szProcessPath, '/');
lpProcessName = lpProcessName ? lpProcessName + 1 : szProcessPath;
strncpy(str, lpProcessName, size);
if (size)
str[size - 1] = 0;
return true;
}
bool
GetCurrentDir(char *str, size_t size)
{
char *ret;
ret = getcwd(str, size);
str[size - 1] = 0;
return ret ? true : false;
}
void
DebugMessage(const char *format, ...)
{
va_list ap;
va_start(ap, format);
fflush(stdout);
vfprintf(stderr, format, ap);
va_end(ap);
}
long long GetTime(void)
{
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_usec + tv.tv_sec*1000000LL;
}
void
Abort(void)
{
exit(0);
}
} /* namespace OS */
<|endoftext|> |
<commit_before>#include "miomain.h"
#include "config/configuration.h"
#include "devicedetection.h"
#include "sysex/commands.h"
#include "sysex/midi.h"
#include "ui_miomain.h"
#include "widgets/centralwidget.h"
#include "widgets/deviceinfowidget.h"
#include "widgets/multiinfowidget.h"
#include "widgets/portswidget.h"
#include <QCloseEvent>
#include <QDesktopWidget>
#include <QSignalMapper>
#include <QStyle>
#include <QTimer>
#include <QtDebug>
MioMain::MioMain(QWidget *parent) : QMainWindow(parent), ui(new Ui::MioMain) {
ui->setupUi(this);
setDockOptions(QMainWindow::AnimatedDocks | QMainWindow::ForceTabbedDocks |
QMainWindow::VerticalTabs);
readSettings();
if (readDevicesFromSettings())
openDefaultDevice();
else
QTimer::singleShot(100, this, SLOT(openDetectionWindow()));
}
MioMain::~MioMain() {
if (deviceDetectionWindow)
delete deviceDetectionWindow;
delete ui;
}
void MioMain::openDefaultDevice() {
writeDevicesToSettings();
long defaultDeviceSN = Configuration::getInstance().getDefaultDevice();
Device *d = Configuration::getInstance().getDevices()->at(defaultDeviceSN);
addDevicesToSelectionMenu(defaultDeviceSN);
openDeviceGUI(d);
}
void MioMain::addDevicesToSelectionMenu(long defaultDeviceSN) {
QSignalMapper *signalMapper = new QSignalMapper();
Devices *devices = Configuration::getInstance().getDevices();
QActionGroup *devicesGroup = new QActionGroup(this);
devicesGroup->setExclusive(true);
for (Devices::iterator it = devices->begin(); it != devices->end(); ++it) {
Device *d = it->second;
QAction *a =
ui->menuSelect->addAction(QString::fromStdString(d->getDeviceName()));
a->setCheckable(true);
devicesGroup->addAction(a);
connect(a, SIGNAL(triggered()), signalMapper, SLOT(map()));
signalMapper->setMapping(a, new DeviceMenuMapper(d));
if (it->first == defaultDeviceSN)
a->setChecked(true);
}
connect(signalMapper, SIGNAL(mapped(QObject *)), this,
SLOT(openDeviceGUI(QObject *)));
}
void MioMain::openDeviceGUI(QObject *o) {
DeviceMenuMapper *m = (DeviceMenuMapper *)o;
#ifdef __MIO_DEBUG__
std::cout << "open device GUI: " << m->device->getDeviceName() << std::endl;
#endif //__MIO_DEBUG__
openDeviceGUI(m->device);
}
void MioMain::addDock(QDockWidget *dockWidget, Qt::DockWidgetArea area) {
if (MultiInfoWidget *miw = dynamic_cast<MultiInfoWidget *>(dockWidget)) {
miw->createInfoSections();
}
switch (area) {
case Qt::NoDockWidgetArea:
setCentralWidget(dockWidget);
break;
case Qt::LeftDockWidgetArea:
this->addDockWidget(Qt::LeftDockWidgetArea, dockWidget);
break;
default:
break;
}
std::vector<QDockWidget *> v = dockWidgetAreas[area];
if (v.size() > 0) {
tabifyDockWidget(v[v.size() - 1], dockWidget);
}
dockWidgetAreas[area].push_back(dockWidget);
}
void MioMain::clearDocWidgets() {
for (std::map<Qt::DockWidgetArea, std::vector<QDockWidget *>>::iterator it =
dockWidgetAreas.begin();
it != dockWidgetAreas.end(); ++it) {
std::vector<QDockWidget *> v = it->second;
for (unsigned int j = 0; j < v.size(); j++) {
QWidget *w = v.at(j);
delete w;
}
v.clear();
}
dockWidgetAreas.clear();
}
void MioMain::replacePanel(QWidget *w) {
CentralWidget *cw = (CentralWidget *)centralWidget();
cw->replacePanel(w);
}
void MioMain::openDeviceGUI(Device *d) {
clearDocWidgets();
Commands *c = d->getCommands();
if (c == 0) {
// TODO throw error
exit(2);
}
setWindowTitle(this->title + QString(": ") +
QString::fromStdString(d->getDeviceName()));
CentralWidget *centralWidget = new CentralWidget(this, d);
this->addDock(centralWidget);
DeviceInfoWidget *deviceInfoWidget =
new DeviceInfoWidget(this, d, d->getDeviceInfo());
this->addDock(deviceInfoWidget, Qt::LeftDockWidgetArea);
PortsWidget *portsWidget = new PortsWidget(this, d);
this->addDock(portsWidget, Qt::LeftDockWidgetArea);
if (c->isCommandSupported(SysExMessage::GET_ETHERNET_PORT_INFO)) {
std::cout << "EthernetPortsAvailable";
}
QSettings *settings = Configuration::getInstance().getSettings();
settings->beginGroup("MainWindow");
restoreGeometry(settings->value("geometry").toByteArray());
settings->endGroup();
settings->beginGroup("Docks");
// restoreState(settings->value("DockWindows").toByteArray());
settings->endGroup();
}
void MioMain::closeEvent(QCloseEvent *event) {
writeSettings();
event->accept();
}
void MioMain::openDetectionWindow() {
deviceDetectionWindow = new DeviceDetection(this);
deviceDetectionWindow->exec();
}
void MioMain::writeSettings() {
QSettings *settings = Configuration::getInstance().getSettings();
settings->beginGroup("MainWindow");
settings->setValue("geometry", saveGeometry());
settings->setValue("size", size());
settings->setValue("pos", pos());
settings->endGroup();
settings->beginGroup("Docks");
settings->setValue("DockWindows", saveState());
settings->endGroup();
}
void MioMain::writeDevicesToSettings() {
QSettings *settings = Configuration::getInstance().getSettings();
Devices *devices = Configuration::getInstance().getDevices();
settings->beginWriteArray("Devices");
int i = 0;
for (Devices::iterator it = devices->begin(); it != devices->end(); ++it) {
settings->setArrayIndex(i);
Device *d = it->second;
settings->setValue("Device Name",
QString::fromStdString(d->getDeviceName()));
settings->setValue("Serial Number",
(qlonglong)(d->getSerialNumber()->getLongValue()));
settings->setValue("Input Port", d->getInPortNumer());
settings->setValue("Output Port", d->getOutPortNumer());
settings->setValue("Product Id",
(qlonglong)d->getProductId()->getLongValue());
#ifdef __MIO_SIMULATE__
if (d->getSimulate()) {
settings->setValue("Simulate", true);
settings->setValue("Model Name",
QString::fromStdString(d->getModelName()));
}
#endif
++i;
}
settings->endArray();
}
void MioMain::connectSlots() {
// connect(this->)
}
void MioMain::readSettings() {
this->title = windowTitle();
QSettings *settings = Configuration::getInstance().getSettings();
settings->beginGroup("MainWindow");
resize(settings->value("size", QSize(400, 400)).toSize());
move(settings->value("pos", QPoint(200, 200)).toPoint());
settings->endGroup();
}
bool MioMain::readDevicesFromSettings() {
Devices *devices = Configuration::getInstance().getDevices();
devices->clear();
QSettings *settings = Configuration::getInstance().getSettings();
int size = settings->beginReadArray("Devices");
if (size == 0)
return false;
for (int i = 0; i < size; ++i) {
settings->setArrayIndex(i);
int productId = settings->value("Product Id").toInt();
long serialNumber =
(qlonglong)settings->value("Serial Number").toLongLong();
int inputPort = (qlonglong)settings->value("Input Port").toInt();
int outputPort = (qlonglong)settings->value("Output Port").toInt();
#ifdef __MIO_SIMULATE__
Device *device = 0;
if (settings->value("Simulate").toBool()) {
std::string modelName =
settings->value("Model Name").toString().toStdString();
std::string deviceName =
settings->value("Device Name").toString().toStdString();
device = new Device(inputPort, outputPort, serialNumber, productId,
modelName, deviceName);
} else {
device = new Device(inputPort, outputPort, serialNumber, productId);
}
#else
Device *device = new Device(inputPort, outputPort, serialNumber, productId);
#endif
if (device->queryDeviceInfo())
devices->insert(std::pair<long, Device *>(serialNumber, device));
}
settings->endArray();
if (devices->size() == 0)
return false;
return true;
}
void MioMain::on_actionQuit_triggered() { close(); }
<commit_msg>always select deviceInfoWidget when opening or switching a device.<commit_after>#include "miomain.h"
#include "config/configuration.h"
#include "devicedetection.h"
#include "sysex/commands.h"
#include "sysex/midi.h"
#include "ui_miomain.h"
#include "widgets/centralwidget.h"
#include "widgets/deviceinfowidget.h"
#include "widgets/multiinfowidget.h"
#include "widgets/portswidget.h"
#include <QCloseEvent>
#include <QDesktopWidget>
#include <QSignalMapper>
#include <QStyle>
#include <QTimer>
#include <QtDebug>
MioMain::MioMain(QWidget *parent) : QMainWindow(parent), ui(new Ui::MioMain) {
ui->setupUi(this);
setDockOptions(QMainWindow::AnimatedDocks | QMainWindow::ForceTabbedDocks |
QMainWindow::VerticalTabs);
readSettings();
if (readDevicesFromSettings())
openDefaultDevice();
else
QTimer::singleShot(100, this, SLOT(openDetectionWindow()));
}
MioMain::~MioMain() {
if (deviceDetectionWindow)
delete deviceDetectionWindow;
delete ui;
}
void MioMain::openDefaultDevice() {
writeDevicesToSettings();
long defaultDeviceSN = Configuration::getInstance().getDefaultDevice();
Device *d = Configuration::getInstance().getDevices()->at(defaultDeviceSN);
addDevicesToSelectionMenu(defaultDeviceSN);
openDeviceGUI(d);
}
void MioMain::addDevicesToSelectionMenu(long defaultDeviceSN) {
QSignalMapper *signalMapper = new QSignalMapper();
Devices *devices = Configuration::getInstance().getDevices();
QActionGroup *devicesGroup = new QActionGroup(this);
devicesGroup->setExclusive(true);
for (Devices::iterator it = devices->begin(); it != devices->end(); ++it) {
Device *d = it->second;
QAction *a =
ui->menuSelect->addAction(QString::fromStdString(d->getDeviceName()));
a->setCheckable(true);
devicesGroup->addAction(a);
connect(a, SIGNAL(triggered()), signalMapper, SLOT(map()));
signalMapper->setMapping(a, new DeviceMenuMapper(d));
if (it->first == defaultDeviceSN)
a->setChecked(true);
}
connect(signalMapper, SIGNAL(mapped(QObject *)), this,
SLOT(openDeviceGUI(QObject *)));
}
void MioMain::openDeviceGUI(QObject *o) {
DeviceMenuMapper *m = (DeviceMenuMapper *)o;
#ifdef __MIO_DEBUG__
std::cout << "open device GUI: " << m->device->getDeviceName() << std::endl;
#endif //__MIO_DEBUG__
openDeviceGUI(m->device);
}
void MioMain::addDock(QDockWidget *dockWidget, Qt::DockWidgetArea area) {
if (MultiInfoWidget *miw = dynamic_cast<MultiInfoWidget *>(dockWidget)) {
miw->createInfoSections();
}
switch (area) {
case Qt::NoDockWidgetArea:
setCentralWidget(dockWidget);
break;
case Qt::LeftDockWidgetArea:
this->addDockWidget(Qt::LeftDockWidgetArea, dockWidget);
break;
default:
break;
}
std::vector<QDockWidget *> v = dockWidgetAreas[area];
if (v.size() > 0) {
tabifyDockWidget(v[v.size() - 1], dockWidget);
}
dockWidgetAreas[area].push_back(dockWidget);
}
void MioMain::clearDocWidgets() {
for (std::map<Qt::DockWidgetArea, std::vector<QDockWidget *>>::iterator it =
dockWidgetAreas.begin();
it != dockWidgetAreas.end(); ++it) {
std::vector<QDockWidget *> v = it->second;
for (unsigned int j = 0; j < v.size(); j++) {
QWidget *w = v.at(j);
delete w;
}
v.clear();
}
dockWidgetAreas.clear();
}
void MioMain::replacePanel(QWidget *w) {
CentralWidget *cw = (CentralWidget *)centralWidget();
cw->replacePanel(w);
}
void MioMain::openDeviceGUI(Device *d) {
clearDocWidgets();
Commands *c = d->getCommands();
if (c == 0) {
// TODO throw error
exit(2);
}
setWindowTitle(this->title + QString(": ") +
QString::fromStdString(d->getDeviceName()));
CentralWidget *centralWidget = new CentralWidget(this, d);
this->addDock(centralWidget);
DeviceInfoWidget *deviceInfoWidget =
new DeviceInfoWidget(this, d, d->getDeviceInfo());
this->addDock(deviceInfoWidget, Qt::LeftDockWidgetArea);
PortsWidget *portsWidget = new PortsWidget(this, d);
this->addDock(portsWidget, Qt::LeftDockWidgetArea);
if (c->isCommandSupported(SysExMessage::GET_ETHERNET_PORT_INFO)) {
std::cout << "EthernetPortsAvailable";
}
QSettings *settings = Configuration::getInstance().getSettings();
settings->beginGroup("MainWindow");
restoreGeometry(settings->value("geometry").toByteArray());
settings->endGroup();
settings->beginGroup("Docks");
// restoreState(settings->value("DockWindows").toByteArray());
settings->endGroup();
deviceInfoWidget->show();
deviceInfoWidget->raise();
}
void MioMain::closeEvent(QCloseEvent *event) {
writeSettings();
event->accept();
}
void MioMain::openDetectionWindow() {
deviceDetectionWindow = new DeviceDetection(this);
deviceDetectionWindow->exec();
}
void MioMain::writeSettings() {
QSettings *settings = Configuration::getInstance().getSettings();
settings->beginGroup("MainWindow");
settings->setValue("geometry", saveGeometry());
settings->setValue("size", size());
settings->setValue("pos", pos());
settings->endGroup();
settings->beginGroup("Docks");
settings->setValue("DockWindows", saveState());
settings->endGroup();
}
void MioMain::writeDevicesToSettings() {
QSettings *settings = Configuration::getInstance().getSettings();
Devices *devices = Configuration::getInstance().getDevices();
settings->beginWriteArray("Devices");
int i = 0;
for (Devices::iterator it = devices->begin(); it != devices->end(); ++it) {
settings->setArrayIndex(i);
Device *d = it->second;
settings->setValue("Device Name",
QString::fromStdString(d->getDeviceName()));
settings->setValue("Serial Number",
(qlonglong)(d->getSerialNumber()->getLongValue()));
settings->setValue("Input Port", d->getInPortNumer());
settings->setValue("Output Port", d->getOutPortNumer());
settings->setValue("Product Id",
(qlonglong)d->getProductId()->getLongValue());
#ifdef __MIO_SIMULATE__
if (d->getSimulate()) {
settings->setValue("Simulate", true);
settings->setValue("Model Name",
QString::fromStdString(d->getModelName()));
}
#endif
++i;
}
settings->endArray();
}
void MioMain::connectSlots() {
// connect(this->)
}
void MioMain::readSettings() {
this->title = windowTitle();
QSettings *settings = Configuration::getInstance().getSettings();
settings->beginGroup("MainWindow");
resize(settings->value("size", QSize(400, 400)).toSize());
move(settings->value("pos", QPoint(200, 200)).toPoint());
settings->endGroup();
}
bool MioMain::readDevicesFromSettings() {
Devices *devices = Configuration::getInstance().getDevices();
devices->clear();
QSettings *settings = Configuration::getInstance().getSettings();
int size = settings->beginReadArray("Devices");
if (size == 0)
return false;
for (int i = 0; i < size; ++i) {
settings->setArrayIndex(i);
int productId = settings->value("Product Id").toInt();
long serialNumber =
(qlonglong)settings->value("Serial Number").toLongLong();
int inputPort = (qlonglong)settings->value("Input Port").toInt();
int outputPort = (qlonglong)settings->value("Output Port").toInt();
#ifdef __MIO_SIMULATE__
Device *device = 0;
if (settings->value("Simulate").toBool()) {
std::string modelName =
settings->value("Model Name").toString().toStdString();
std::string deviceName =
settings->value("Device Name").toString().toStdString();
device = new Device(inputPort, outputPort, serialNumber, productId,
modelName, deviceName);
} else {
device = new Device(inputPort, outputPort, serialNumber, productId);
}
#else
Device *device = new Device(inputPort, outputPort, serialNumber, productId);
#endif
if (device->queryDeviceInfo())
devices->insert(std::pair<long, Device *>(serialNumber, device));
}
settings->endArray();
if (devices->size() == 0)
return false;
return true;
}
void MioMain::on_actionQuit_triggered() { close(); }
<|endoftext|> |
<commit_before>/* molecule.cc
* Copyright 2014 Cubane Canada, Inc.
*
* Released under the MIT license -- see MIT-LICENSE for details
*/
#include <node.h>
#include <v8.h>
#include <uv.h>
#include <nan.h>
#include <cstring>
#include "./using_v8.h"
#include "./molecule.h"
#include "./get_inchi_worker.h"
/**
@module Internal
@class Molecule_CC
*/
/* local (non-API) functions */
void populate_input(Handle<Value> val, Molecule* in);
static void populate_ret(Handle<Object> ret,
const inchi_Output& out, int result);
void addstring(Handle<Object> ret, const char * name, const char * value);
/**
* Create an Molecule structure from a partially or fully specified
* JavaScript object
*
* @method Create
* @param {Handle<Object>} val Object handle that parallels an inchi_Input
*/
Molecule * Molecule::Create(Handle<Value> val) {
// create an empty Molecule
Molecule * input = new Molecule;
// populate it
populate_input(val, input);
// return it
return input;
}
void add_atom(Molecule* in, Handle<Object> a) {
InchiAtom atom = InchiAtom::makeFromObject(a);
int index = in->addAtom(atom);
Handle<Array> neighbor =
Handle<Array>::Cast(a->Get(NanSymbol("neighbor")));
int bonds = neighbor->Length();
for (int i = 0; i < bonds; ++i) {
int bonded = neighbor->Get(i)->ToNumber()->Value();
in->addBond(InchiBond(index, bonded));
}
}
void populate_input(Handle<Value> val, Molecule* in) {
// TODO(SOM): support validation, possibly return error code
// expect args[0] to be an Object, call it 'mol'
// expect mol.atom to be an Array
// expect mol.options to be a string
// expect mol.stereo0D to be an Array
if (!val->IsObject()) {
return;
}
Handle<Object> mol = val->ToObject();
if (!mol->Has(NanSymbol("atom")) || !mol->Get(NanSymbol("atom"))->IsArray()) {
return;
}
Handle<Array> atom = mol->Get(NanSymbol("atom")).As<Array>();
int atoms = atom->Length();
for (int i = 0; i < atoms; i += 1) {
add_atom(in, atom->Get(i)->ToObject());
}
}
void addstring(Handle<Object> ret, const char * name, const char * in) {
const char * value = (in ? in : "");
ret->Set(NanSymbol(name), String::New(value));
}
static void populate_ret(Handle<Object> ret,
const inchi_Output& out, int result) {
addstring(ret, "inchi", out.szInChI);
addstring(ret, "auxinfo", out.szAuxInfo);
addstring(ret, "message", out.szMessage);
addstring(ret, "log", out.szLog);
ret->Set(NanSymbol("code"), Number::New(result));
}
Handle<Object> GetResult(GetINCHIData * data) {
NanScope();
Local<Object> ret = Object::New();
populate_ret(ret, data->out_, data->result_);
addstring(ret, "inchikey", data->inchikey);
return scope.Close(ret);
}
<commit_msg>inchilib: remove confusing headers<commit_after>/* molecule.cc
* Copyright 2014 Cubane Canada, Inc.
*
* Released under the MIT license -- see MIT-LICENSE for details
*/
#include <nan.h>
#include <cstring>
#include "./using_v8.h"
#include "./molecule.h"
#include "./get_inchi_worker.h"
/**
@module Internal
@class Molecule_CC
*/
/* local (non-API) functions */
void populate_input(Handle<Value> val, Molecule* in);
static void populate_ret(Handle<Object> ret,
const inchi_Output& out, int result);
void addstring(Handle<Object> ret, const char * name, const char * value);
/**
* Create an Molecule structure from a partially or fully specified
* JavaScript object
*
* @method Create
* @param {Handle<Object>} val Object handle that parallels an inchi_Input
*/
Molecule * Molecule::Create(Handle<Value> val) {
// create an empty Molecule
Molecule * input = new Molecule;
// populate it
populate_input(val, input);
// return it
return input;
}
void add_atom(Molecule* in, Handle<Object> a) {
InchiAtom atom = InchiAtom::makeFromObject(a);
int index = in->addAtom(atom);
Handle<Array> neighbor =
Handle<Array>::Cast(a->Get(NanSymbol("neighbor")));
int bonds = neighbor->Length();
for (int i = 0; i < bonds; ++i) {
int bonded = neighbor->Get(i)->ToNumber()->Value();
in->addBond(InchiBond(index, bonded));
}
}
void populate_input(Handle<Value> val, Molecule* in) {
// TODO(SOM): support validation, possibly return error code
// expect args[0] to be an Object, call it 'mol'
// expect mol.atom to be an Array
// expect mol.options to be a string
// expect mol.stereo0D to be an Array
if (!val->IsObject()) {
return;
}
Handle<Object> mol = val->ToObject();
if (!mol->Has(NanSymbol("atom")) || !mol->Get(NanSymbol("atom"))->IsArray()) {
return;
}
Handle<Array> atom = mol->Get(NanSymbol("atom")).As<Array>();
int atoms = atom->Length();
for (int i = 0; i < atoms; i += 1) {
add_atom(in, atom->Get(i)->ToObject());
}
}
void addstring(Handle<Object> ret, const char * name, const char * in) {
const char * value = (in ? in : "");
ret->Set(NanSymbol(name), String::New(value));
}
static void populate_ret(Handle<Object> ret,
const inchi_Output& out, int result) {
addstring(ret, "inchi", out.szInChI);
addstring(ret, "auxinfo", out.szAuxInfo);
addstring(ret, "message", out.szMessage);
addstring(ret, "log", out.szLog);
ret->Set(NanSymbol("code"), Number::New(result));
}
Handle<Object> GetResult(GetINCHIData * data) {
NanScope();
Local<Object> ret = Object::New();
populate_ret(ret, data->out_, data->result_);
addstring(ret, "inchikey", data->inchikey);
return scope.Close(ret);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/timer.h"
#include <math.h>
#if defined(OS_WIN)
#include <mmsystem.h>
#endif
#include "base/atomic_sequence_num.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/task.h"
namespace base {
// A sequence number for all allocated times (used to break ties when
// comparing times in the TimerManager, and assure FIFO execution sequence).
static AtomicSequenceNumber timer_id_counter_;
//-----------------------------------------------------------------------------
// Timer
Timer::Timer(int delay, Task* task, bool repeating)
: task_(task),
delay_(delay),
repeating_(repeating) {
timer_id_ = timer_id_counter_.GetNext();
DCHECK(delay >= 0);
Reset();
}
Timer::Timer(Time fire_time, Task* task)
: fire_time_(fire_time),
task_(task),
repeating_(false) {
timer_id_ = timer_id_counter_.GetNext();
// TODO(darin): kill off this stuff
creation_time_ = Time::Now();
delay_ = static_cast<int>((fire_time_ - creation_time_).InMilliseconds());
DCHECK(delay_ >= 0);
DHISTOGRAM_COUNTS(L"Timer.Durations", delay_);
}
void Timer::Reset() {
creation_time_ = Time::Now();
fire_time_ = creation_time_ + TimeDelta::FromMilliseconds(delay_);
DHISTOGRAM_COUNTS(L"Timer.Durations", delay_);
}
//-----------------------------------------------------------------------------
// TimerPQueue
void TimerPQueue::RemoveTimer(Timer* timer) {
const std::vector<Timer*>::iterator location =
find(c.begin(), c.end(), timer);
if (location != c.end()) {
c.erase(location);
make_heap(c.begin(), c.end(), TimerComparison());
}
}
bool TimerPQueue::ContainsTimer(const Timer* timer) const {
return find(c.begin(), c.end(), timer) != c.end();
}
//-----------------------------------------------------------------------------
// TimerManager
TimerManager::TimerManager(MessageLoop* message_loop)
: use_broken_delay_(false),
message_loop_(message_loop) {
#if defined(OS_WIN)
// We've experimented with all sorts of timers, and initially tried
// to avoid using timeBeginPeriod because it does affect the system
// globally. However, after much investigation, it turns out that all
// of the major plugins (flash, windows media 9-11, and quicktime)
// already use timeBeginPeriod to increase the speed of the clock.
// Since the browser must work with these plugins, the browser already
// needs to support a fast clock. We may as well use this ourselves,
// as it really is the best timer mechanism for our needs.
timeBeginPeriod(1);
#endif
}
TimerManager::~TimerManager() {
#if defined(OS_WIN)
// Match timeBeginPeriod() from construction.
timeEndPeriod(1);
#endif
// Be nice to unit tests, and discard and delete all timers along with the
// embedded task objects by handing off to MessageLoop (which would have Run()
// and optionally deleted the objects).
while (timers_.size()) {
Timer* pending = timers_.top();
timers_.pop();
message_loop_->DiscardTimer(pending);
}
}
Timer* TimerManager::StartTimer(int delay, Task* task, bool repeating) {
Timer* t = new Timer(delay, task, repeating);
StartTimer(t);
return t;
}
void TimerManager::StopTimer(Timer* timer) {
// Make sure the timer is actually running.
if (!IsTimerRunning(timer))
return;
// Kill the active timer, and remove the pending entry from the queue.
if (timer != timers_.top()) {
timers_.RemoveTimer(timer);
} else {
timers_.pop();
DidChangeNextTimer();
}
}
void TimerManager::ResetTimer(Timer* timer) {
StopTimer(timer);
timer->Reset();
StartTimer(timer);
}
bool TimerManager::IsTimerRunning(const Timer* timer) const {
return timers_.ContainsTimer(timer);
}
Timer* TimerManager::PeekTopTimer() {
if (timers_.empty())
return NULL;
return timers_.top();
}
bool TimerManager::RunSomePendingTimers() {
bool did_work = false;
// Process a small group of timers. Cap the maximum number of timers we can
// process so we don't deny cycles to other parts of the process when lots of
// timers have been set.
const int kMaxTimersPerCall = 2;
for (int i = 0; i < kMaxTimersPerCall; ++i) {
if (timers_.empty() || timers_.top()->fire_time() > Time::Now())
break;
// Get a pending timer. Deal with updating the timers_ queue and setting
// the TopTimer. We'll execute the timer task only after the timer queue
// is back in a consistent state.
Timer* pending = timers_.top();
// If pending task isn't invoked_later, then it must be possible to run it
// now (i.e., current task needs to be reentrant).
// TODO(jar): We may block tasks that we can queue from being popped.
if (!message_loop_->NestableTasksAllowed() &&
!pending->task()->owned_by_message_loop_)
break;
timers_.pop();
did_work = true;
// If the timer is repeating, add it back to the list of timers to process.
if (pending->repeating()) {
pending->Reset();
timers_.push(pending);
}
message_loop_->RunTimerTask(pending);
}
// Restart the WM_TIMER (if necessary).
if (did_work)
DidChangeNextTimer();
return did_work;
}
// Note: Caller is required to call timer->Reset() before calling StartTimer().
// TODO(jar): change API so that Reset() is called as part of StartTimer, making
// the API a little less error prone.
void TimerManager::StartTimer(Timer* timer) {
// Make sure the timer is not running.
if (IsTimerRunning(timer))
return;
timers_.push(timer); // Priority queue will sort the timer into place.
if (timers_.top() == timer) // We are new head of queue.
DidChangeNextTimer();
}
Time TimerManager::GetNextFireTime() const {
if (timers_.empty())
return Time();
return timers_.top()->fire_time();
}
void TimerManager::DidChangeNextTimer() {
// Determine if the next timer expiry actually changed...
if (!timers_.empty()) {
const Time& expiry = timers_.top()->fire_time();
if (expiry == next_timer_expiry_)
return;
next_timer_expiry_ = expiry;
} else {
next_timer_expiry_ = Time();
}
message_loop_->DidChangeNextTimerExpiry();
}
//-----------------------------------------------------------------------------
// BaseTimer_Helper
void BaseTimer_Helper::OrphanDelayedTask() {
if (delayed_task_) {
delayed_task_->timer_ = NULL;
delayed_task_ = NULL;
}
}
void BaseTimer_Helper::InitiateDelayedTask(TimerTask* timer_task) {
OrphanDelayedTask();
delayed_task_ = timer_task;
delayed_task_->timer_ = this;
MessageLoop::current()->PostDelayedTask(
FROM_HERE, timer_task, static_cast<int>(delay_.InMilliseconds()));
}
} // namespace base
<commit_msg>Remove assertion in Timer() because it was too aggressive. Instead, we need to just treat a negative delay as a zero delay.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/timer.h"
#include <math.h>
#if defined(OS_WIN)
#include <mmsystem.h>
#endif
#include "base/atomic_sequence_num.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/task.h"
namespace base {
// A sequence number for all allocated times (used to break ties when
// comparing times in the TimerManager, and assure FIFO execution sequence).
static AtomicSequenceNumber timer_id_counter_;
//-----------------------------------------------------------------------------
// Timer
Timer::Timer(int delay, Task* task, bool repeating)
: task_(task),
delay_(delay),
repeating_(repeating) {
timer_id_ = timer_id_counter_.GetNext();
DCHECK(delay >= 0);
Reset();
}
Timer::Timer(Time fire_time, Task* task)
: fire_time_(fire_time),
task_(task),
repeating_(false) {
timer_id_ = timer_id_counter_.GetNext();
// TODO(darin): kill off this stuff. because we are forced to compute 'now'
// in order to determine the delay, it is possible that our fire time could
// be in the past. /sigh/
creation_time_ = Time::Now();
delay_ = static_cast<int>((fire_time_ - creation_time_).InMilliseconds());
if (delay_ < 0)
delay_ = 0;
DHISTOGRAM_COUNTS(L"Timer.Durations", delay_);
}
void Timer::Reset() {
creation_time_ = Time::Now();
fire_time_ = creation_time_ + TimeDelta::FromMilliseconds(delay_);
DHISTOGRAM_COUNTS(L"Timer.Durations", delay_);
}
//-----------------------------------------------------------------------------
// TimerPQueue
void TimerPQueue::RemoveTimer(Timer* timer) {
const std::vector<Timer*>::iterator location =
find(c.begin(), c.end(), timer);
if (location != c.end()) {
c.erase(location);
make_heap(c.begin(), c.end(), TimerComparison());
}
}
bool TimerPQueue::ContainsTimer(const Timer* timer) const {
return find(c.begin(), c.end(), timer) != c.end();
}
//-----------------------------------------------------------------------------
// TimerManager
TimerManager::TimerManager(MessageLoop* message_loop)
: use_broken_delay_(false),
message_loop_(message_loop) {
#if defined(OS_WIN)
// We've experimented with all sorts of timers, and initially tried
// to avoid using timeBeginPeriod because it does affect the system
// globally. However, after much investigation, it turns out that all
// of the major plugins (flash, windows media 9-11, and quicktime)
// already use timeBeginPeriod to increase the speed of the clock.
// Since the browser must work with these plugins, the browser already
// needs to support a fast clock. We may as well use this ourselves,
// as it really is the best timer mechanism for our needs.
timeBeginPeriod(1);
#endif
}
TimerManager::~TimerManager() {
#if defined(OS_WIN)
// Match timeBeginPeriod() from construction.
timeEndPeriod(1);
#endif
// Be nice to unit tests, and discard and delete all timers along with the
// embedded task objects by handing off to MessageLoop (which would have Run()
// and optionally deleted the objects).
while (timers_.size()) {
Timer* pending = timers_.top();
timers_.pop();
message_loop_->DiscardTimer(pending);
}
}
Timer* TimerManager::StartTimer(int delay, Task* task, bool repeating) {
Timer* t = new Timer(delay, task, repeating);
StartTimer(t);
return t;
}
void TimerManager::StopTimer(Timer* timer) {
// Make sure the timer is actually running.
if (!IsTimerRunning(timer))
return;
// Kill the active timer, and remove the pending entry from the queue.
if (timer != timers_.top()) {
timers_.RemoveTimer(timer);
} else {
timers_.pop();
DidChangeNextTimer();
}
}
void TimerManager::ResetTimer(Timer* timer) {
StopTimer(timer);
timer->Reset();
StartTimer(timer);
}
bool TimerManager::IsTimerRunning(const Timer* timer) const {
return timers_.ContainsTimer(timer);
}
Timer* TimerManager::PeekTopTimer() {
if (timers_.empty())
return NULL;
return timers_.top();
}
bool TimerManager::RunSomePendingTimers() {
bool did_work = false;
// Process a small group of timers. Cap the maximum number of timers we can
// process so we don't deny cycles to other parts of the process when lots of
// timers have been set.
const int kMaxTimersPerCall = 2;
for (int i = 0; i < kMaxTimersPerCall; ++i) {
if (timers_.empty() || timers_.top()->fire_time() > Time::Now())
break;
// Get a pending timer. Deal with updating the timers_ queue and setting
// the TopTimer. We'll execute the timer task only after the timer queue
// is back in a consistent state.
Timer* pending = timers_.top();
// If pending task isn't invoked_later, then it must be possible to run it
// now (i.e., current task needs to be reentrant).
// TODO(jar): We may block tasks that we can queue from being popped.
if (!message_loop_->NestableTasksAllowed() &&
!pending->task()->owned_by_message_loop_)
break;
timers_.pop();
did_work = true;
// If the timer is repeating, add it back to the list of timers to process.
if (pending->repeating()) {
pending->Reset();
timers_.push(pending);
}
message_loop_->RunTimerTask(pending);
}
// Restart the WM_TIMER (if necessary).
if (did_work)
DidChangeNextTimer();
return did_work;
}
// Note: Caller is required to call timer->Reset() before calling StartTimer().
// TODO(jar): change API so that Reset() is called as part of StartTimer, making
// the API a little less error prone.
void TimerManager::StartTimer(Timer* timer) {
// Make sure the timer is not running.
if (IsTimerRunning(timer))
return;
timers_.push(timer); // Priority queue will sort the timer into place.
if (timers_.top() == timer) // We are new head of queue.
DidChangeNextTimer();
}
Time TimerManager::GetNextFireTime() const {
if (timers_.empty())
return Time();
return timers_.top()->fire_time();
}
void TimerManager::DidChangeNextTimer() {
// Determine if the next timer expiry actually changed...
if (!timers_.empty()) {
const Time& expiry = timers_.top()->fire_time();
if (expiry == next_timer_expiry_)
return;
next_timer_expiry_ = expiry;
} else {
next_timer_expiry_ = Time();
}
message_loop_->DidChangeNextTimerExpiry();
}
//-----------------------------------------------------------------------------
// BaseTimer_Helper
void BaseTimer_Helper::OrphanDelayedTask() {
if (delayed_task_) {
delayed_task_->timer_ = NULL;
delayed_task_ = NULL;
}
}
void BaseTimer_Helper::InitiateDelayedTask(TimerTask* timer_task) {
OrphanDelayedTask();
delayed_task_ = timer_task;
delayed_task_->timer_ = this;
MessageLoop::current()->PostDelayedTask(
FROM_HERE, timer_task, static_cast<int>(delay_.InMilliseconds()));
}
} // namespace base
<|endoftext|> |
<commit_before>#include "xchainer/array.h"
#include <cassert>
#include <cstring>
#ifdef XCHAINER_ENABLE_CUDA
#include <cuda.h>
#include <cuda_runtime.h>
#endif // XCHAINER_ENABLE_CUDA
#include "xchainer/array_fill.h"
#include "xchainer/array_math.h"
#include "xchainer/array_repr.h"
#ifdef XCHAINER_ENABLE_CUDA
#include "xchainer/cuda/array_fill.h"
#include "xchainer/cuda/array_math.h"
#include "xchainer/cuda/cuda_runtime.h"
#endif // XCHAINER_ENABLE_CUDA
#include "xchainer/device.h"
#include "xchainer/memory.h"
#include "xchainer/op_node.h"
#include "xchainer/scalar.h"
namespace xchainer {
Array::Array(Shape shape, Dtype dtype, std::shared_ptr<void> data, std::shared_ptr<ArrayNode> node, bool requires_grad, bool is_contiguous,
int64_t offset)
: shape_(std::move(shape)),
dtype_(dtype),
data_(std::move(data)),
requires_grad_(requires_grad),
is_contiguous_(is_contiguous),
offset_(offset),
node_(std::move(node)) {}
Array::Array(const Array& other)
: shape_(other.shape_),
dtype_(other.dtype_),
requires_grad_(other.requires_grad_),
is_contiguous_(other.is_contiguous_),
offset_(other.offset_),
node_(std::make_shared<ArrayNode>()) {
data_ = internal::Allocate(GetCurrentDevice(), other.total_bytes());
other.Copy(*this);
}
const std::shared_ptr<ArrayNode>& Array::RenewNode() {
node_ = std::make_shared<ArrayNode>();
return node_;
}
const nonstd::optional<Array>& Array::grad() const noexcept { return node_->grad(); }
void Array::set_grad(Array grad) { node_->set_grad(std::move(grad)); }
void Array::ClearGrad() noexcept { node_->ClearGrad(); }
Array Array::FromBuffer(const Shape& shape, Dtype dtype, std::shared_ptr<void> data) {
auto bytesize = static_cast<size_t>(shape.total_size() * GetElementSize(dtype));
std::shared_ptr<void> device_data = internal::MemoryFromBuffer(GetCurrentDevice(), data, bytesize);
return {shape, dtype, device_data, std::make_unique<ArrayNode>()};
}
Array Array::Empty(const Shape& shape, Dtype dtype) {
auto bytesize = static_cast<size_t>(shape.total_size() * GetElementSize(dtype));
std::shared_ptr<void> data = internal::Allocate(GetCurrentDevice(), bytesize);
return {shape, dtype, data, std::make_unique<ArrayNode>()};
}
Array Array::Full(const Shape& shape, Scalar scalar, Dtype dtype) {
Array array = Empty(shape, dtype);
array.Fill(scalar);
return array;
}
Array Array::Full(const Shape& shape, Scalar scalar) { return Full(shape, scalar, scalar.dtype()); }
Array Array::Zeros(const Shape& shape, Dtype dtype) { return Full(shape, 0, dtype); }
Array Array::Ones(const Shape& shape, Dtype dtype) { return Full(shape, 1, dtype); }
Array Array::EmptyLike(const Array& array) { return Empty(array.shape(), array.dtype()); }
Array Array::FullLike(const Array& array, Scalar scalar) { return Full(array.shape(), scalar, array.dtype()); }
Array Array::ZerosLike(const Array& array) { return Zeros(array.shape(), array.dtype()); }
Array Array::OnesLike(const Array& array) { return Ones(array.shape(), array.dtype()); }
Array Array::MakeView() const { return {shape_, dtype_, data_, node_, requires_grad_, is_contiguous_, offset_}; }
Array& Array::operator+=(const Array& rhs) {
Add(rhs, *this);
requires_grad_ = requires_grad_ || rhs.requires_grad();
return *this;
}
Array& Array::operator*=(const Array& rhs) {
Mul(rhs, *this);
requires_grad_ = requires_grad_ || rhs.requires_grad();
return *this;
}
Array Array::operator+(const Array& rhs) const {
Array out = Array::EmptyLike(*this);
out.set_requires_grad(requires_grad_ || rhs.requires_grad());
Add(rhs, out);
return out;
}
Array Array::operator*(const Array& rhs) const {
Array out = Array::EmptyLike(*this);
out.set_requires_grad(requires_grad_ || rhs.requires_grad());
Mul(rhs, out);
return out;
}
void Array::Copy(Array& out) const {
if (requires_grad_) {
std::shared_ptr<ArrayNode> out_node = out.RenewNode();
auto in_func = [](const Array& gout) { return gout; };
auto backward_functions = std::vector<std::function<Array(const Array&)>>{in_func};
std::shared_ptr<OpNode> op_node =
std::make_shared<OpNode>("copy", std::vector<std::shared_ptr<const ArrayNode>>{node_}, backward_functions);
out_node->set_next_node(op_node);
}
internal::MemoryCopy(out.data().get(), data_.get(), total_bytes());
}
void Array::Add(const Array& rhs, Array& out) const {
if ((&out == this || &out == &rhs) && out.requires_grad_) {
throw XchainerError("In-place operation (Add) is not supported for an array with requires_grad=true.");
}
// TODO(sonots): dtype conversion
CheckEqual(dtype_, rhs.dtype());
// TODO(sonots): broadcasting
CheckEqual(shape_, rhs.shape());
if (requires_grad_ || rhs.requires_grad()) {
const Array& lhs = *this;
std::shared_ptr<const ArrayNode> lhs_node = node();
std::shared_ptr<const ArrayNode> rhs_node = rhs.node();
std::shared_ptr<ArrayNode> out_node = out.RenewNode();
std::function<Array(const Array&)> empty_func;
auto lhs_func = lhs.requires_grad() ? [](const Array& gout) { return gout; } : empty_func;
auto rhs_func = rhs.requires_grad() ? [](const Array& gout) { return gout; } : empty_func;
auto backward_functions = std::vector<std::function<Array(const Array&)>>{lhs_func, rhs_func};
std::shared_ptr<OpNode> op_node =
std::make_shared<OpNode>("add", std::vector<std::shared_ptr<const ArrayNode>>{lhs_node, rhs_node}, backward_functions);
out_node->set_next_node(op_node);
}
Device device = GetCurrentDevice();
if (device == MakeDevice("cpu")) {
xchainer::Add(*this, rhs, out);
#ifdef XCHAINER_ENABLE_CUDA
} else if (device == MakeDevice("cuda")) {
xchainer::cuda::Add(*this, rhs, out);
#endif // XCHAINER_ENABLE_CUDA
} else {
throw DeviceError("invalid device");
}
}
void Array::Mul(const Array& rhs, Array& out) const {
if ((&out == this || &out == &rhs) && out.requires_grad_) {
throw XchainerError("In-place operation (Mul) is not supported for an array with requires_grad=true.");
}
// TODO(sonots): dtype conversion
CheckEqual(dtype_, rhs.dtype());
// TODO(sonots): broadcasting
CheckEqual(shape_, rhs.shape());
if (requires_grad_ || rhs.requires_grad()) {
std::shared_ptr<const ArrayNode> lhs_node = node();
std::shared_ptr<const ArrayNode> rhs_node = rhs.node();
std::shared_ptr<ArrayNode> out_node = out.RenewNode();
std::function<Array(const Array&)> empty_func;
// TODO(sonots): turn off constructing graph (requires_grad) in backward (but, turn on for double backprop)
// TODO(hvy): capture rhs by view (value)
auto lhs_func = requires_grad_ ? [rhs](const Array& gout) { return gout * rhs; } : empty_func;
auto rhs_func = empty_func;
if (rhs.requires_grad()) {
if (this == &out) {
// deep copy for in-place operation to keep original input
Array lhs = *this;
rhs_func = [lhs](const Array& gout) { return gout * lhs; };
} else {
// TODO(takagi): capture lhs by view
Array lhs = *this;
rhs_func = [lhs](const Array& gout) { return gout * lhs; };
}
}
auto backward_functions = std::vector<std::function<Array(const Array&)>>{lhs_func, rhs_func};
std::shared_ptr<OpNode> op_node =
std::make_shared<OpNode>("mul", std::vector<std::shared_ptr<const ArrayNode>>{lhs_node, rhs_node}, backward_functions);
out_node->set_next_node(op_node);
}
Device device = GetCurrentDevice();
if (device == MakeDevice("cpu")) {
xchainer::Mul(*this, rhs, out);
#ifdef XCHAINER_ENABLE_CUDA
} else if (device == MakeDevice("cuda")) {
xchainer::cuda::Mul(*this, rhs, out);
#endif // XCHAINER_ENABLE_CUDA
} else {
throw DeviceError("invalid device");
}
}
void Array::Fill(Scalar value) {
Device device = GetCurrentDevice();
if (device == MakeDevice("cpu")) {
xchainer::Fill(*this, value);
#ifdef XCHAINER_ENABLE_CUDA
} else if (device == MakeDevice("cuda")) {
xchainer::cuda::Fill(*this, value);
#endif // XCHAINER_ENABLE_CUDA
} else {
throw DeviceError("invalid device");
}
}
std::string Array::ToString() const { return ArrayRepr(*this); }
namespace {
void DebugDumpComputationalGraph(std::ostream& os, const ArrayNode& array_node, int indent) {
static const char kIndentChar = ' ';
os << std::string(static_cast<size_t>(indent * 2), kIndentChar) << "ArrayNode<" << &array_node << ">" << std::endl;
std::shared_ptr<const OpNode> op = array_node.next_node();
if (op) {
os << std::string(static_cast<size_t>((indent + 1) * 2), kIndentChar) << "Op<" << op->name() << ">" << std::endl;
for (const std::shared_ptr<const ArrayNode>& next_node : op->next_nodes()) {
DebugDumpComputationalGraph(os, *next_node, static_cast<size_t>(indent + 2));
}
}
}
} // namespace
void DebugDumpComputationalGraph(std::ostream& os, const Array& array, int indent) {
DebugDumpComputationalGraph(os, *array.node(), indent);
}
} // namespace xchainer
<commit_msg>Use MakeView<commit_after>#include "xchainer/array.h"
#include <cassert>
#include <cstring>
#ifdef XCHAINER_ENABLE_CUDA
#include <cuda.h>
#include <cuda_runtime.h>
#endif // XCHAINER_ENABLE_CUDA
#include "xchainer/array_fill.h"
#include "xchainer/array_math.h"
#include "xchainer/array_repr.h"
#ifdef XCHAINER_ENABLE_CUDA
#include "xchainer/cuda/array_fill.h"
#include "xchainer/cuda/array_math.h"
#include "xchainer/cuda/cuda_runtime.h"
#endif // XCHAINER_ENABLE_CUDA
#include "xchainer/device.h"
#include "xchainer/memory.h"
#include "xchainer/op_node.h"
#include "xchainer/scalar.h"
namespace xchainer {
Array::Array(Shape shape, Dtype dtype, std::shared_ptr<void> data, std::shared_ptr<ArrayNode> node, bool requires_grad, bool is_contiguous,
int64_t offset)
: shape_(std::move(shape)),
dtype_(dtype),
data_(std::move(data)),
requires_grad_(requires_grad),
is_contiguous_(is_contiguous),
offset_(offset),
node_(std::move(node)) {}
Array::Array(const Array& other)
: shape_(other.shape_),
dtype_(other.dtype_),
requires_grad_(other.requires_grad_),
is_contiguous_(other.is_contiguous_),
offset_(other.offset_),
node_(std::make_shared<ArrayNode>()) {
data_ = internal::Allocate(GetCurrentDevice(), other.total_bytes());
other.Copy(*this);
}
const std::shared_ptr<ArrayNode>& Array::RenewNode() {
node_ = std::make_shared<ArrayNode>();
return node_;
}
const nonstd::optional<Array>& Array::grad() const noexcept { return node_->grad(); }
void Array::set_grad(Array grad) { node_->set_grad(std::move(grad)); }
void Array::ClearGrad() noexcept { node_->ClearGrad(); }
Array Array::FromBuffer(const Shape& shape, Dtype dtype, std::shared_ptr<void> data) {
auto bytesize = static_cast<size_t>(shape.total_size() * GetElementSize(dtype));
std::shared_ptr<void> device_data = internal::MemoryFromBuffer(GetCurrentDevice(), data, bytesize);
return {shape, dtype, device_data, std::make_unique<ArrayNode>()};
}
Array Array::Empty(const Shape& shape, Dtype dtype) {
auto bytesize = static_cast<size_t>(shape.total_size() * GetElementSize(dtype));
std::shared_ptr<void> data = internal::Allocate(GetCurrentDevice(), bytesize);
return {shape, dtype, data, std::make_unique<ArrayNode>()};
}
Array Array::Full(const Shape& shape, Scalar scalar, Dtype dtype) {
Array array = Empty(shape, dtype);
array.Fill(scalar);
return array;
}
Array Array::Full(const Shape& shape, Scalar scalar) { return Full(shape, scalar, scalar.dtype()); }
Array Array::Zeros(const Shape& shape, Dtype dtype) { return Full(shape, 0, dtype); }
Array Array::Ones(const Shape& shape, Dtype dtype) { return Full(shape, 1, dtype); }
Array Array::EmptyLike(const Array& array) { return Empty(array.shape(), array.dtype()); }
Array Array::FullLike(const Array& array, Scalar scalar) { return Full(array.shape(), scalar, array.dtype()); }
Array Array::ZerosLike(const Array& array) { return Zeros(array.shape(), array.dtype()); }
Array Array::OnesLike(const Array& array) { return Ones(array.shape(), array.dtype()); }
Array Array::MakeView() const { return {shape_, dtype_, data_, node_, requires_grad_, is_contiguous_, offset_}; }
Array& Array::operator+=(const Array& rhs) {
Add(rhs, *this);
requires_grad_ = requires_grad_ || rhs.requires_grad();
return *this;
}
Array& Array::operator*=(const Array& rhs) {
Mul(rhs, *this);
requires_grad_ = requires_grad_ || rhs.requires_grad();
return *this;
}
Array Array::operator+(const Array& rhs) const {
Array out = Array::EmptyLike(*this);
out.set_requires_grad(requires_grad_ || rhs.requires_grad());
Add(rhs, out);
return out;
}
Array Array::operator*(const Array& rhs) const {
Array out = Array::EmptyLike(*this);
out.set_requires_grad(requires_grad_ || rhs.requires_grad());
Mul(rhs, out);
return out;
}
void Array::Copy(Array& out) const {
if (requires_grad_) {
std::shared_ptr<ArrayNode> out_node = out.RenewNode();
auto in_func = [](const Array& gout) { return gout; };
auto backward_functions = std::vector<std::function<Array(const Array&)>>{in_func};
std::shared_ptr<OpNode> op_node =
std::make_shared<OpNode>("copy", std::vector<std::shared_ptr<const ArrayNode>>{node_}, backward_functions);
out_node->set_next_node(op_node);
}
internal::MemoryCopy(out.data().get(), data_.get(), total_bytes());
}
void Array::Add(const Array& rhs, Array& out) const {
if ((&out == this || &out == &rhs) && out.requires_grad_) {
throw XchainerError("In-place operation (Add) is not supported for an array with requires_grad=true.");
}
// TODO(sonots): dtype conversion
CheckEqual(dtype_, rhs.dtype());
// TODO(sonots): broadcasting
CheckEqual(shape_, rhs.shape());
if (requires_grad_ || rhs.requires_grad()) {
const Array& lhs = *this;
std::shared_ptr<const ArrayNode> lhs_node = node();
std::shared_ptr<const ArrayNode> rhs_node = rhs.node();
std::shared_ptr<ArrayNode> out_node = out.RenewNode();
std::function<Array(const Array&)> empty_func;
auto lhs_func = lhs.requires_grad() ? [](const Array& gout) { return gout; } : empty_func;
auto rhs_func = rhs.requires_grad() ? [](const Array& gout) { return gout; } : empty_func;
auto backward_functions = std::vector<std::function<Array(const Array&)>>{lhs_func, rhs_func};
std::shared_ptr<OpNode> op_node =
std::make_shared<OpNode>("add", std::vector<std::shared_ptr<const ArrayNode>>{lhs_node, rhs_node}, backward_functions);
out_node->set_next_node(op_node);
}
Device device = GetCurrentDevice();
if (device == MakeDevice("cpu")) {
xchainer::Add(*this, rhs, out);
#ifdef XCHAINER_ENABLE_CUDA
} else if (device == MakeDevice("cuda")) {
xchainer::cuda::Add(*this, rhs, out);
#endif // XCHAINER_ENABLE_CUDA
} else {
throw DeviceError("invalid device");
}
}
void Array::Mul(const Array& rhs, Array& out) const {
if ((&out == this || &out == &rhs) && out.requires_grad_) {
throw XchainerError("In-place operation (Mul) is not supported for an array with requires_grad=true.");
}
// TODO(sonots): dtype conversion
CheckEqual(dtype_, rhs.dtype());
// TODO(sonots): broadcasting
CheckEqual(shape_, rhs.shape());
if (requires_grad_ || rhs.requires_grad()) {
std::shared_ptr<const ArrayNode> lhs_node = node();
std::shared_ptr<const ArrayNode> rhs_node = rhs.node();
std::shared_ptr<ArrayNode> out_node = out.RenewNode();
std::function<Array(const Array&)> empty_func;
// TODO(sonots): turn off constructing graph (requires_grad) in backward (but, turn on for double backprop)
auto lhs_func = requires_grad_ ? [rhs_view = rhs.MakeView()](const Array& gout) { return gout * rhs_view; } : empty_func;
auto rhs_func = requires_grad_ ? [lhs_view = MakeView()](const Array& gout) { return gout * lhs_view; } : empty_func;
auto backward_functions = std::vector<std::function<Array(const Array&)>>{lhs_func, rhs_func};
std::shared_ptr<OpNode> op_node =
std::make_shared<OpNode>("mul", std::vector<std::shared_ptr<const ArrayNode>>{lhs_node, rhs_node}, backward_functions);
out_node->set_next_node(op_node);
}
Device device = GetCurrentDevice();
if (device == MakeDevice("cpu")) {
xchainer::Mul(*this, rhs, out);
#ifdef XCHAINER_ENABLE_CUDA
} else if (device == MakeDevice("cuda")) {
xchainer::cuda::Mul(*this, rhs, out);
#endif // XCHAINER_ENABLE_CUDA
} else {
throw DeviceError("invalid device");
}
}
void Array::Fill(Scalar value) {
Device device = GetCurrentDevice();
if (device == MakeDevice("cpu")) {
xchainer::Fill(*this, value);
#ifdef XCHAINER_ENABLE_CUDA
} else if (device == MakeDevice("cuda")) {
xchainer::cuda::Fill(*this, value);
#endif // XCHAINER_ENABLE_CUDA
} else {
throw DeviceError("invalid device");
}
}
std::string Array::ToString() const { return ArrayRepr(*this); }
namespace {
void DebugDumpComputationalGraph(std::ostream& os, const ArrayNode& array_node, int indent) {
static const char kIndentChar = ' ';
os << std::string(static_cast<size_t>(indent * 2), kIndentChar) << "ArrayNode<" << &array_node << ">" << std::endl;
std::shared_ptr<const OpNode> op = array_node.next_node();
if (op) {
os << std::string(static_cast<size_t>((indent + 1) * 2), kIndentChar) << "Op<" << op->name() << ">" << std::endl;
for (const std::shared_ptr<const ArrayNode>& next_node : op->next_nodes()) {
DebugDumpComputationalGraph(os, *next_node, static_cast<size_t>(indent + 2));
}
}
}
} // namespace
void DebugDumpComputationalGraph(std::ostream& os, const Array& array, int indent) {
DebugDumpComputationalGraph(os, *array.node(), indent);
}
} // namespace xchainer
<|endoftext|> |
<commit_before>#include "include/geom.h"
#include <assert.h>
Constructor::Constructor(MoveListener *listener) :
Scope(listener), angles() {}
Constructor::~Constructor()
{
for (auto *a : angles)
delete a;
}
bool Constructor::contains(const Angle *a) const
{
return a != nullptr &&
std::count_if(angles.begin(), angles.end(), [a](const Angle *p) {return *p == *a; });
}
void Constructor::add(const Angle *a)
{
if (!contains(a))
angles.push_back(a);
}
#define _make_move(movetype, arg1, arg2, res) do { \
if (res != nullptr) { \
Scope::add(res); \
Scope::listener->movetype(arg1, arg2, res); \
}} while (0)
const LineSegment *Constructor::join_segment(const Point &a, const Point &b)
{
if (!Scope::contains(&a) || !Scope::contains(&b) || a == b)
return nullptr;
const LineSegment *res = new LineSegment(a, b);
Scope::add(res);
_make_move(straightedge, &a, &b, res);
return res;
}
const Angle *Constructor::join_angle(const Point &end1, const Point &vertex, const Point &end2)
{
if (!Scope::contains(&end1) || !Scope::contains(&vertex) || !Scope::contains(&end2) ||
vertex == end1 || vertex == end2) // end1 and end2 might be the same in a 0 degree angle
return nullptr;
const Angle *res = new Angle(end1, vertex, end2);
add(res);
if (!Scope::contains(&res->l1)) {
Scope::add(&res->l1);
_make_move(straightedge, &vertex, &end1, &res->l1);
}
if (!Scope::contains(&res->l2)) {
Scope::add(&res->l2);
_make_move(straightedge, &vertex, &end2, &res->l2);
}
return res;
}
#undef _make_move
// only returns nullptr if l or p isn't contained, makes no moves in that case
const Line *Constructor::perpendicular(const Line &l, const Point &p)
{
const Point *o1, *o2;
const Circle *c, *c1, *c2;
const Line &l1 (l); // ensure containment for line segments
if (!Scope::contains(&p) || !Scope::contains(&l))
return nullptr;
// generate two points on the line equidistant from p
o1 = nullptr;
for (auto *p2 : points)
if (l1.contains(*p2) && *p2 != p) { o1 = p2; break; }
assert(o1 != nullptr);
c = join_circle(p, *o1);
assert(c != nullptr); // p != *o1 as generated by the loop
auto pair = meet(l1, *c); // the copy constructor works well with Scope::contains
o2 = *pair.first == *o1 ? pair.second : pair.first;
assert(o2 != nullptr); // l1 goes through the diameter of *c, has two intersections
// create circles from o1 to o2 and from o2 to o1
c1 = join_circle(*o1, *o2);
c2 = join_circle(*o2, *o1);
assert(*c1 != *c2); // o1 and o2 are different
pair = meet(*c1, *c2);
assert(pair.second != nullptr);
// by this assertion, no moves will be made before returning nullptr
return join_line(*pair.first, *pair.second); // two meets have to be different
// the deletion of all these items are to be handled by ~Scope()
}
// only returns nullptr if l or p not contained, makes no moves in that case
const Line *Constructor::parallel(const Line &l, const Point &p)
{
if (l.contains(p))
return &l;
auto perp = perpendicular(l, p);
if (perp == nullptr)
return nullptr;
return perpendicular(*perp, p);
}
// returns nullptr if l or start not contained, returns l if l.start == start, makes no moves in those cases
const LineSegment *Constructor::translate(const LineSegment &l, const Point &start)
{
const Line *par, *diff, *diff1;
const Point *end;
const LineSegment *res;
par = parallel(l, start);
if (par == nullptr) // l or start isn't added
return nullptr;
diff = join_line(l.start, start);
if (diff == nullptr) // fails if l.start == start
return &l;
diff1 = parallel(*diff, l.end);
assert(diff1 != nullptr);
end = meet(*par, *diff1);
assert(end != nullptr); // TODO move these assertions to Scope
return join_segment(start, *end);
}
#define _ratio(l1, l2) ((l1).x_coeff == 0) ? sgn((l1).y_coeff * (l2).y_coeff) : sgn((l1).x_coeff * (l2).x_coeff)
// only returns nullptr if a or p isn't contained, makes no moves
const Angle *Constructor::translate(const Angle &a, const Point &p)
{
const Line *l1 = parallel(a.l1, p),
*l2 = parallel(a.l2, p);
if (l1 == nullptr || l2 == nullptr)
return nullptr;
// the sign of the ratio of nonconstant coefficients for l1 and l2
int r1 = _ratio(a.l1, *l1),
r2 = _ratio(a.l2, *l2);
// necessary for the construction of angle based on lines and regions
// join_angle only makes moves if l1 or l2 isn't contained, which isn't true in this case
const Angle *res = new Angle(*l1, *l2, r1 * a.region1, r2 * a.region2);
add(res);
return res;
}
#undef _ratio
// fails if arguments aren't contained or are the same, makes no moves
const Line *Constructor::bisect(const Point &a, const Point &b)
{
const Circle *c1 = join_circle(a, b),
*c2 = join_circle(b, a);
if (c1 == nullptr || c2 == nullptr) // in which case a != b and c1 != c2
return nullptr;
auto _meet = meet(*c1, *c2);
assert(_meet.second != nullptr);
return join_line(*_meet.first, *_meet.second); // two meets have to be different
}
// same as above
const Line *Constructor::bisect(const LineSegment &l)
{
return bisect(l.start, l.end);
}
// fails if a isn't contained, with no moves, works for the 180 degree case
const Line *Constructor::bisect(const Angle &a)
{
if (!contains(&a))
return nullptr;
// 0 degree angle
if (a.l1 == a.l2 && a.region1 * a.l1.x_coeff == a.region2 * a.l2.x_coeff)
return &a.l1;
// find point on l1 other than vertex
const Point *p1 = nullptr;
for (auto *p : points)
if (a.l1.contains(*p) && *p != a.vertex) { p1 = p; break; }
assert(p1 != nullptr);
// find point on l2 with same region as p1
const Circle *c = join_circle(a.vertex, *p1); // points different
auto _meet = meet(a.l2, *c);
assert(_meet.second != nullptr); // l2 goes through vertex, the center of c
// choose point on l2 on the same side as p1
const Point *p2 = (a.l1.precedes(a.vertex, *p1) ? a.region1 : -a.region1 ==
a.l2.precedes(a.vertex, *_meet.first) ? a.region2 : -a.region2) ? _meet.first : _meet.second;
return bisect(*p1, *p2);
}
// fails if the arguments aren't contained or are the same, with no moves
const Point *Constructor::midpoint(const Point &a, const Point &b)
{
const Line *l1 = join_line(a, b),
*l2 = bisect(a, b);
if (l1 == nullptr || l2 == nullptr)
return nullptr;
return meet(*l1, *l2);
}
// same as above
const Point *Constructor::midpoint(const LineSegment &a)
{
return midpoint(a.start, a.end);
}
// same as above
const Point *Constructor::reflect(const Point &a, const Point &pivot)
{
const Line *l = join_line(a, pivot);
const Circle *c = join_circle(pivot, a);
if (l == nullptr || c == nullptr)
return nullptr;
auto _meet = meet(*l, *c);
assert( _meet.second == nullptr); // again, diameter across circle
return *_meet.first == a ? _meet.second : _meet.first;
}
const Point *Constructor::reflect(const Point &a, const Line &pivot)
{
const Line &p (pivot), // override within_boundary
*l = perpendicular(p, a);
if (l == nullptr)
return nullptr;
const Point *c = meet(p, *l);
if (c == nullptr)
return nullptr;
return reflect(a, *c);
}
const Line *Constructor::reflect(const Line &a, const Point &pivot)
{
const Line &l (a),
*p = perpendicular(l, pivot);
if (p == nullptr)
return nullptr;
const Point *b = reflect(*meet(l, *p), pivot);
if (b == nullptr)
return nullptr;
return perpendicular(*p, *b);
}
const Line *Constructor::reflect(const Line &a, const Line &pivot)
{
// different cases for a and pivot being parallel or not
const Point *vertex = meet(a, pivot), *p1 = nullptr;
if (vertex == nullptr) { // parallel
// find point on pivot
for (auto *p : points)
if (pivot.contains(*p)) { p1 = p; break; }
assert(p1 != nullptr);
// reflect a by p1
return reflect(a, *p1);
}
// not parallel
// find point on a
for (auto *p : points)
if (a.contains(*p) && *p != *vertex) { p1 = p; break; }
assert(p1 != nullptr);
// reflect p1 around pivot
const Point *p = reflect(*p1, pivot);
if (p == nullptr)
return nullptr;
return join_line(*vertex, *p);
}
const Line *Constructor::rotate(const Line &l, const Angle &a, const Point &pivot)
{
// find bisector of angle
const Line *l1 = bisect(a);
assert(l1 != nullptr);
// get parallel of bisector at pivot
l1 = parallel(*l1, pivot);
assert(l1 != nullptr);
// reflect bisector around line
l1 = reflect(*l1, l);
assert(l1 != nullptr);
// then reflect line around new bisector
return reflect(l, *l1);
}
const LineSegment *Constructor::rotate(const LineSegment &l, const Angle &a)
{
// find bisector of angle
const Line *l1 = bisect(a);
if (l1 == nullptr) return nullptr;
// get parallel of bisector at l.start
l1 = parallel(*l1, l.start);
if (l1 == nullptr) return nullptr;
// reflect bisector around segment
l1 = reflect(*l1, l);
if (l1 == nullptr) return nullptr;
// reflect end around new bisector
const Point *end = reflect(l.end, *l1);
if (end == nullptr) return nullptr;
// connect start and end
return join_segment(l.start, *end);
/* Awful previous algorithm:
// - Translate l to the vertex of a, call the new segment l1
const LineSegment *l1 = translate(l, a.vertex);
// - Draw circle with center l1.start and touching l1.end
if (l1 == nullptr)
return nullptr;
const Circle *c = join_circle(l1->start, l1->end);
// - Pick the meets p1 and p2 of the circle with a.l1 and a.l2 that lie in a.region1 and a.region2
auto meet1 = meet(a.l1, *c),
meet2 = meet(a.l2, *c);
assert(meet1.second != nullptr);
assert(meet2.second != nullptr);
const Point *p1 = a.l1.precedes(a.vertex, *meet1.first) == (a.region1 > 0) ? meet1.first : meet1.second,
*p2 = a.l2.precedes(a.vertex, *meet2.first) == (a.region2 > 0) ? meet2.first : meet2.second;
// - Find perpendicular bisector to l1.end and p2
const Line *l2 = bisect(l1->end, *p2);
assert(l2 != nullptr);
// - Reflect p1 around the bisector
const Point *p = reflect(*p1, *l2);
assert(p != nullptr);
// - Connect l1.start with p1 and translate the new line segment back to l.start
const LineSegment *l3 = join_segment(l1->start, *p);
assert(l3 != nullptr);
return translate(*l3, l.start);
*/
}
<commit_msg>Verified more constructor functions<commit_after>#include "include/geom.h"
#include <assert.h>
Constructor::Constructor(MoveListener *listener) :
Scope(listener), angles() {}
Constructor::~Constructor()
{
for (auto *a : angles)
delete a;
}
bool Constructor::contains(const Angle *a) const
{
return a != nullptr &&
std::count_if(angles.begin(), angles.end(), [a](const Angle *p) {return *p == *a; });
}
void Constructor::add(const Angle *a)
{
if (!contains(a))
angles.push_back(a);
}
#define _make_move(movetype, arg1, arg2, res) do { \
if (res != nullptr) { \
Scope::add(res); \
Scope::listener->movetype(arg1, arg2, res); \
}} while (0)
const LineSegment *Constructor::join_segment(const Point &a, const Point &b)
{
if (!Scope::contains(&a) || !Scope::contains(&b) || a == b)
return nullptr;
const LineSegment *res = new LineSegment(a, b);
Scope::add(res);
_make_move(straightedge, &a, &b, res);
return res;
}
const Angle *Constructor::join_angle(const Point &end1, const Point &vertex, const Point &end2)
{
if (!Scope::contains(&end1) || !Scope::contains(&vertex) || !Scope::contains(&end2) ||
vertex == end1 || vertex == end2) // end1 and end2 might be the same in a 0 degree angle
return nullptr;
const Angle *res = new Angle(end1, vertex, end2);
add(res);
if (!Scope::contains(&res->l1)) {
Scope::add(&res->l1);
_make_move(straightedge, &vertex, &end1, &res->l1);
}
if (!Scope::contains(&res->l2)) {
Scope::add(&res->l2);
_make_move(straightedge, &vertex, &end2, &res->l2);
}
return res;
}
#undef _make_move
// only returns nullptr if l or p isn't contained, makes no moves in that case
const Line *Constructor::perpendicular(const Line &l, const Point &p)
{
const Point *o1, *o2;
const Circle *c, *c1, *c2;
if (!Scope::contains(&p) || !Scope::contains(&l))
return nullptr;
// generate two points on the line equidistant from p
o1 = nullptr;
for (auto *p2 : points)
if (l1.contains(*p2) && *p2 != p) { o1 = p2; break; }
assert(o1 != nullptr);
c = join_circle(p, *o1);
assert(c != nullptr); // p != *o1 as generated by the loop
auto pair = meet(l1, *c); // the copy constructor works well with Scope::contains
o2 = *pair.first == *o1 ? pair.second : pair.first;
assert(o2 != nullptr); // l1 goes through the diameter of *c, has two intersections
// create circles from o1 to o2 and from o2 to o1
c1 = join_circle(*o1, *o2);
c2 = join_circle(*o2, *o1);
assert(*c1 != *c2); // o1 and o2 are different
pair = meet(*c1, *c2);
assert(pair.second != nullptr);
// by this assertion, no moves will be made before returning nullptr
return join_line(*pair.first, *pair.second); // two meets have to be different
// the deletion of all these items are to be handled by ~Scope()
}
// only returns nullptr if l or p not contained, makes no moves in that case
const Line *Constructor::parallel(const Line &l, const Point &p)
{
if (l.contains(p))
return &l;
auto perp = perpendicular(l, p);
if (perp == nullptr)
return nullptr;
return perpendicular(*perp, p);
}
// returns nullptr if l or start not contained, returns l if l.start == start, makes no moves in those cases
const LineSegment *Constructor::translate(const LineSegment &l, const Point &start)
{
const Line *par, *diff, *diff1;
const Point *end;
const LineSegment *res;
par = parallel(l, start);
if (par == nullptr) // l or start isn't added
return nullptr;
diff = join_line(l.start, start);
if (diff == nullptr) // fails if l.start == start
return &l;
diff1 = parallel(*diff, l.end);
assert(diff1 != nullptr);
end = meet(*par, *diff1);
assert(end != nullptr); // TODO move these assertions to Scope
return join_segment(start, *end);
}
#define _ratio(l1, l2) ((l1).x_coeff == 0) ? sgn((l1).y_coeff * (l2).y_coeff) : sgn((l1).x_coeff * (l2).x_coeff)
// only returns nullptr if a or p isn't contained, makes no moves
const Angle *Constructor::translate(const Angle &a, const Point &p)
{
const Line *l1 = parallel(a.l1, p),
*l2 = parallel(a.l2, p);
if (l1 == nullptr || l2 == nullptr)
return nullptr;
// the sign of the ratio of nonconstant coefficients for l1 and l2
int r1 = _ratio(a.l1, *l1),
r2 = _ratio(a.l2, *l2);
// necessary for the construction of angle based on lines and regions
// join_angle only makes moves if l1 or l2 isn't contained, which isn't true in this case
const Angle *res = new Angle(*l1, *l2, r1 * a.region1, r2 * a.region2);
add(res);
return res;
}
#undef _ratio
// fails if arguments aren't contained or are the same, makes no moves
const Line *Constructor::bisect(const Point &a, const Point &b)
{
const Circle *c1 = join_circle(a, b),
*c2 = join_circle(b, a);
if (c1 == nullptr || c2 == nullptr) // in which case a != b and c1 != c2
return nullptr;
auto _meet = meet(*c1, *c2);
assert(_meet.second != nullptr);
return join_line(*_meet.first, *_meet.second); // two meets have to be different
}
// same as above
const Line *Constructor::bisect(const LineSegment &l)
{
return bisect(l.start, l.end);
}
// fails if a isn't contained, with no moves, works for the 180 degree case
const Line *Constructor::bisect(const Angle &a)
{
if (!contains(&a))
return nullptr;
// 0 degree angle
if (a.l1 == a.l2 && a.region1 * a.l1.x_coeff == a.region2 * a.l2.x_coeff)
return &a.l1;
// find point on l1 other than vertex
const Point *p1 = nullptr;
for (auto *p : points)
if (a.l1.contains(*p) && *p != a.vertex) { p1 = p; break; }
assert(p1 != nullptr);
// find point on l2 with same region as p1
const Circle *c = join_circle(a.vertex, *p1); // points different
auto _meet = meet(a.l2, *c);
assert(_meet.second != nullptr); // l2 goes through vertex, the center of c
// choose point on l2 on the same side as p1
const Point *p2 = (a.l1.precedes(a.vertex, *p1) ? a.region1 : -a.region1 ==
a.l2.precedes(a.vertex, *_meet.first) ? a.region2 : -a.region2) ? _meet.first : _meet.second;
return bisect(*p1, *p2);
}
// fails if the arguments aren't contained or are the same, with no moves
const Point *Constructor::midpoint(const Point &a, const Point &b)
{
const Line *l1 = join_line(a, b),
*l2 = bisect(a, b);
if (l1 == nullptr || l2 == nullptr)
return nullptr;
return meet(*l1, *l2);
}
// same as above
const Point *Constructor::midpoint(const LineSegment &a)
{
return midpoint(a.start, a.end);
}
// same as above
const Point *Constructor::reflect(const Point &a, const Point &pivot)
{
const Line *l = join_line(a, pivot);
const Circle *c = join_circle(pivot, a);
if (l == nullptr || c == nullptr)
return nullptr;
auto _meet = meet(*l, *c);
assert( _meet.second == nullptr); // again, diameter across circle
return *_meet.first == a ? _meet.second : _meet.first;
}
// only returns nullptr if a or pivot isn't contained, makes no moves in that case
const Point *Constructor::reflect(const Point &a, const Line &pivot)
{
const Line &p (pivot), // override within_boundary
*l = perpendicular(p, a);
if (l == nullptr) // when p or a isn't contained
return nullptr;
const Point *c = meet(p, *l);
assert(c == nullptr); // p and l are both contained and perpendicular to one another
return reflect(a, *c);
}
// returns a if pivot on a, nullptr if either of them isn't contained, makes no moves in those cases
const Line *Constructor::reflect(const Line &a, const Point &pivot)
{
const Line &l (a);
// how would this behave with line segments?
if (l.contains(pivot)) {
add(l);
return l;
}
const Line *p = perpendicular(l, pivot);
if (p == nullptr) // when a or pivot isn't contained
return nullptr;
const Point *b = reflect(*meet(l, *p), pivot);
assert(b != nullptr); // pivot isn't on a
return perpendicular(*p, *b);
}
// returns nullptr if arguments aren't contained, makes no moves
const Line *Constructor::reflect(const Line &a, const Line &pivot)
{
if (!Scope::contains(&a) || !Scope::contains(&pivot))
return nullptr;
// different cases for a and pivot being parallel or not
const Point *vertex = meet(a, pivot), *p1 = nullptr;
if (vertex == nullptr) { // parallel
// find point on pivot
for (auto *p : points)
if (pivot.contains(*p)) { p1 = p; break; }
assert(p1 != nullptr);
// reflect a by p1
return reflect(a, *p1);
}
// not parallel
// find point on a
for (auto *p : points)
if (a.contains(*p) && *p != *vertex) { p1 = p; break; }
assert(p1 != nullptr);
// reflect p1 around pivot
const Point *p = reflect(*p1, pivot);
assert (p != nullptr); // p1 and pivot are contained
return join_line(*vertex, *p);
}
// The following algorithms don't work:
// pivot is assumed to be in the internal region of the angle of rotation
const Line *Constructor::rotate(const Line &l, const Angle &a, const Point &pivot)
{
if (!contains(&a) || !Scope::contains(&l) || !Scope::contains(&pivot))
return nullptr;
// find bisector of angle
const Line *l1 = bisect(a);
assert(l1 != nullptr);
// get parallel of bisector at pivot
l1 = parallel(*l1, pivot);
assert(l1 != nullptr);
// then reflect line around bisector
return reflect(l, *l1);
}
const LineSegment *Constructor::rotate(const LineSegment &l, const Angle &a)
{
if (!Scope::contains(&l) || !contains(&a))
return nullptr;
// find bisector of angle
const Line *l1 = bisect(a);
if (l1 == nullptr) return nullptr;
// get parallel of bisector at l.start
l1 = parallel(*l1, l.start);
if (l1 == nullptr) return nullptr;
// reflect bisector around segment
l1 = reflect(*l1, l);
if (l1 == nullptr) return nullptr;
// reflect end around new bisector
const Point *end = reflect(l.end, *l1);
if (end == nullptr) return nullptr;
// connect start and end
return join_segment(l.start, *end);
/* Awful previous algorithm:
// - Translate l to the vertex of a, call the new segment l1
const LineSegment *l1 = translate(l, a.vertex);
// - Draw circle with center l1.start and touching l1.end
if (l1 == nullptr)
return nullptr;
const Circle *c = join_circle(l1->start, l1->end);
// - Pick the meets p1 and p2 of the circle with a.l1 and a.l2 that lie in a.region1 and a.region2
auto meet1 = meet(a.l1, *c),
meet2 = meet(a.l2, *c);
assert(meet1.second != nullptr);
assert(meet2.second != nullptr);
const Point *p1 = a.l1.precedes(a.vertex, *meet1.first) == (a.region1 > 0) ? meet1.first : meet1.second,
*p2 = a.l2.precedes(a.vertex, *meet2.first) == (a.region2 > 0) ? meet2.first : meet2.second;
// - Find perpendicular bisector to l1.end and p2
const Line *l2 = bisect(l1->end, *p2);
assert(l2 != nullptr);
// - Reflect p1 around the bisector
const Point *p = reflect(*p1, *l2);
assert(p != nullptr);
// - Connect l1.start with p1 and translate the new line segment back to l.start
const LineSegment *l3 = join_segment(l1->start, *p);
assert(l3 != nullptr);
return translate(*l3, l.start);
*/
}
<|endoftext|> |
<commit_before>/**
* @file pointer.hpp
*
* @brief A wrapper class for host and/or device pointers, allowing
* easy access to CUDA's pointer attributes.
*
* @note at the moment, this class is not used by other sections of the API
* wrappers; specifically, freestanding functions and methods returning
* pointers return raw `T*`'s rather than `pointer_t<T>`'s.
* This may change in the future.
*
* @todo Consider allowing for storing attributes within the class,
* lazily (e.g. with an std::optional).
*/
#pragma once
#ifndef CUDA_API_WRAPPERS_POINTER_HPP_
#define CUDA_API_WRAPPERS_POINTER_HPP_
#include <cuda/api/types.hpp>
#include <cuda/api/constants.hpp>
#include <cuda/api/error.hpp>
#include <cuda_runtime_api.h>
#ifndef NDEBUG
#include <cassert>
#endif
#ifndef NDEBUG
#include <cassert>
#endif
#ifndef NDEBUG
#include <cassert>
#endif
namespace cuda {
///@cond
template <bool AssumedCurrent> class device_t;
///@endcond
namespace memory {
/**
* @brief see @ref memory::host, @ref memory::device, @ref memory::managed
*/
enum type_t : std::underlying_type<cudaMemoryType>::type {
host_memory = cudaMemoryTypeHost,
device_memory = cudaMemoryTypeDevice,
#if CUDART_VERSION >= 10000
unregistered_memory = cudaMemoryTypeUnregistered,
managed_memory = cudaMemoryTypeManaged,
#else
unregistered_memory,
managed_memory,
#endif // CUDART_VERSION >= 10000
};
namespace pointer {
struct attributes_t : cudaPointerAttributes {
/**
* @brief indicates a choice memory space, management and access type -
* from among the options in @ref type_t .
*
* @return A value whose semantics are those introduced in CUDA 10.0,
* rather than those of CUDA 9 and earlier, where `type_t::device`
* actually signifies either device-only or `type_t::managed`.
*/
type_t memory_type() const
{
// TODO: For some strange reason, g++ 6.x claims that converting
// to the underlying type is a "narrowing conversion", and doesn't
// like some other conversions I've tried - so let's cast
// more violently instead
// Note: In CUDA v10.0, the semantics changed to what we're supporting
#if CUDART_VERSION >= 10000
return (type_t)cudaPointerAttributes::type;
#else // CUDART_VERSION < 10000
using utype = typename std::underlying_type<cudaMemoryType>::type;
if (((utype) memoryType == utype {type_t::device_memory}) and
cudaPointerAttributes::isManaged) {
return type_t::managed_memory;
}
return (type_t)(memoryType);
#endif // CUDART_VERSION >= 10000
}
};
} // namespace pointer
/**
* A convenience wrapper around a raw pointer "known" to the CUDA runtime
* and which thus has various kinds of associated information which this
* wrapper allows access to.
*/
template <typename T>
class pointer_t {
public: // getters and operators
/**
* @return Address of the pointed-to memory, regardless of which memory
* space it's in and whether or not it is accessible from the host
*/
T* get() const { return ptr_; }
operator T*() const { return ptr_; }
public: // other non-mutators
pointer::attributes_t attributes() const
{
pointer::attributes_t the_attributes;
auto status = cudaPointerGetAttributes (&the_attributes, ptr_);
throw_if_error(status, "Failed obtaining attributes of pointer " + cuda::detail::ptr_as_hex(ptr_));
return the_attributes;
}
device_t<detail::do_not_assume_device_is_current> device() const;
/**
* @returns A pointer into device-accessible memory (not necessary on-device memory though).
* CUDA ensures that, for pointers to memory not accessible on the CUDA device, `nullptr`
* is returned.
*/
T* get_for_device() const { return attributes().devicePointer; }
/**
* @returns A pointer into device-accessible memory (not necessary on-device memory though).
* CUDA ensures that, for pointers to memory not accessible on the CUDA device, `nullptr`
* is returned.
*/
T* get_for_host() const { return attributes().hostPointer; }
/**
* @returns For a mapped-memory pointer, returns the other side of the mapping,
* i.e. if this is the device pointer, returns the host pointer, otherwise
* returns the device pointer. For a managed-memory pointer, returns the
* single pointer usable on both device and host. In other cases returns `nullptr`.
*
* @note this relies on either the device and host pointers being `nullptr` in
* the case of a non-mapped pointer; and on the device and host pointers being
* identical to ptr_ for managed-memory pointers.
*/
pointer_t other_side_of_region_pair() const {
auto attrs = attributes();
#ifndef NDEBUG
assert(attrs.devicePointer == ptr_ or attrs.hostPointer == ptr_);
#endif
return pointer_t { ptr_ == attrs.devicePointer ? attrs.hostPointer : ptr_ };
}
public: // constructors
pointer_t(T* ptr) noexcept : ptr_(ptr) { }
pointer_t(const pointer_t& other) noexcept = default;
pointer_t(pointer_t&& other) noexcept = default;
protected: // data members
T* const ptr_;
};
namespace pointer {
/**
* Wraps an existing pointer in a @ref pointer_t wrapper
*
* @param ptr a pointer - into either device or host memory -
* to be wrapped.
*/
template<typename T>
inline pointer_t<T> wrap(T* ptr) noexcept { return pointer_t<T>(ptr); }
} // namespace pointer
} // namespace memory
} // namespace cuda
#endif /* CUDA_API_WRAPPERS_POINTER_HPP_ */
<commit_msg>Fix Odd Merging from Rebase...<commit_after>/**
* @file pointer.hpp
*
* @brief A wrapper class for host and/or device pointers, allowing
* easy access to CUDA's pointer attributes.
*
* @note at the moment, this class is not used by other sections of the API
* wrappers; specifically, freestanding functions and methods returning
* pointers return raw `T*`'s rather than `pointer_t<T>`'s.
* This may change in the future.
*
* @todo Consider allowing for storing attributes within the class,
* lazily (e.g. with an std::optional).
*/
#pragma once
#ifndef CUDA_API_WRAPPERS_POINTER_HPP_
#define CUDA_API_WRAPPERS_POINTER_HPP_
#include <cuda/api/types.hpp>
#include <cuda/api/constants.hpp>
#include <cuda/api/error.hpp>
#include <cuda_runtime_api.h>
#ifndef NDEBUG
#include <cassert>
#endif
namespace cuda {
///@cond
template <bool AssumedCurrent> class device_t;
///@endcond
namespace memory {
/**
* @brief see @ref memory::host, @ref memory::device, @ref memory::managed
*/
enum type_t : std::underlying_type<cudaMemoryType>::type {
host_memory = cudaMemoryTypeHost,
device_memory = cudaMemoryTypeDevice,
#if CUDART_VERSION >= 10000
unregistered_memory = cudaMemoryTypeUnregistered,
managed_memory = cudaMemoryTypeManaged,
#else
unregistered_memory,
managed_memory,
#endif // CUDART_VERSION >= 10000
};
namespace pointer {
struct attributes_t : cudaPointerAttributes {
/**
* @brief indicates a choice memory space, management and access type -
* from among the options in @ref type_t .
*
* @return A value whose semantics are those introduced in CUDA 10.0,
* rather than those of CUDA 9 and earlier, where `type_t::device`
* actually signifies either device-only or `type_t::managed`.
*/
type_t memory_type() const
{
// TODO: For some strange reason, g++ 6.x claims that converting
// to the underlying type is a "narrowing conversion", and doesn't
// like some other conversions I've tried - so let's cast
// more violently instead
// Note: In CUDA v10.0, the semantics changed to what we're supporting
#if CUDART_VERSION >= 10000
return (type_t)cudaPointerAttributes::type;
#else // CUDART_VERSION < 10000
using utype = typename std::underlying_type<cudaMemoryType>::type;
if (((utype) memoryType == utype {type_t::device_memory}) and
cudaPointerAttributes::isManaged) {
return type_t::managed_memory;
}
return (type_t)(memoryType);
#endif // CUDART_VERSION >= 10000
}
};
} // namespace pointer
/**
* A convenience wrapper around a raw pointer "known" to the CUDA runtime
* and which thus has various kinds of associated information which this
* wrapper allows access to.
*/
template <typename T>
class pointer_t {
public: // getters and operators
/**
* @return Address of the pointed-to memory, regardless of which memory
* space it's in and whether or not it is accessible from the host
*/
T* get() const { return ptr_; }
operator T*() const { return ptr_; }
public: // other non-mutators
pointer::attributes_t attributes() const
{
pointer::attributes_t the_attributes;
auto status = cudaPointerGetAttributes (&the_attributes, ptr_);
throw_if_error(status, "Failed obtaining attributes of pointer " + cuda::detail::ptr_as_hex(ptr_));
return the_attributes;
}
device_t<detail::do_not_assume_device_is_current> device() const;
/**
* @returns A pointer into device-accessible memory (not necessary on-device memory though).
* CUDA ensures that, for pointers to memory not accessible on the CUDA device, `nullptr`
* is returned.
*/
T* get_for_device() const { return attributes().devicePointer; }
/**
* @returns A pointer into device-accessible memory (not necessary on-device memory though).
* CUDA ensures that, for pointers to memory not accessible on the CUDA device, `nullptr`
* is returned.
*/
T* get_for_host() const { return attributes().hostPointer; }
/**
* @returns For a mapped-memory pointer, returns the other side of the mapping,
* i.e. if this is the device pointer, returns the host pointer, otherwise
* returns the device pointer. For a managed-memory pointer, returns the
* single pointer usable on both device and host. In other cases returns `nullptr`.
*
* @note this relies on either the device and host pointers being `nullptr` in
* the case of a non-mapped pointer; and on the device and host pointers being
* identical to ptr_ for managed-memory pointers.
*/
pointer_t other_side_of_region_pair() const {
auto attrs = attributes();
#ifndef NDEBUG
assert(attrs.devicePointer == ptr_ or attrs.hostPointer == ptr_);
#endif
return pointer_t { ptr_ == attrs.devicePointer ? attrs.hostPointer : ptr_ };
}
public: // constructors
pointer_t(T* ptr) noexcept : ptr_(ptr) { }
pointer_t(const pointer_t& other) noexcept = default;
pointer_t(pointer_t&& other) noexcept = default;
protected: // data members
T* const ptr_;
};
namespace pointer {
/**
* Wraps an existing pointer in a @ref pointer_t wrapper
*
* @param ptr a pointer - into either device or host memory -
* to be wrapped.
*/
template<typename T>
inline pointer_t<T> wrap(T* ptr) noexcept { return pointer_t<T>(ptr); }
} // namespace pointer
} // namespace memory
} // namespace cuda
#endif /* CUDA_API_WRAPPERS_POINTER_HPP_ */
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
// mapnik
#include <mapnik/debug.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/config_error.hpp>
#include <mapnik/params.hpp>
#include <mapnik/plugin.hpp>
#include <mapnik/util/fs.hpp>
// boost
#include <boost/filesystem/operations.hpp>
#include <boost/algorithm/string.hpp>
// stl
#include <algorithm>
#include <map>
#include <stdexcept>
namespace mapnik {
extern datasource_ptr create_static_datasource(parameters const& params);
extern std::vector<std::string> get_static_datasource_names();
bool is_input_plugin(std::string const& filename)
{
return boost::algorithm::ends_with(filename,std::string(".input"));
}
datasource_cache::datasource_cache()
{
PluginInfo::init();
}
datasource_cache::~datasource_cache()
{
PluginInfo::exit();
}
datasource_ptr datasource_cache::create(parameters const& params)
{
boost::optional<std::string> type = params.get<std::string>("type");
if ( ! type)
{
throw config_error(std::string("Could not create datasource. Required ") +
"parameter 'type' is missing");
}
datasource_ptr ds;
#ifdef MAPNIK_STATIC_PLUGINS
// return if it's created, raise otherwise
ds = create_static_datasource(params);
if (ds)
{
return ds;
}
#endif
#ifdef MAPNIK_THREADSAFE
mapnik::scoped_lock lock(mutex_);
#endif
std::map<std::string,std::shared_ptr<PluginInfo> >::iterator itr=plugins_.find(*type);
if (itr == plugins_.end())
{
std::string s("Could not create datasource for type: '");
s += *type + "'";
if (plugin_directories_.empty())
{
s += " (no datasource plugin directories have been successfully registered)";
}
else
{
s += " (searched for datasource plugins in '" + plugin_directories() + "')";
}
throw config_error(s);
}
if (! itr->second->valid())
{
throw std::runtime_error(std::string("Cannot load library: ") +
itr->second->get_error());
}
// http://www.mr-edd.co.uk/blog/supressing_gcc_warnings
#ifdef __GNUC__
__extension__
#endif
create_ds* create_datasource = reinterpret_cast<create_ds*>(itr->second->get_symbol("create"));
if (! create_datasource)
{
throw std::runtime_error(std::string("Cannot load symbols: ") +
itr->second->get_error());
}
ds = datasource_ptr(create_datasource(params), datasource_deleter());
#ifdef MAPNIK_LOG
MAPNIK_LOG_DEBUG(datasource_cache)
<< "datasource_cache: Datasource="
<< ds << " type=" << type;
MAPNIK_LOG_DEBUG(datasource_cache)
<< "datasource_cache: Size="
<< params.size();
parameters::const_iterator i = params.begin();
for (; i != params.end(); ++i)
{
MAPNIK_LOG_DEBUG(datasource_cache)
<< "datasource_cache: -- "
<< i->first << "=" << i->second;
}
#endif
return ds;
}
std::string datasource_cache::plugin_directories()
{
return boost::algorithm::join(plugin_directories_,", ");
}
std::vector<std::string> datasource_cache::plugin_names()
{
std::vector<std::string> names;
#ifdef MAPNIK_STATIC_PLUGINS
names = get_static_datasource_names();
#endif
std::map<std::string,std::shared_ptr<PluginInfo> >::const_iterator itr;
for (itr = plugins_.begin(); itr != plugins_.end(); ++itr)
{
names.push_back(itr->first);
}
return names;
}
void datasource_cache::register_datasources(std::string const& str)
{
#ifdef MAPNIK_THREADSAFE
mapnik::scoped_lock lock(mutex_);
#endif
plugin_directories_.insert(str);
if (mapnik::util::exists(str) && mapnik::util::is_directory(str))
{
boost::filesystem::directory_iterator end_itr;
for (boost::filesystem::directory_iterator itr(str); itr != end_itr; ++itr )
{
#if (BOOST_FILESYSTEM_VERSION == 3)
if (!boost::filesystem::is_directory(*itr) && is_input_plugin(itr->path().filename().string()))
#else // v2
if (!boost::filesystem::is_directory(*itr) && is_input_plugin(itr->path().leaf()))
#endif
{
#if (BOOST_FILESYSTEM_VERSION == 3)
if (register_datasource(itr->path().string()))
#else // v2
if (register_datasource(itr->string()))
#endif
{
registered_ = true;
}
}
}
}
}
bool datasource_cache::register_datasource(std::string const& filename)
{
try
{
if (!mapnik::util::exists(filename))
{
MAPNIK_LOG_ERROR(datasource_cache)
<< "Cannot load '"
<< filename << "' (plugin does not exist)";
return false;
}
std::shared_ptr<PluginInfo> plugin = std::make_shared<PluginInfo>(filename,"datasource_name");
if (plugin->valid())
{
if (plugin->name().empty())
{
MAPNIK_LOG_ERROR(datasource_cache)
<< "Problem loading plugin library '"
<< filename << "' (plugin is lacking compatible interface)";
}
else
{
plugins_.insert(std::make_pair(plugin->name(),plugin));
MAPNIK_LOG_DEBUG(datasource_cache)
<< "datasource_cache: Registered="
<< plugin->name();
return true;
}
}
else
{
MAPNIK_LOG_ERROR(datasource_cache)
<< "Problem loading plugin library: "
<< filename << " (dlopen failed - plugin likely has an unsatisfied dependency or incompatible ABI)";
}
}
catch (std::exception const& ex)
{
MAPNIK_LOG_ERROR(datasource_cache)
<< "Exception caught while loading plugin library: "
<< filename << " (" << ex.what() << ")";
}
return false;
}
}
<commit_msg>only return true if plugins are actually newly registered<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
// mapnik
#include <mapnik/debug.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/config_error.hpp>
#include <mapnik/params.hpp>
#include <mapnik/plugin.hpp>
#include <mapnik/util/fs.hpp>
// boost
#include <boost/filesystem/operations.hpp>
#include <boost/algorithm/string.hpp>
// stl
#include <algorithm>
#include <map>
#include <stdexcept>
namespace mapnik {
extern datasource_ptr create_static_datasource(parameters const& params);
extern std::vector<std::string> get_static_datasource_names();
bool is_input_plugin(std::string const& filename)
{
return boost::algorithm::ends_with(filename,std::string(".input"));
}
datasource_cache::datasource_cache()
{
PluginInfo::init();
}
datasource_cache::~datasource_cache()
{
PluginInfo::exit();
}
datasource_ptr datasource_cache::create(parameters const& params)
{
boost::optional<std::string> type = params.get<std::string>("type");
if ( ! type)
{
throw config_error(std::string("Could not create datasource. Required ") +
"parameter 'type' is missing");
}
datasource_ptr ds;
#ifdef MAPNIK_STATIC_PLUGINS
// return if it's created, raise otherwise
ds = create_static_datasource(params);
if (ds)
{
return ds;
}
#endif
#ifdef MAPNIK_THREADSAFE
mapnik::scoped_lock lock(mutex_);
#endif
std::map<std::string,std::shared_ptr<PluginInfo> >::iterator itr=plugins_.find(*type);
if (itr == plugins_.end())
{
std::string s("Could not create datasource for type: '");
s += *type + "'";
if (plugin_directories_.empty())
{
s += " (no datasource plugin directories have been successfully registered)";
}
else
{
s += " (searched for datasource plugins in '" + plugin_directories() + "')";
}
throw config_error(s);
}
if (! itr->second->valid())
{
throw std::runtime_error(std::string("Cannot load library: ") +
itr->second->get_error());
}
// http://www.mr-edd.co.uk/blog/supressing_gcc_warnings
#ifdef __GNUC__
__extension__
#endif
create_ds* create_datasource = reinterpret_cast<create_ds*>(itr->second->get_symbol("create"));
if (! create_datasource)
{
throw std::runtime_error(std::string("Cannot load symbols: ") +
itr->second->get_error());
}
ds = datasource_ptr(create_datasource(params), datasource_deleter());
#ifdef MAPNIK_LOG
MAPNIK_LOG_DEBUG(datasource_cache)
<< "datasource_cache: Datasource="
<< ds << " type=" << type;
MAPNIK_LOG_DEBUG(datasource_cache)
<< "datasource_cache: Size="
<< params.size();
parameters::const_iterator i = params.begin();
for (; i != params.end(); ++i)
{
MAPNIK_LOG_DEBUG(datasource_cache)
<< "datasource_cache: -- "
<< i->first << "=" << i->second;
}
#endif
return ds;
}
std::string datasource_cache::plugin_directories()
{
return boost::algorithm::join(plugin_directories_,", ");
}
std::vector<std::string> datasource_cache::plugin_names()
{
std::vector<std::string> names;
#ifdef MAPNIK_STATIC_PLUGINS
names = get_static_datasource_names();
#endif
std::map<std::string,std::shared_ptr<PluginInfo> >::const_iterator itr;
for (itr = plugins_.begin(); itr != plugins_.end(); ++itr)
{
names.push_back(itr->first);
}
return names;
}
void datasource_cache::register_datasources(std::string const& str)
{
#ifdef MAPNIK_THREADSAFE
mapnik::scoped_lock lock(mutex_);
#endif
plugin_directories_.insert(str);
if (mapnik::util::exists(str) && mapnik::util::is_directory(str))
{
boost::filesystem::directory_iterator end_itr;
for (boost::filesystem::directory_iterator itr(str); itr != end_itr; ++itr )
{
#if (BOOST_FILESYSTEM_VERSION == 3)
if (!boost::filesystem::is_directory(*itr) && is_input_plugin(itr->path().filename().string()))
#else // v2
if (!boost::filesystem::is_directory(*itr) && is_input_plugin(itr->path().leaf()))
#endif
{
#if (BOOST_FILESYSTEM_VERSION == 3)
if (register_datasource(itr->path().string()))
#else // v2
if (register_datasource(itr->string()))
#endif
{
registered_ = true;
}
}
}
}
}
bool datasource_cache::register_datasource(std::string const& filename)
{
try
{
if (!mapnik::util::exists(filename))
{
MAPNIK_LOG_ERROR(datasource_cache)
<< "Cannot load '"
<< filename << "' (plugin does not exist)";
return false;
}
std::shared_ptr<PluginInfo> plugin = std::make_shared<PluginInfo>(filename,"datasource_name");
if (plugin->valid())
{
if (plugin->name().empty())
{
MAPNIK_LOG_ERROR(datasource_cache)
<< "Problem loading plugin library '"
<< filename << "' (plugin is lacking compatible interface)";
}
else
{
if (plugins_.insert(std::make_pair(plugin->name(),plugin)).second)
{
MAPNIK_LOG_ERROR(datasource_cache)
<< "datasource_cache: Registered="
<< plugin->name();
return true;
}
}
}
else
{
MAPNIK_LOG_ERROR(datasource_cache)
<< "Problem loading plugin library: "
<< filename << " (dlopen failed - plugin likely has an unsatisfied dependency or incompatible ABI)";
}
}
catch (std::exception const& ex)
{
MAPNIK_LOG_ERROR(datasource_cache)
<< "Exception caught while loading plugin library: "
<< filename << " (" << ex.what() << ")";
}
return false;
}
}
<|endoftext|> |
<commit_before>#include <debug.hpp>
#include <itemsForm.hpp>
#include <string>
ItemForm::ItemForm(void) {
// TODO: Load this list from some default settings or leave empty
Item* item1 = new Item("Item #1", 1, 1, Item::GRAM);
Item* item25 = new Item("Item #25", 25, 25, Item::PIECE);
Item* item125 = new Item("Item #125", 125, 125, Item::PIECE);
Food* food1 = new Food("Food #1", 1, 1, Item::GRAM, 1, 1, 1, 1);
Food* food25 = new Food("Food #25", 25, 25, Item::PIECE, 25, 25, 25, 25);
Food* food125 = new Food("Food #125", 125, 125, Item::PIECE, 125, 125, 125, 125);
Dish* dish1 = new Dish("Dish #1", food1, food1->getMass(), 1);
Dish* dish25 = new Dish("Dish #25", food25, food25->getMass(), 1);
Dish* dish125 = new Dish("Dish #125", food125, food125->getMass(), 1);
avaliableItems.push_back(item1);
item1->addItemList(&avaliableItems);
avaliableItems.push_back(item25);
item25->addItemList(&avaliableItems);
avaliableItems.push_back(item125);
item125->addItemList(&avaliableItems);
avaliableItems.push_back(food1);
food1->addItemList(&avaliableItems);
avaliableItems.push_back(food25);
food25->addItemList(&avaliableItems);
avaliableItems.push_back(food125);
food125->addItemList(&avaliableItems);
avaliableDish.push_back(dish1);
dish1->addDishList(&avaliableDish);
avaliableDish.push_back(dish25);
dish25->addDishList(&avaliableDish);
avaliableDish.push_back(dish125);
dish125->addDishList(&avaliableDish);
PRINT_OBJ("ItemForm created");
}
ItemForm::~ItemForm(void) {
for ( auto& entry: avaliableItems ) {
delete entry;
}
PRINT_OBJ("ItemForm destroyed");
}
<commit_msg>itemsForm: Avoid removing items from list while moving in this list<commit_after>#include <debug.hpp>
#include <itemsForm.hpp>
#include <string>
ItemForm::ItemForm(void) {
// TODO: Load this list from some default settings or leave empty
Item* item1 = new Item("Item #1", 1, 1, Item::GRAM);
Item* item25 = new Item("Item #25", 25, 25, Item::PIECE);
Item* item125 = new Item("Item #125", 125, 125, Item::PIECE);
Food* food1 = new Food("Food #1", 1, 1, Item::GRAM, 1, 1, 1, 1);
Food* food25 = new Food("Food #25", 25, 25, Item::PIECE, 25, 25, 25, 25);
Food* food125 = new Food("Food #125", 125, 125, Item::PIECE, 125, 125, 125, 125);
Dish* dish1 = new Dish("Dish #1", food1, food1->getMass(), 1);
Dish* dish25 = new Dish("Dish #25", food25, food25->getMass(), 1);
Dish* dish125 = new Dish("Dish #125", food125, food125->getMass(), 1);
avaliableItems.push_back(item1);
item1->addItemList(&avaliableItems);
avaliableItems.push_back(item25);
item25->addItemList(&avaliableItems);
avaliableItems.push_back(item125);
item125->addItemList(&avaliableItems);
avaliableItems.push_back(food1);
food1->addItemList(&avaliableItems);
avaliableItems.push_back(food25);
food25->addItemList(&avaliableItems);
avaliableItems.push_back(food125);
food125->addItemList(&avaliableItems);
avaliableDish.push_back(dish1);
dish1->addDishList(&avaliableDish);
avaliableDish.push_back(dish25);
dish25->addDishList(&avaliableDish);
avaliableDish.push_back(dish125);
dish125->addDishList(&avaliableDish);
PRINT_OBJ("ItemForm created");
}
ItemForm::~ItemForm(void) {
for ( std::list<Item*>::iterator it = avaliableItems.begin(); it != avaliableItems.end(); ) {
std::list<Item*>::iterator oldit = it++;
delete *oldit;
}
PRINT_OBJ("ItemForm destroyed");
}
<|endoftext|> |
<commit_before>/**
* \file
* \remark This file is part of VITA.
*
* \copyright Copyright (C) 2011-2014 EOS di Manlio Morini.
*
* \license
* 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/
*/
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <memory>
#include "kernel/evolution.h"
#include "kernel/i_mep.h"
#include "kernel/terminal.h"
#include "kernel/src/primitive/factory.h"
using i_interp = vita::core_interpreter;
// This class models the first input.
class X : public vita::terminal
{
public:
X() : vita::terminal("X", 0) { input_ = true; }
virtual vita::any eval(i_interp *) const override { return vita::any(val); }
static double val;
};
class Y : public vita::terminal
{
public:
Y() : vita::terminal("Y", 0) { input_ = true; }
virtual vita::any eval(i_interp *) const override { return vita::any(val); }
static double val;
};
class Z : public vita::terminal
{
public:
Z() : vita::terminal("Z", 0) { input_ = true; }
virtual vita::any eval(i_interp *) const override { return vita::any(val); }
static double val;
};
double X::val;
double Y::val;
double Z::val;
class my_evaluator : public vita::evaluator<vita::i_mep>
{
vita::fitness_t operator()(const vita::i_mep &ind)
{
vita::interpreter<vita::i_mep> agent(&ind);
vita::fitness_t::value_type fit(0.0);
for (double x(0); x < 10; ++x)
for (double y(0); y < 10; ++y)
for (double z(0); z < 10; ++z)
{
X::val = x;
Y::val = y;
Z::val = z;
const vita::any res(agent.run());
if (!res.empty())
{
const auto dres(vita::any_cast<double>(res));
assert(std::isfinite(dres));
fit += std::exp(-std::fabs(dres - (x*x + y*y - z*z)));
}
}
return {fit};
}
};
int main(int argc, char *argv[])
{
vita::environment env(true);
env.individuals = static_cast<unsigned>(argc > 1 ? std::atoi(argv[1]) : 100);
env.code_length = static_cast<unsigned>(argc > 2 ? std::atoi(argv[2]) : 100);
env.generations = static_cast<unsigned>(argc > 3 ? std::atoi(argv[3]) : 100);
vita::symbol_set sset;
vita::symbol_factory &factory(vita::symbol_factory::instance());
sset.insert(vita::make_unique<X>());
sset.insert(vita::make_unique<Y>());
sset.insert(vita::make_unique<Z>());
sset.insert(factory.make("FADD"));
sset.insert(factory.make("FSUB"));
sset.insert(factory.make("FMUL"));
sset.insert(factory.make("FIFL"));
sset.insert(factory.make("FIFE"));
auto eva(vita::make_unique<my_evaluator>());
vita::evolution<vita::i_mep, vita::std_es> evo(env, sset, *eva.get());
evo.run(1);
return EXIT_SUCCESS;
}
<commit_msg>[FIX] Compilation error for example6.cc<commit_after>/**
* \file
* \remark This file is part of VITA.
*
* \copyright Copyright (C) 2011-2014 EOS di Manlio Morini.
*
* \license
* 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/
*/
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <memory>
#include "kernel/evolution.h"
#include "kernel/i_mep.h"
#include "kernel/terminal.h"
#include "kernel/src/primitive/factory.h"
using i_interp = vita::core_interpreter;
// This class models the first input.
class X : public vita::terminal
{
public:
X() : vita::terminal("X", 0) {}
virtual bool input() const override { return true; }
virtual vita::any eval(i_interp *) const override { return vita::any(val); }
static double val;
};
class Y : public vita::terminal
{
public:
Y() : vita::terminal("Y", 0) {}
virtual bool input() const override { return true; }
virtual vita::any eval(i_interp *) const override { return vita::any(val); }
static double val;
};
class Z : public vita::terminal
{
public:
Z() : vita::terminal("Z", 0) {}
virtual bool input() const override { return true; }
virtual vita::any eval(i_interp *) const override { return vita::any(val); }
static double val;
};
double X::val;
double Y::val;
double Z::val;
class my_evaluator : public vita::evaluator<vita::i_mep>
{
vita::fitness_t operator()(const vita::i_mep &ind)
{
vita::interpreter<vita::i_mep> agent(&ind);
vita::fitness_t::value_type fit(0.0);
for (double x(0); x < 10; ++x)
for (double y(0); y < 10; ++y)
for (double z(0); z < 10; ++z)
{
X::val = x;
Y::val = y;
Z::val = z;
const vita::any res(agent.run());
if (!res.empty())
{
const auto dres(vita::any_cast<double>(res));
assert(std::isfinite(dres));
fit += std::exp(-std::fabs(dres - (x*x + y*y - z*z)));
}
}
return {fit};
}
};
int main(int argc, char *argv[])
{
vita::environment env(true);
env.individuals = static_cast<unsigned>(argc > 1 ? std::atoi(argv[1]) : 100);
env.code_length = static_cast<unsigned>(argc > 2 ? std::atoi(argv[2]) : 100);
env.generations = static_cast<unsigned>(argc > 3 ? std::atoi(argv[3]) : 100);
vita::symbol_set sset;
vita::symbol_factory &factory(vita::symbol_factory::instance());
sset.insert(vita::make_unique<X>());
sset.insert(vita::make_unique<Y>());
sset.insert(vita::make_unique<Z>());
sset.insert(factory.make("FADD"));
sset.insert(factory.make("FSUB"));
sset.insert(factory.make("FMUL"));
sset.insert(factory.make("FIFL"));
sset.insert(factory.make("FIFE"));
auto eva(vita::make_unique<my_evaluator>());
vita::evolution<vita::i_mep, vita::std_es> evo(env, sset, *eva.get());
evo.run(1);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
* FastRPC -- Fast RPC library compatible with XML-RPC
* Copyright (C) 2005-7 Seznam.cz, a.s.
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Seznam.cz, a.s.
* Radlicka 2, Praha 5, 15000, Czech Republic
* http://www.seznam.cz, mailto:fastrpc@firma.seznam.cz
*
* FILE $Id: frpcxmlmarshaller.cc,v 1.6 2007-05-22 13:03:23 mirecta Exp $
*
* DESCRIPTION
*
* AUTHOR
* Miroslav Talasek <miroslav.talasek@firma.seznam.cz>
*
* HISTORY
*
*/
#include "frpcxmlmarshaller.h"
#include <string.h>
#include <stdio.h>
#include <frpclenerror.h>
#include <frpc.h>
#include <sstream>
namespace FRPC {
XmlMarshaller_t::XmlMarshaller_t(Writer_t &writer,
const ProtocolVersion_t &protocolVersion)
:writer(writer),level(0),protocolVersion(protocolVersion) {
if (protocolVersion.versionMajor > FRPC_MAJOR_VERSION) {
throw Error_t("Not supported protocol version");
}
}
XmlMarshaller_t::~XmlMarshaller_t() {
entityStorage.clear();
}
void XmlMarshaller_t::packArray(unsigned int numOfItems) {
//write correct spaces
packSpaces(level);
if (entityStorage.empty()) {
writer.write("<param>\n",8);
level++;
}
packSpaces(level);
//write array tag
writer.write("<value>\n",8);
level++;
packSpaces(level);
writer.write("<array>\n",8);
level++;
//write correct spaces
packSpaces(level);
//write array tag
writer.write("<data>\n",7);
level++;
if (numOfItems == 0) {
level--;
writer.write("</data>\n",8);
level--;
writer.write("</array>\n",9);
level--;
writer.write("</value>\n",9);
if ( entityStorage.size() == 0)
writer.write("</param>\n",9);
decrementItem();
} else {
//entity to storage
entityStorage.push_back(TypeStorage_t(ARRAY,numOfItems));
}
}
void XmlMarshaller_t::packBinary(const char* value, unsigned int size) {
//write correct spaces
packSpaces(level);
if (entityStorage.empty()) {
writer.write("<param>\n",8);
level++;
}
//write correct spaces
packSpaces(level);
//write tags
writer.write("<value><base64>",15);
//write value base64
//writer.write(value,size);
writeEncodeBase64(value, size);
//write tags
writer.write("</base64></value>\n",18);
if (entityStorage.empty()) {
packSpaces(level - 1);
writer.write("</param>\n",9);
level--;
}
decrementItem();
}
void XmlMarshaller_t::packBool(bool value) {
char boolean = (value==true)?'1':'0';
//write correct spaces
packSpaces(level);
if (entityStorage.empty()) {
writer.write("<param>\n",8);
level++;
}
//write correct spaces
packSpaces(level);
writer.write("<value><boolean>",16);
writer.write(&boolean,1);
writer.write("</boolean></value>\n",19);
if (entityStorage.empty()) {
packSpaces(level - 1);
writer.write("</param>\n",9);
level--;
}
decrementItem();
}
void XmlMarshaller_t::packDateTime(short year, char month, char day, char hour, char minute, char sec,
char weekDay, time_t unixTime, char timeZone) {
std::string data = getISODateTime(year,month,day,hour,minute,sec,timeZone);
//write correct spaces
packSpaces(level);
if (entityStorage.empty()) {
writer.write("<param>\n",8);
level++;
}
//write correct spaces
packSpaces(level);
writer.write("<value><dateTime.iso8601>",25);
writer.write(data.data(),data.size());
writer.write("</dateTime.iso8601></value>\n",28);
if (entityStorage.empty()) {
packSpaces(level - 1);
writer.write("</param>\n",9);
level--;
}
decrementItem();
}
void XmlMarshaller_t::packDouble(double value) {
char buff[50];
sprintf(buff,"%f",value);
//write correct spaces
packSpaces(level);
if (entityStorage.empty()) {
writer.write("<param>\n",8);
level++;
}
//write correct spaces
packSpaces(level);
writer.write("<value><double>",15);
writer.write(buff,strlen(buff));
writer.write("</double></value>\n",18);
if (entityStorage.empty()) {
packSpaces(level - 1);
writer.write("</param>\n",9);
level--;
}
decrementItem();
}
void XmlMarshaller_t::packFault(int errNumber, const char* errMsg, unsigned int size) {
//magic
packMagic();
writer.write("<methodResponse>\n",17);
level++;
//tag fault
packSpaces(level);
writer.write("<fault>\n",8);
level++;
entityStorage.push_back(TypeStorage_t(FAULT,0));
packStruct(2);
packStructMember("faultCode",9);
packInt(errNumber);
packStructMember("faultString",11);
packString(errMsg,size);
packSpaces(level - 1);
writer.write("</fault>\n",9);
level--;
packSpaces(level - 1);
writer.write("</methodResponse>\n",18);
mainType = FAULT;
}
void XmlMarshaller_t::packInt(Int_t::value_type value) {
std::ostringstream buff;
buff << value;
//write correct spaces
packSpaces(level);
if (entityStorage.empty()) {
writer.write("<param>\n",8);
level++;
}
//write correct spaces
packSpaces(level);
Int_t::value_type absValue = value < 0 ? -value :value;
if ((absValue & INT31_MASK)) {
if (protocolVersion.versionMajor < 2)
throw StreamError_t("Number is too big for protocol version 1.0");
writer.write("<value><i8>",11);
writer.write(buff.str().data(),buff.str().size());
writer.write("</i8></value>\n",14);
} else {
writer.write("<value><i4>",11);
writer.write(buff.str().data(),buff.str().size());
writer.write("</i4></value>\n",14);
}
if (entityStorage.empty()) {
packSpaces(level - 1);
writer.write("</param>\n",9);
level--;
}
decrementItem();
}
void XmlMarshaller_t::packMethodCall(const char* methodName, unsigned int size) {
if (size > 255 || size == 0)
throw LenError_t("Lenght of method name is %d not in interval (1-255)",size);
//pack MAgic header
packMagic();
writer.write("<methodCall>\n",13);
level++;
packSpaces(level);
writer.write("<methodName>",12);
writeQuotedString(methodName,size);
//writer.write(methodName,nameSize);
writer.write("</methodName>\n",14);
writer.write("<params>\n",9);
level++;
mainType = METHOD_CALL;
}
void XmlMarshaller_t::packMethodResponse() {
packMagic();
writer.write("<methodResponse>\n",17);
level++;
packSpaces(level);
writer.write("<params>\n",9);
level++;
mainType = METHOD_RESPONSE;
}
void XmlMarshaller_t::packString(const char* value, unsigned int size) {
//write correct spaces
packSpaces(level);
if (entityStorage.empty()) {
writer.write("<param>\n",8);
level++;
}
//write correct spaces
packSpaces(level);
//write tags
writer.write("<value><string>",15);
//write value
writeQuotedString(value,size);
//writer.write(value,strSize);
//write tags
writer.write("</string></value>\n",18);
if (entityStorage.empty()) {
packSpaces(level - 1);
writer.write("</param>\n",9);
level--;
}
decrementItem();
}
void XmlMarshaller_t::packStruct(unsigned int numOfMembers) {
//write correct spaces
packSpaces(level);
if (entityStorage.empty()) {
writer.write("<param>\n",8);
level++;
}
packSpaces(level);
//write array tag
writer.write("<value>\n",8);
level++;
packSpaces(level);
writer.write("<struct>\n",9);
level++;
if (numOfMembers == 0) {
level--;
writer.write("</struct>\n",10);
level--;
writer.write("</value>\n",9);
if ( entityStorage.size() == 0)
writer.write("</param>\n",9);
decrementItem();
} else {
//entity to storage
entityStorage.push_back(TypeStorage_t(STRUCT,numOfMembers));
}
}
void XmlMarshaller_t::packStructMember(const char* memberName, unsigned int size) {
if (size > 255 || size == 0)
throw LenError_t("Lenght of member name is %d not in interval (1-255)",size);
packSpaces(level);
writer.write("<member>\n",9);
level++;
packSpaces(level);
writer.write("<name>",6);
writeQuotedString(memberName,size);
//writer.write(memberName,nameSize);
writer.write("</name>\n",8);
}
void XmlMarshaller_t::flush() {
switch (mainType) {
case METHOD_CALL:
packSpaces(level-1);
writer.write("</params>\n",10);
level--;
packSpaces(level-1);
writer.write("</methodCall>\n",14);
break;
case METHOD_RESPONSE:
packSpaces(level-1);
writer.write("</params>\n",10);
level--;
packSpaces(level-1);
writer.write("</methodResponse>\n",18);
break;
}
writer.flush();
level = 0;
entityStorage.clear();
}
void XmlMarshaller_t::packMagic() {
if (protocolVersion.versionMajor < 2) {
char magic[]="<?xml version=\"1.0\"?>\n";
//write magic
writer.write(magic,strlen(magic));
} else {
char magic[]="<?xml version=\"1.0\" protocolVersion=\"2.0\"?>\n";
//write magic
writer.write(magic,strlen(magic));
}
}
void XmlMarshaller_t::writeEncodeBase64(const char *data, unsigned int len) {
static const char table[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string src(data,len);
if (src.empty()) {
return ;
}
size_t lineLen = 0;
std::string::const_iterator end = src.end();
for (std::string::const_iterator isrc = src.begin();
isrc != end; ) {
unsigned char input[3];
int n = 0;
for (; (isrc != end) && (n < 3) ; isrc++, n++)
input[n] = *isrc;
if (n) {
writer.write(&table[input[0] >> 2],1);
writer.write(&table[((input[0] & 0x03) << 4) | (input[1] >> 4)],1);
if (n > 1)
writer.write(&table[((input[1] & 0x0F) << 2) | (input[2] >> 6)],1);
else
writer.write("=",1);
if (n > 2)
writer.write(&table[input[2] & 0x3F],1);
else
writer.write("=",1);
lineLen += 4;
if (lineLen > 72) {
writer.write("\r\n",2);
lineLen = 0;
}
}
}
if (lineLen) {
writer.write("\r\n",2);
lineLen = 0;
}
return ;
}
void XmlMarshaller_t::writeQuotedString(const char *data, unsigned int len) {
for (unsigned int i = 0; i < len; i++) {
switch (data[i]) {
case '<':
writer.write("<",4);
break;
case '>':
writer.write(">",4);
break;
case '"':
writer.write(""",6);
break;
case '&':
writer.write("&",5);
break;
default:
writer.write(&data[i],1);
break;
}
}
}
};
<commit_msg>version control<commit_after>/*
* FastRPC -- Fast RPC library compatible with XML-RPC
* Copyright (C) 2005-7 Seznam.cz, a.s.
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Seznam.cz, a.s.
* Radlicka 2, Praha 5, 15000, Czech Republic
* http://www.seznam.cz, mailto:fastrpc@firma.seznam.cz
*
* FILE $Id: frpcxmlmarshaller.cc,v 1.7 2007-05-22 13:12:52 mirecta Exp $
*
* DESCRIPTION
*
* AUTHOR
* Miroslav Talasek <miroslav.talasek@firma.seznam.cz>
*
* HISTORY
*
*/
#include "frpcxmlmarshaller.h"
#include <string.h>
#include <stdio.h>
#include <frpclenerror.h>
#include <frpc.h>
#include <sstream>
namespace FRPC {
XmlMarshaller_t::XmlMarshaller_t(Writer_t &writer,
const ProtocolVersion_t &protocolVersion)
:writer(writer),level(0),protocolVersion(protocolVersion) {
if (protocolVersion.versionMajor > FRPC_MAJOR_VERSION) {
throw Error_t("Not supported protocol version");
}
}
XmlMarshaller_t::~XmlMarshaller_t() {
entityStorage.clear();
}
void XmlMarshaller_t::packArray(unsigned int numOfItems) {
//write correct spaces
packSpaces(level);
if (entityStorage.empty()) {
writer.write("<param>\n",8);
level++;
}
packSpaces(level);
//write array tag
writer.write("<value>\n",8);
level++;
packSpaces(level);
writer.write("<array>\n",8);
level++;
//write correct spaces
packSpaces(level);
//write array tag
writer.write("<data>\n",7);
level++;
if (numOfItems == 0) {
level--;
writer.write("</data>\n",8);
level--;
writer.write("</array>\n",9);
level--;
writer.write("</value>\n",9);
if ( entityStorage.size() == 0)
writer.write("</param>\n",9);
decrementItem();
} else {
//entity to storage
entityStorage.push_back(TypeStorage_t(ARRAY,numOfItems));
}
}
void XmlMarshaller_t::packBinary(const char* value, unsigned int size) {
//write correct spaces
packSpaces(level);
if (entityStorage.empty()) {
writer.write("<param>\n",8);
level++;
}
//write correct spaces
packSpaces(level);
//write tags
writer.write("<value><base64>",15);
//write value base64
//writer.write(value,size);
writeEncodeBase64(value, size);
//write tags
writer.write("</base64></value>\n",18);
if (entityStorage.empty()) {
packSpaces(level - 1);
writer.write("</param>\n",9);
level--;
}
decrementItem();
}
void XmlMarshaller_t::packBool(bool value) {
char boolean = (value==true)?'1':'0';
//write correct spaces
packSpaces(level);
if (entityStorage.empty()) {
writer.write("<param>\n",8);
level++;
}
//write correct spaces
packSpaces(level);
writer.write("<value><boolean>",16);
writer.write(&boolean,1);
writer.write("</boolean></value>\n",19);
if (entityStorage.empty()) {
packSpaces(level - 1);
writer.write("</param>\n",9);
level--;
}
decrementItem();
}
void XmlMarshaller_t::packDateTime(short year, char month, char day, char hour, char minute, char sec,
char weekDay, time_t unixTime, char timeZone) {
std::string data = getISODateTime(year,month,day,hour,minute,sec,timeZone);
//write correct spaces
packSpaces(level);
if (entityStorage.empty()) {
writer.write("<param>\n",8);
level++;
}
//write correct spaces
packSpaces(level);
writer.write("<value><dateTime.iso8601>",25);
writer.write(data.data(),data.size());
writer.write("</dateTime.iso8601></value>\n",28);
if (entityStorage.empty()) {
packSpaces(level - 1);
writer.write("</param>\n",9);
level--;
}
decrementItem();
}
void XmlMarshaller_t::packDouble(double value) {
char buff[50];
sprintf(buff,"%f",value);
//write correct spaces
packSpaces(level);
if (entityStorage.empty()) {
writer.write("<param>\n",8);
level++;
}
//write correct spaces
packSpaces(level);
writer.write("<value><double>",15);
writer.write(buff,strlen(buff));
writer.write("</double></value>\n",18);
if (entityStorage.empty()) {
packSpaces(level - 1);
writer.write("</param>\n",9);
level--;
}
decrementItem();
}
void XmlMarshaller_t::packFault(int errNumber, const char* errMsg, unsigned int size) {
//magic
packMagic();
writer.write("<methodResponse>\n",17);
level++;
//tag fault
packSpaces(level);
writer.write("<fault>\n",8);
level++;
entityStorage.push_back(TypeStorage_t(FAULT,0));
packStruct(2);
packStructMember("faultCode",9);
packInt(errNumber);
packStructMember("faultString",11);
packString(errMsg,size);
packSpaces(level - 1);
writer.write("</fault>\n",9);
level--;
packSpaces(level - 1);
writer.write("</methodResponse>\n",18);
mainType = FAULT;
}
void XmlMarshaller_t::packInt(Int_t::value_type value) {
std::ostringstream buff;
buff << value;
//write correct spaces
packSpaces(level);
if (entityStorage.empty()) {
writer.write("<param>\n",8);
level++;
}
//write correct spaces
packSpaces(level);
Int_t::value_type absValue = value < 0 ? -value :value;
if ((absValue & INT31_MASK)) {
if (protocolVersion.versionMajor < 2)
throw StreamError_t("Number is too big for protocol version 1.0");
writer.write("<value><i8>",11);
writer.write(buff.str().data(),buff.str().size());
writer.write("</i8></value>\n",14);
} else {
writer.write("<value><i4>",11);
writer.write(buff.str().data(),buff.str().size());
writer.write("</i4></value>\n",14);
}
if (entityStorage.empty()) {
packSpaces(level - 1);
writer.write("</param>\n",9);
level--;
}
decrementItem();
}
void XmlMarshaller_t::packMethodCall(const char* methodName, unsigned int size) {
if (size > 255 || size == 0)
throw LenError_t("Lenght of method name is %d not in interval (1-255)",size);
//pack MAgic header
packMagic();
writer.write("<methodCall>\n",13);
level++;
packSpaces(level);
writer.write("<methodName>",12);
writeQuotedString(methodName,size);
//writer.write(methodName,nameSize);
writer.write("</methodName>\n",14);
writer.write("<params>\n",9);
level++;
mainType = METHOD_CALL;
}
void XmlMarshaller_t::packMethodResponse() {
packMagic();
writer.write("<methodResponse>\n",17);
level++;
packSpaces(level);
writer.write("<params>\n",9);
level++;
mainType = METHOD_RESPONSE;
}
void XmlMarshaller_t::packString(const char* value, unsigned int size) {
//write correct spaces
packSpaces(level);
if (entityStorage.empty()) {
writer.write("<param>\n",8);
level++;
}
//write correct spaces
packSpaces(level);
//write tags
writer.write("<value><string>",15);
//write value
writeQuotedString(value,size);
//writer.write(value,strSize);
//write tags
writer.write("</string></value>\n",18);
if (entityStorage.empty()) {
packSpaces(level - 1);
writer.write("</param>\n",9);
level--;
}
decrementItem();
}
void XmlMarshaller_t::packStruct(unsigned int numOfMembers) {
//write correct spaces
packSpaces(level);
if (entityStorage.empty()) {
writer.write("<param>\n",8);
level++;
}
packSpaces(level);
//write array tag
writer.write("<value>\n",8);
level++;
packSpaces(level);
writer.write("<struct>\n",9);
level++;
if (numOfMembers == 0) {
level--;
writer.write("</struct>\n",10);
level--;
writer.write("</value>\n",9);
if ( entityStorage.size() == 0)
writer.write("</param>\n",9);
decrementItem();
} else {
//entity to storage
entityStorage.push_back(TypeStorage_t(STRUCT,numOfMembers));
}
}
void XmlMarshaller_t::packStructMember(const char* memberName, unsigned int size) {
if (size > 255 || size == 0)
throw LenError_t("Lenght of member name is %d not in interval (1-255)",size);
packSpaces(level);
writer.write("<member>\n",9);
level++;
packSpaces(level);
writer.write("<name>",6);
writeQuotedString(memberName,size);
//writer.write(memberName,nameSize);
writer.write("</name>\n",8);
}
void XmlMarshaller_t::flush() {
switch (mainType) {
case METHOD_CALL:
packSpaces(level-1);
writer.write("</params>\n",10);
level--;
packSpaces(level-1);
writer.write("</methodCall>\n",14);
break;
case METHOD_RESPONSE:
packSpaces(level-1);
writer.write("</params>\n",10);
level--;
packSpaces(level-1);
writer.write("</methodResponse>\n",18);
break;
}
writer.flush();
level = 0;
entityStorage.clear();
}
void XmlMarshaller_t::packMagic() {
if (protocolVersion.versionMajor < 2) {
char magic[]="<?xml version=\"1.0\"?>\n";
//write magic
writer.write(magic,strlen(magic));
} else {
char magic[]="<?xml version=\"1.0\"?>\n<!--protocolVersion=\"2.0\"-->\n";
//write magic
writer.write(magic,strlen(magic));
}
}
void XmlMarshaller_t::writeEncodeBase64(const char *data, unsigned int len) {
static const char table[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string src(data,len);
if (src.empty()) {
return ;
}
size_t lineLen = 0;
std::string::const_iterator end = src.end();
for (std::string::const_iterator isrc = src.begin();
isrc != end; ) {
unsigned char input[3];
int n = 0;
for (; (isrc != end) && (n < 3) ; isrc++, n++)
input[n] = *isrc;
if (n) {
writer.write(&table[input[0] >> 2],1);
writer.write(&table[((input[0] & 0x03) << 4) | (input[1] >> 4)],1);
if (n > 1)
writer.write(&table[((input[1] & 0x0F) << 2) | (input[2] >> 6)],1);
else
writer.write("=",1);
if (n > 2)
writer.write(&table[input[2] & 0x3F],1);
else
writer.write("=",1);
lineLen += 4;
if (lineLen > 72) {
writer.write("\r\n",2);
lineLen = 0;
}
}
}
if (lineLen) {
writer.write("\r\n",2);
lineLen = 0;
}
return ;
}
void XmlMarshaller_t::writeQuotedString(const char *data, unsigned int len) {
for (unsigned int i = 0; i < len; i++) {
switch (data[i]) {
case '<':
writer.write("<",4);
break;
case '>':
writer.write(">",4);
break;
case '"':
writer.write(""",6);
break;
case '&':
writer.write("&",5);
break;
default:
writer.write(&data[i],1);
break;
}
}
}
};
<|endoftext|> |
<commit_before>#include <getopt.h>
#include <string>
#include <iostream>
#include "gfakluge.hpp"
using namespace std;
using namespace gfak;
void spec_help(char** argv){
cout << "gfa_spec_convert: convert GFA 0.1 <-> 1.0 <-> 2.0, walks <-> paths, etc." << endl
<< "Usage: " << argv[0] << " [OPTIONS] <GFA_FILE> > gfa_out.gfa" << endl
<< "Options: " << endl
<< " -w / --walks Output paths as walks, but maintain version (NOT SPEC COMPLIANT)." << endl
<< " -p / --paths Output walks as paths, but maintain version." << endl
<< " -s / --spec [0.1, 1.0, 2.0] Convert the input GFA file to specification [0.1, 1.0, or 2.0]." << endl
<< " NB: not all GFA specs are backward/forward compatible, so a subset of the GFA may be used." << endl
<< " -b / --block-order Output GFA in block order [HSLP / HSLW | HSEFGUO]."
<< endl;
}
int main(int argc, char** argv){
string gfa_file = "";
bool block_order = false;
double spec_version = 0.1;
bool use_paths = true;
if (argc < 2){
spec_help(argv);
exit(0);
}
int c;
optind = 1;
while (true){
static struct option long_options[] =
{
{"help", no_argument, 0, 'h'},
{"block-order", no_argument, 0, 'b'},
{"gfa-file", required_argument, 0, 'i'},
{"paths", no_argument, 0, 'p'},
{"walks", no_argument, 0, 'w'},
{"spec", required_argument, 0, 's'},
{0,0,0,0}
};
int option_index = 0;
c = getopt_long(argc, argv, "hbpws:", long_options, &option_index);
if (c == -1){
break;
}
switch (c){
case 'i':
gfa_file = optarg;
break;
case '?':
case 'h':
cerr << "gfa_sort [-b --block-order ] -i <GFA_File> >> my_sorted_gfa.gfa" << endl;
exit(0);
case 'b':
block_order = true;
break;
case 's':
spec_version = stod(optarg);
break;
case 'w':
use_paths = false;
break;
case 'p':
use_paths = true;
break;
default:
abort();
}
}
gfa_file = argv[optind];
GFAKluge gg;
gg.parse_gfa_file(gfa_file);
if (use_paths){
gg.set_version(1.0);
}
else{
gg.set_version(0.1);
gg.set_walks(true);
}
if (spec_version == 0.1){
gg.set_version(0.1);
}
else if (spec_version == 1.0){
gg.set_version(1.0);
}
else if (spec_version == 2.0){
gg.set_version(2.0);
}
else if (spec_version != 0.0){
cerr << "Invalid specification number: " << spec_version << endl
<< "Please provide one of [0.1, 1.0, 2.0]." << endl;
exit(22);
}
if (block_order){
cout << gg.block_order_string();
}
else{
cout << gg.to_string();
}
return 0;
}
<commit_msg>Fix spec convert help<commit_after>#include <getopt.h>
#include <string>
#include <iostream>
#include "gfakluge.hpp"
using namespace std;
using namespace gfak;
void spec_help(char** argv){
cout << "gfa_spec_convert: convert GFA 0.1 <-> 1.0 <-> 2.0, walks <-> paths, etc." << endl
<< "Usage: " << argv[0] << " [OPTIONS] <GFA_FILE> > gfa_out.gfa" << endl
<< "Options: " << endl
<< " -w / --walks Output paths as walks, but maintain version (NOT SPEC COMPLIANT)." << endl
<< " -p / --paths Output walks as paths, but maintain version." << endl
<< " -s / --spec [0.1, 1.0, 2.0] Convert the input GFA file to specification [0.1, 1.0, or 2.0]." << endl
<< " NB: not all GFA specs are backward/forward compatible, so a subset of the GFA may be used." << endl
<< " -b / --block-order Output GFA in block order [HSLP / HSLW | HSEFGUO]."
<< endl;
}
int main(int argc, char** argv){
string gfa_file = "";
bool block_order = false;
double spec_version = 0.1;
bool use_paths = true;
if (argc < 2){
spec_help(argv);
exit(0);
}
int c;
optind = 1;
while (true){
static struct option long_options[] =
{
{"help", no_argument, 0, 'h'},
{"block-order", no_argument, 0, 'b'},
{"gfa-file", required_argument, 0, 'i'},
{"paths", no_argument, 0, 'p'},
{"walks", no_argument, 0, 'w'},
{"spec", required_argument, 0, 's'},
{0,0,0,0}
};
int option_index = 0;
c = getopt_long(argc, argv, "hbpws:", long_options, &option_index);
if (c == -1){
break;
}
switch (c){
case 'i':
gfa_file = optarg;
break;
case '?':
case 'h':
spec_help(argv);
exit(0);
case 'b':
block_order = true;
break;
case 's':
spec_version = stod(optarg);
break;
case 'w':
use_paths = false;
break;
case 'p':
use_paths = true;
break;
default:
abort();
}
}
gfa_file = argv[optind];
GFAKluge gg;
gg.parse_gfa_file(gfa_file);
if (use_paths){
gg.set_version(1.0);
}
else{
gg.set_version(0.1);
gg.set_walks(true);
}
if (spec_version == 0.1){
gg.set_version(0.1);
}
else if (spec_version == 1.0){
gg.set_version(1.0);
}
else if (spec_version == 2.0){
gg.set_version(2.0);
}
else if (spec_version != 0.0){
cerr << "Invalid specification number: " << spec_version << endl
<< "Please provide one of [0.1, 1.0, 2.0]." << endl;
exit(22);
}
if (block_order){
cout << gg.block_order_string();
}
else{
cout << gg.to_string();
}
return 0;
}
<|endoftext|> |
<commit_before>///
/// @file pi_lmo4.cpp
/// @brief Implementation of the Lagarias-Miller-Odlyzko prime
/// counting algorithm. This implementation uses the segmented
/// sieve of Eratosthenes and a special tree data structure
/// for faster counting in S2(x).
///
/// 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.
///
#include "PhiTiny.hpp"
#include "Pk.hpp"
#include "pmath.hpp"
#include "tos_counters.hpp"
#include <primecount.hpp>
#include <primesieve.hpp>
#include <stdint.h>
#include <vector>
using std::log;
namespace {
/// Calculate the contribution of the ordinary leaves.
///
int64_t S1(int64_t x,
int64_t x13_alpha,
int64_t c,
std::vector<int32_t>& primes,
std::vector<int32_t>& lpf,
std::vector<int32_t>& mu)
{
int64_t S1_result = 0;
for (int64_t n = 1; n <= x13_alpha; n++)
if (lpf[n] > primes[c])
S1_result += mu[n] * primecount::phi(x / n, c);
return S1_result;
}
/// Calculate the contribution of the special leaves.
/// @pre c >= 2
///
int64_t S2(int64_t x,
int64_t x13_alpha,
int64_t a,
int64_t c,
std::vector<int32_t>& primes,
std::vector<int32_t>& lpf,
std::vector<int32_t>& mu)
{
int64_t limit = x / x13_alpha + 1;
int64_t segment_size = next_power_of_2(isqrt(limit));
int64_t S2_result = 0;
// vector used for sieving
std::vector<char> sieve(segment_size);
std::vector<int32_t> counters(segment_size);
std::vector<int64_t> next(primes.begin(), primes.end());
std::vector<int64_t> phi(primes.size(), 0);
// Segmented sieve of Eratosthenes
for (int64_t low = 1; low < limit; low += segment_size)
{
std::fill(sieve.begin(), sieve.end(), 1);
// Current segment = interval [low, high[
int64_t high = std::min(low + segment_size, limit);
// phi(y, b) nodes with b <= c do not contribute to S2, so we
// simply sieve out the multiples of the first c primes
for (int64_t b = 1; b <= c; b++)
{
int64_t k = next[b];
for (int64_t prime = primes[b]; k < high; k += prime)
sieve[k - low] = 0;
next[b] = k;
}
// Initialize special tree data structure from sieve
cnt_finit(sieve, counters, segment_size);
for (int64_t b = c; b + 1 < a; b++)
{
int64_t prime = primes[b + 1];
int64_t max_m = std::min(x / (low * prime), x13_alpha);
int64_t min_m = std::max(x / (high * prime), x13_alpha / prime);
// Obviously if (prime >= max_m) then (prime >= lpf[max_m])
// if so then (prime < lpf[m]) will always evaluate to
// false and no special leaves are possible
if (prime >= max_m)
break;
for (int64_t m = min_m + 1; m <= max_m; m++)
{
if (mu[m] != 0 && prime < lpf[m])
{
// We have found a special leaf, compute it's contribution
// phi(x / (m * primes[b + 1]), b) by counting the
// number of unsieved elements <= x / (m * primes[b + 1])
// after having removed the multiples of the first b primes
//
int64_t y = x / (m * prime);
int64_t count = cnt_query(counters, y - low);
int64_t phi_y = phi[b + 1] + count;
S2_result -= mu[m] * phi_y;
}
}
// Calculate phi(x / ((high - 1) * primes[b + 1]), b) which will
// be used to calculate special leaves in the next segment
phi[b + 1] += cnt_query(counters, (high - 1) - low);
// Remove the multiples of (b + 1)th prime
int64_t k = next[b + 1];
for (; k < high; k += prime * 2)
{
if (sieve[k - low])
{
sieve[k - low] = 0;
cnt_update(counters, k - low, segment_size);
}
}
next[b + 1] = k;
}
}
return S2_result;
}
} // namespace
namespace primecount {
/// Calculate the number of primes below x using the
/// Lagarias-Miller-Odlyzko algorithm.
/// Run time: O(x^(2/3) / log x) operations, O(x^0.5) space.
/// @note O(x^0.5) space is due to parallel P2(x, a).
///
int64_t pi_lmo4(int64_t x, int threads)
{
if (x < 2)
return 0;
// Optimization factor, see:
// J. C. Lagarias, V. S. Miller, and A. M. Odlyzko, Computing pi(x): The Meissel-
// Lehmer method, Mathematics of Computation, 44 (1985), p. 556.
double beta = 1.0;
double alpha = std::max(1.0, log(log((double) x)) * beta);
int64_t x13 = iroot<3>(x);
int64_t x13_alpha = (int64_t)(x13 * alpha);
int64_t a = pi_lehmer(x13_alpha);
int64_t c = (a < 6) ? a : 6;
std::vector<int32_t> lpf = make_least_prime_factor(x13_alpha);
std::vector<int32_t> mu = make_moebius(x13_alpha);
std::vector<int32_t> primes;
primes.push_back(0);
primesieve::generate_n_primes(a, &primes);
int64_t phi = S1(x, x13_alpha, c, primes, lpf , mu) + S2(x, x13_alpha, a, c, primes, lpf , mu);
int64_t sum = phi + a - 1 - P2(x, a, threads);
return sum;
}
} // namespace primecount
<commit_msg>Correct runtime complexity<commit_after>///
/// @file pi_lmo4.cpp
/// @brief Implementation of the Lagarias-Miller-Odlyzko prime
/// counting algorithm. This implementation uses the segmented
/// sieve of Eratosthenes and a special tree data structure
/// for faster counting in S2(x).
///
/// 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.
///
#include "PhiTiny.hpp"
#include "Pk.hpp"
#include "pmath.hpp"
#include "tos_counters.hpp"
#include <primecount.hpp>
#include <primesieve.hpp>
#include <stdint.h>
#include <vector>
using std::log;
namespace {
/// Calculate the contribution of the ordinary leaves.
///
int64_t S1(int64_t x,
int64_t x13_alpha,
int64_t c,
std::vector<int32_t>& primes,
std::vector<int32_t>& lpf,
std::vector<int32_t>& mu)
{
int64_t S1_result = 0;
for (int64_t n = 1; n <= x13_alpha; n++)
if (lpf[n] > primes[c])
S1_result += mu[n] * primecount::phi(x / n, c);
return S1_result;
}
/// Calculate the contribution of the special leaves.
/// @pre c >= 2
///
int64_t S2(int64_t x,
int64_t x13_alpha,
int64_t a,
int64_t c,
std::vector<int32_t>& primes,
std::vector<int32_t>& lpf,
std::vector<int32_t>& mu)
{
int64_t limit = x / x13_alpha + 1;
int64_t segment_size = next_power_of_2(isqrt(limit));
int64_t S2_result = 0;
// vector used for sieving
std::vector<char> sieve(segment_size);
std::vector<int32_t> counters(segment_size);
std::vector<int64_t> next(primes.begin(), primes.end());
std::vector<int64_t> phi(primes.size(), 0);
// Segmented sieve of Eratosthenes
for (int64_t low = 1; low < limit; low += segment_size)
{
std::fill(sieve.begin(), sieve.end(), 1);
// Current segment = interval [low, high[
int64_t high = std::min(low + segment_size, limit);
// phi(y, b) nodes with b <= c do not contribute to S2, so we
// simply sieve out the multiples of the first c primes
for (int64_t b = 1; b <= c; b++)
{
int64_t k = next[b];
for (int64_t prime = primes[b]; k < high; k += prime)
sieve[k - low] = 0;
next[b] = k;
}
// Initialize special tree data structure from sieve
cnt_finit(sieve, counters, segment_size);
for (int64_t b = c; b + 1 < a; b++)
{
int64_t prime = primes[b + 1];
int64_t max_m = std::min(x / (low * prime), x13_alpha);
int64_t min_m = std::max(x / (high * prime), x13_alpha / prime);
// Obviously if (prime >= max_m) then (prime >= lpf[max_m])
// if so then (prime < lpf[m]) will always evaluate to
// false and no special leaves are possible
if (prime >= max_m)
break;
for (int64_t m = min_m + 1; m <= max_m; m++)
{
if (mu[m] != 0 && prime < lpf[m])
{
// We have found a special leaf, compute it's contribution
// phi(x / (m * primes[b + 1]), b) by counting the
// number of unsieved elements <= x / (m * primes[b + 1])
// after having removed the multiples of the first b primes
//
int64_t y = x / (m * prime);
int64_t count = cnt_query(counters, y - low);
int64_t phi_y = phi[b + 1] + count;
S2_result -= mu[m] * phi_y;
}
}
// Calculate phi(x / ((high - 1) * primes[b + 1]), b) which will
// be used to calculate special leaves in the next segment
phi[b + 1] += cnt_query(counters, (high - 1) - low);
// Remove the multiples of (b + 1)th prime
int64_t k = next[b + 1];
for (; k < high; k += prime * 2)
{
if (sieve[k - low])
{
sieve[k - low] = 0;
cnt_update(counters, k - low, segment_size);
}
}
next[b + 1] = k;
}
}
return S2_result;
}
} // namespace
namespace primecount {
/// Calculate the number of primes below x using the
/// Lagarias-Miller-Odlyzko algorithm.
/// Run time: O(x^(2/3) / log log x) operations, O(x^0.5) space.
/// @note O(x^0.5) space is due to parallel P2(x, a).
///
int64_t pi_lmo4(int64_t x, int threads)
{
if (x < 2)
return 0;
// Optimization factor, see:
// J. C. Lagarias, V. S. Miller, and A. M. Odlyzko, Computing pi(x): The Meissel-
// Lehmer method, Mathematics of Computation, 44 (1985), p. 556.
double beta = 1.0;
double alpha = std::max(1.0, log(log((double) x)) * beta);
int64_t x13 = iroot<3>(x);
int64_t x13_alpha = (int64_t)(x13 * alpha);
int64_t a = pi_lehmer(x13_alpha);
int64_t c = (a < 6) ? a : 6;
std::vector<int32_t> lpf = make_least_prime_factor(x13_alpha);
std::vector<int32_t> mu = make_moebius(x13_alpha);
std::vector<int32_t> primes;
primes.push_back(0);
primesieve::generate_n_primes(a, &primes);
int64_t phi = S1(x, x13_alpha, c, primes, lpf , mu) + S2(x, x13_alpha, a, c, primes, lpf , mu);
int64_t sum = phi + a - 1 - P2(x, a, threads);
return sum;
}
} // namespace primecount
<|endoftext|> |
<commit_before>// Ylikuutio - A 3D game and simulation engine.
//
// Copyright (C) 2015-2022 Antti Nuortimo.
//
// This program 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.
//
// 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef __YLIKUUTIO_ONTOLOGY_TEXT_3D_HPP_INCLUDED
#define __YLIKUUTIO_ONTOLOGY_TEXT_3D_HPP_INCLUDED
#include "movable.hpp"
#include "child_module.hpp"
#include "generic_master_module.hpp"
#include "glyph_object_creation.hpp"
// Include standard headers
#include <cstddef> // std::size_t
#include <optional> // std::optional
#include <string> // std::string
namespace yli::data
{
class AnyValue;
}
namespace yli::ontology
{
class Entity;
class Universe;
class Scene;
class Shader;
class Object;
class GenericParentModule;
class VectorFont;
struct Text3DStruct;
class Text3D: public yli::ontology::Movable
{
public:
// Disable all character `Object`s of `text_3d`,
// set `parent` according to the input, request a new childID
// from the `new_parent`, and create and enable the needed
// character `Object`s of `text_3d`.
// TODO: implement creation and enabling the character `Object`s!
// Note: different fonts may provide glyphs for different Unicode code points!
static std::optional<yli::data::AnyValue> bind_to_new_vector_font_parent(yli::ontology::Text3D& text_3d, yli::ontology::VectorFont& new_parent);
Text3D(
yli::ontology::Universe& universe,
const yli::ontology::Text3DStruct& text_3d_struct,
yli::ontology::GenericParentModule* const vector_font_parent_module,
yli::ontology::GenericMasterModule* const generic_master_module);
Text3D(const Text3D&) = delete; // Delete copy constructor.
Text3D& operator=(const Text3D&) = delete; // Delete copy assignment.
// destructor.
virtual ~Text3D();
yli::ontology::Entity* get_parent() const override;
friend class yli::ontology::Object;
friend void yli::ontology::create_glyph_objects(const std::string& text_string, yli::ontology::Text3D* text_3d);
yli::ontology::ChildModule child_of_vector_font;
yli::ontology::GenericMasterModule master_of_objects;
private:
yli::ontology::Scene* get_scene() const override;
public:
yli::ontology::Shader* get_shader() const;
private:
std::size_t get_number_of_children() const override;
std::size_t get_number_of_descendants() const override;
std::string text_string;
};
}
#endif
<commit_msg>Reorder forward declarations into canonical order.<commit_after>// Ylikuutio - A 3D game and simulation engine.
//
// Copyright (C) 2015-2022 Antti Nuortimo.
//
// This program 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.
//
// 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef __YLIKUUTIO_ONTOLOGY_TEXT_3D_HPP_INCLUDED
#define __YLIKUUTIO_ONTOLOGY_TEXT_3D_HPP_INCLUDED
#include "movable.hpp"
#include "child_module.hpp"
#include "generic_master_module.hpp"
#include "glyph_object_creation.hpp"
// Include standard headers
#include <cstddef> // std::size_t
#include <optional> // std::optional
#include <string> // std::string
namespace yli::data
{
class AnyValue;
}
namespace yli::ontology
{
class GenericParentModule;
class Entity;
class Universe;
class Scene;
class Shader;
class Object;
class VectorFont;
struct Text3DStruct;
class Text3D: public yli::ontology::Movable
{
public:
// Disable all character `Object`s of `text_3d`,
// set `parent` according to the input, request a new childID
// from the `new_parent`, and create and enable the needed
// character `Object`s of `text_3d`.
// TODO: implement creation and enabling the character `Object`s!
// Note: different fonts may provide glyphs for different Unicode code points!
static std::optional<yli::data::AnyValue> bind_to_new_vector_font_parent(yli::ontology::Text3D& text_3d, yli::ontology::VectorFont& new_parent);
Text3D(
yli::ontology::Universe& universe,
const yli::ontology::Text3DStruct& text_3d_struct,
yli::ontology::GenericParentModule* const vector_font_parent_module,
yli::ontology::GenericMasterModule* const generic_master_module);
Text3D(const Text3D&) = delete; // Delete copy constructor.
Text3D& operator=(const Text3D&) = delete; // Delete copy assignment.
// destructor.
virtual ~Text3D();
yli::ontology::Entity* get_parent() const override;
friend class yli::ontology::Object;
friend void yli::ontology::create_glyph_objects(const std::string& text_string, yli::ontology::Text3D* text_3d);
yli::ontology::ChildModule child_of_vector_font;
yli::ontology::GenericMasterModule master_of_objects;
private:
yli::ontology::Scene* get_scene() const override;
public:
yli::ontology::Shader* get_shader() const;
private:
std::size_t get_number_of_children() const override;
std::size_t get_number_of_descendants() const override;
std::string text_string;
};
}
#endif
<|endoftext|> |
<commit_before>/*
KOrganizer Alarm Daemon Client.
This file is part of KOrganizer.
Copyright (c) 2002,2003 Cornelius Schumacher
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.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "koalarmclient.h"
#include "alarmdockwindow.h"
#include "alarmdialog.h"
#include <libkcal/calendarresources.h>
#include <kstandarddirs.h>
#include <kdebug.h>
#include <klocale.h>
#include <kapplication.h>
KOAlarmClient::KOAlarmClient( QObject *parent, const char *name )
: DCOPObject( "ac" ), QObject( parent, name ),
mSuspendTimer( this )
{
kdDebug(5900) << "KOAlarmClient::KOAlarmClient()" << endl;
mDocker = new AlarmDockWindow;
mDocker->show();
mAlarmDialog = new AlarmDialog;
connect( mAlarmDialog, SIGNAL( suspendSignal( int ) ),
SLOT( suspend( int ) ) );
mCalendar = new CalendarResources();
KConfig c( locate( "config", "korganizerrc" ) );
c.setGroup( "Time & Date" );
QString tz = c.readEntry( "TimeZoneId" );
kdDebug() << "TimeZone: " << tz << endl;
mCalendar->setTimeZoneId( tz );
connect( &mCheckTimer, SIGNAL( timeout() ), SLOT( checkAlarms() ) );
KConfig *cfg = KGlobal::config();
cfg->setGroup( "Alarms" );
int interval = cfg->readNumEntry( "Interval", 60 );
kdDebug() << "KOAlarmClient check interval: " << interval << " seconds."
<< endl;
mCheckTimer.start( 1000 * interval ); // interval in seconds
}
KOAlarmClient::~KOAlarmClient()
{
delete mCalendar;
delete mDocker;
}
void KOAlarmClient::checkAlarms()
{
KConfig *cfg = KGlobal::config();
cfg->setGroup( "General" );
if ( !cfg->readBoolEntry( "Enabled", true ) ) return;
cfg->setGroup( "Alarms" );
QDateTime lastChecked = cfg->readDateTimeEntry( "CalendarsLastChecked" );
QDateTime from = lastChecked.addSecs( 1 );
QDateTime to = QDateTime::currentDateTime();
kdDebug() << "Check: " << from.toString() << " - " << to.toString() << endl;
QValueList<Alarm *> alarms = mCalendar->alarms( from, to );
bool newEvents = false;
QValueList<Alarm *>::ConstIterator it;
for( it = alarms.begin(); it != alarms.end(); ++it ) {
kdDebug() << "ALARM: " << (*it)->parent()->summary() << endl;
Event *event = mCalendar->event( (*it)->parent()->uid() );
if ( event ) {
mAlarmDialog->appendEvent( event );
newEvents = true;
}
}
if ( newEvents ) {
mAlarmDialog->show();
mAlarmDialog->eventNotification();
}
cfg->writeEntry( "CalendarsLastChecked", to );
cfg->sync();
}
void KOAlarmClient::suspend( int minutes )
{
// kdDebug(5900) << "KOAlarmClient::suspend() " << minutes << " minutes" << endl;
connect( &mSuspendTimer, SIGNAL( timeout() ), SLOT( showAlarmDialog() ) );
mSuspendTimer.start( 1000 * 60 * minutes, true );
}
void KOAlarmClient::showAlarmDialog()
{
mAlarmDialog->show();
mAlarmDialog->eventNotification();
}
void KOAlarmClient::quit()
{
kdDebug() << "KOAlarmClient::quit()" << endl;
kapp->quit();
}
void KOAlarmClient::forceAlarmCheck()
{
checkAlarms();
}
void KOAlarmClient::dumpDebug()
{
KConfig *cfg = KGlobal::config();
cfg->setGroup( "Alarms" );
QDateTime lastChecked = cfg->readDateTimeEntry( "CalendarsLastChecked" );
kdDebug() << "Last Check: " << lastChecked << endl;
}
QStringList KOAlarmClient::dumpAlarms()
{
QDateTime start = QDateTime( QDateTime::currentDateTime().date(),
QTime( 0, 0 ) );
QDateTime end = start.addDays( 1 ).addSecs( -1 );
QStringList lst;
// Don't translate, this is for debugging purposes.
lst << QString("AlarmDeamon::dumpAlarms() from ") + start.toString()+ " to " +
end.toString();
QValueList<Alarm*> alarms = mCalendar->alarms( start, end );
QValueList<Alarm*>::ConstIterator it;
for( it = alarms.begin(); it != alarms.end(); ++it ) {
Alarm *a = *it;
lst << QString(" ") + a->parent()->summary() + " ("
+ a->time().toString() + ")";
}
return lst;
}
#include "koalarmclient.moc"
<commit_msg>Fixing debug areas.<commit_after>/*
KOrganizer Alarm Daemon Client.
This file is part of KOrganizer.
Copyright (c) 2002,2003 Cornelius Schumacher
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.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "koalarmclient.h"
#include "alarmdockwindow.h"
#include "alarmdialog.h"
#include <libkcal/calendarresources.h>
#include <kstandarddirs.h>
#include <kdebug.h>
#include <klocale.h>
#include <kapplication.h>
KOAlarmClient::KOAlarmClient( QObject *parent, const char *name )
: DCOPObject( "ac" ), QObject( parent, name ),
mSuspendTimer( this )
{
kdDebug(5850) << "KOAlarmClient::KOAlarmClient()" << endl;
mDocker = new AlarmDockWindow;
mDocker->show();
mAlarmDialog = new AlarmDialog;
connect( mAlarmDialog, SIGNAL( suspendSignal( int ) ),
SLOT( suspend( int ) ) );
mCalendar = new CalendarResources();
KConfig c( locate( "config", "korganizerrc" ) );
c.setGroup( "Time & Date" );
QString tz = c.readEntry( "TimeZoneId" );
kdDebug(5850) << "TimeZone: " << tz << endl;
mCalendar->setTimeZoneId( tz );
connect( &mCheckTimer, SIGNAL( timeout() ), SLOT( checkAlarms() ) );
KConfig *cfg = KGlobal::config();
cfg->setGroup( "Alarms" );
int interval = cfg->readNumEntry( "Interval", 60 );
kdDebug(5850) << "KOAlarmClient check interval: " << interval << " seconds."
<< endl;
mCheckTimer.start( 1000 * interval ); // interval in seconds
}
KOAlarmClient::~KOAlarmClient()
{
delete mCalendar;
delete mDocker;
}
void KOAlarmClient::checkAlarms()
{
KConfig *cfg = KGlobal::config();
cfg->setGroup( "General" );
if ( !cfg->readBoolEntry( "Enabled", true ) ) return;
cfg->setGroup( "Alarms" );
QDateTime lastChecked = cfg->readDateTimeEntry( "CalendarsLastChecked" );
QDateTime from = lastChecked.addSecs( 1 );
QDateTime to = QDateTime::currentDateTime();
kdDebug(5855) << "Check: " << from.toString() << " - " << to.toString() << endl;
QValueList<Alarm *> alarms = mCalendar->alarms( from, to );
bool newEvents = false;
QValueList<Alarm *>::ConstIterator it;
for( it = alarms.begin(); it != alarms.end(); ++it ) {
kdDebug(5855) << "ALARM: " << (*it)->parent()->summary() << endl;
Event *event = mCalendar->event( (*it)->parent()->uid() );
if ( event ) {
mAlarmDialog->appendEvent( event );
newEvents = true;
}
}
if ( newEvents ) {
mAlarmDialog->show();
mAlarmDialog->eventNotification();
}
cfg->writeEntry( "CalendarsLastChecked", to );
cfg->sync();
}
void KOAlarmClient::suspend( int minutes )
{
// kdDebug(5850) << "KOAlarmClient::suspend() " << minutes << " minutes" << endl;
connect( &mSuspendTimer, SIGNAL( timeout() ), SLOT( showAlarmDialog() ) );
mSuspendTimer.start( 1000 * 60 * minutes, true );
}
void KOAlarmClient::showAlarmDialog()
{
mAlarmDialog->show();
mAlarmDialog->eventNotification();
}
void KOAlarmClient::quit()
{
kdDebug(5850) << "KOAlarmClient::quit()" << endl;
kapp->quit();
}
void KOAlarmClient::forceAlarmCheck()
{
checkAlarms();
}
void KOAlarmClient::dumpDebug()
{
KConfig *cfg = KGlobal::config();
cfg->setGroup( "Alarms" );
QDateTime lastChecked = cfg->readDateTimeEntry( "CalendarsLastChecked" );
kdDebug(5850) << "Last Check: " << lastChecked << endl;
}
QStringList KOAlarmClient::dumpAlarms()
{
QDateTime start = QDateTime( QDateTime::currentDateTime().date(),
QTime( 0, 0 ) );
QDateTime end = start.addDays( 1 ).addSecs( -1 );
QStringList lst;
// Don't translate, this is for debugging purposes.
lst << QString("AlarmDeamon::dumpAlarms() from ") + start.toString()+ " to " +
end.toString();
QValueList<Alarm*> alarms = mCalendar->alarms( start, end );
QValueList<Alarm*>::ConstIterator it;
for( it = alarms.begin(); it != alarms.end(); ++it ) {
Alarm *a = *it;
lst << QString(" ") + a->parent()->summary() + " ("
+ a->time().toString() + ")";
}
return lst;
}
#include "koalarmclient.moc"
<|endoftext|> |
<commit_before><commit_msg>wrench ratio works and is consistent<commit_after><|endoftext|> |
<commit_before>/*******************************************************************************
*
* X testing environment - Google Test environment feat. dummy x server
*
* Copyright (C) 2011, 2012 Canonical Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
******************************************************************************/
#include "xorg/gtest/xorg-gtest-process.h"
#include <sys/prctl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <algorithm>
#include <cerrno>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <stdexcept>
#include <vector>
struct xorg::testing::Process::Private {
pid_t pid;
enum State state;
};
xorg::testing::Process::Process() : d_(new Private) {
d_->pid = -1;
d_->state = NONE;
}
enum xorg::testing::Process::State xorg::testing::Process::GetState() {
if (d_->state == RUNNING) {
int status;
int pid = waitpid(Pid(), &status, WNOHANG);
if (pid == Pid()) {
if (WIFEXITED(status)) {
d_->pid = -1;
d_->state = WEXITSTATUS(status) ? FINISHED_FAILURE : FINISHED_SUCCESS;
}
}
}
return d_->state;
}
pid_t xorg::testing::Process::Fork() {
if (d_->pid != -1)
throw std::runtime_error("A process may only be forked once");
d_->pid = fork();
if (d_->pid == -1) {
d_->state = ERROR;
throw std::runtime_error("Failed to fork child process");
} else if (d_->pid == 0) { /* Child */
close(0);
if (getenv("XORG_GTEST_CHILD_STDOUT") == NULL) {
close(1);
close(2);
}
#ifdef __linux
prctl(PR_SET_PDEATHSIG, SIGTERM);
#endif
}
d_->state = RUNNING;
return d_->pid;
}
void xorg::testing::Process::Start(const std::string &program, const std::vector<std::string> &argv) {
if (d_->pid == -1)
d_->pid = Fork();
else if (d_->pid > 0)
throw std::runtime_error("Start() may only be called on the child process");
if (d_->pid == 0) { /* Child */
std::vector<char*> args;
std::vector<std::string>::const_iterator it;
char *valgrind = getenv("XORG_GTEST_USE_VALGRIND");
if (valgrind) {
char *tok = strtok(valgrind, " ");
while(tok) {
args.push_back(strdup(tok));
tok = strtok(NULL, " ");
}
}
args.push_back(strdup(program.c_str()));
for (it = argv.begin(); it != argv.end(); it++)
args.push_back(strdup(it->c_str()));
args.push_back(NULL);
execvp(args[0], &args[0]);
d_->state = ERROR;
throw std::runtime_error("Failed to start process");
}
d_->state = RUNNING;
}
void xorg::testing::Process::Start(const std::string& program, va_list args) {
std::vector<std::string> argv;
if (args) {
char *arg;
do {
arg = va_arg(args, char*);
if (arg)
argv.push_back(std::string(arg));
} while (arg);
}
Start(program, argv);
}
void xorg::testing::Process::Start(const std::string& program, ...) {
va_list list;
va_start(list, program);
Start(program, list);
va_end(list); /* Shouldn't get here */
}
bool xorg::testing::Process::WaitForExit(unsigned int timeout) {
sigset_t sig_mask, old_mask;
sigemptyset(&sig_mask);
sigaddset(&sig_mask, SIGCHLD);
if (sigprocmask(SIG_BLOCK, &sig_mask, &old_mask) == 0) {
struct timespec sig_timeout = {timeout / 1000,
(timeout % 1000) * 1000000L};
if (sigtimedwait(&sig_mask, NULL, &sig_timeout) != SIGCHLD && errno != EAGAIN)
usleep(timeout * 1000);
if (!sigismember(&sig_mask, SIGCHLD)) {
if (sigprocmask(SIG_UNBLOCK, &sig_mask, NULL) == -1)
std::cout << "WARNING: Failed to unblock SIGCHLD. Tests may behave funny.\n";
}
} else { /* oops, can't wait for SIGCHLD, sleep instead */
usleep(timeout * 1000);
}
int status;
int pid = waitpid(Pid(), &status, WNOHANG);
if (pid == Pid()) {
if (WIFEXITED(status)) {
d_->state = WEXITSTATUS(status) ? FINISHED_FAILURE : FINISHED_SUCCESS;
} else if (WIFSIGNALED(status)) {
d_->state = FINISHED_FAILURE;
}
return true;
} else
return (pid == -1 && errno == ECHILD);
}
bool xorg::testing::Process::KillSelf(int signal, unsigned int timeout) {
enum State state = GetState();
switch (state) {
case FINISHED_SUCCESS:
case FINISHED_FAILURE:
case TERMINATED:
return true;
case ERROR:
case NONE:
return false;
default:
break;
}
if (d_->pid == -1) {
return false;
} else if (d_->pid == 0) {
/* Child */
throw std::runtime_error("Child process tried to kill itself");
} else { /* Parent */
if (kill(d_->pid, signal) < 0) {
d_->pid = -1;
d_->state = ERROR;
return false;
}
if (timeout > 0) {
bool wait_success = true;
wait_success = WaitForExit(timeout);
if (wait_success)
d_->pid = -1;
return wait_success;
}
d_->pid = -1;
}
d_->state = TERMINATED;
return true;
}
bool xorg::testing::Process::Terminate(unsigned int timeout) {
return KillSelf(SIGTERM, timeout);
}
bool xorg::testing::Process::Kill(unsigned int timeout) {
return KillSelf(SIGKILL, timeout);
}
void xorg::testing::Process::SetEnv(const std::string& name,
const std::string& value, bool overwrite) {
if (setenv(name.c_str(), value.c_str(), overwrite) != 0)
throw std::runtime_error("Failed to set environment variable in process");
return;
}
std::string xorg::testing::Process::GetEnv(const std::string& name,
bool* exists) {
const char* var = getenv(name.c_str());
if (exists != NULL)
*exists = (var != NULL);
return std::string(var);
}
pid_t xorg::testing::Process::Pid() const {
return d_->pid;
}
<commit_msg>process: if the wait fails because the child is still running, reset errno<commit_after>/*******************************************************************************
*
* X testing environment - Google Test environment feat. dummy x server
*
* Copyright (C) 2011, 2012 Canonical Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
******************************************************************************/
#include "xorg/gtest/xorg-gtest-process.h"
#include <sys/prctl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <algorithm>
#include <cerrno>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <stdexcept>
#include <vector>
struct xorg::testing::Process::Private {
pid_t pid;
enum State state;
};
xorg::testing::Process::Process() : d_(new Private) {
d_->pid = -1;
d_->state = NONE;
}
enum xorg::testing::Process::State xorg::testing::Process::GetState() {
if (d_->state == RUNNING) {
int status;
int pid = waitpid(Pid(), &status, WNOHANG);
if (pid == Pid()) {
if (WIFEXITED(status)) {
d_->pid = -1;
d_->state = WEXITSTATUS(status) ? FINISHED_FAILURE : FINISHED_SUCCESS;
}
}
}
return d_->state;
}
pid_t xorg::testing::Process::Fork() {
if (d_->pid != -1)
throw std::runtime_error("A process may only be forked once");
d_->pid = fork();
if (d_->pid == -1) {
d_->state = ERROR;
throw std::runtime_error("Failed to fork child process");
} else if (d_->pid == 0) { /* Child */
close(0);
if (getenv("XORG_GTEST_CHILD_STDOUT") == NULL) {
close(1);
close(2);
}
#ifdef __linux
prctl(PR_SET_PDEATHSIG, SIGTERM);
#endif
}
d_->state = RUNNING;
return d_->pid;
}
void xorg::testing::Process::Start(const std::string &program, const std::vector<std::string> &argv) {
if (d_->pid == -1)
d_->pid = Fork();
else if (d_->pid > 0)
throw std::runtime_error("Start() may only be called on the child process");
if (d_->pid == 0) { /* Child */
std::vector<char*> args;
std::vector<std::string>::const_iterator it;
char *valgrind = getenv("XORG_GTEST_USE_VALGRIND");
if (valgrind) {
char *tok = strtok(valgrind, " ");
while(tok) {
args.push_back(strdup(tok));
tok = strtok(NULL, " ");
}
}
args.push_back(strdup(program.c_str()));
for (it = argv.begin(); it != argv.end(); it++)
args.push_back(strdup(it->c_str()));
args.push_back(NULL);
execvp(args[0], &args[0]);
d_->state = ERROR;
throw std::runtime_error("Failed to start process");
}
d_->state = RUNNING;
}
void xorg::testing::Process::Start(const std::string& program, va_list args) {
std::vector<std::string> argv;
if (args) {
char *arg;
do {
arg = va_arg(args, char*);
if (arg)
argv.push_back(std::string(arg));
} while (arg);
}
Start(program, argv);
}
void xorg::testing::Process::Start(const std::string& program, ...) {
va_list list;
va_start(list, program);
Start(program, list);
va_end(list); /* Shouldn't get here */
}
bool xorg::testing::Process::WaitForExit(unsigned int timeout) {
sigset_t sig_mask, old_mask;
sigemptyset(&sig_mask);
sigaddset(&sig_mask, SIGCHLD);
if (sigprocmask(SIG_BLOCK, &sig_mask, &old_mask) == 0) {
struct timespec sig_timeout = {timeout / 1000,
(timeout % 1000) * 1000000L};
if (sigtimedwait(&sig_mask, NULL, &sig_timeout) != SIGCHLD && errno != EAGAIN)
usleep(timeout * 1000);
if (!sigismember(&sig_mask, SIGCHLD)) {
if (sigprocmask(SIG_UNBLOCK, &sig_mask, NULL) == -1)
std::cout << "WARNING: Failed to unblock SIGCHLD. Tests may behave funny.\n";
}
} else { /* oops, can't wait for SIGCHLD, sleep instead */
usleep(timeout * 1000);
}
int status;
int pid = waitpid(Pid(), &status, WNOHANG);
if (pid == Pid()) {
if (WIFEXITED(status)) {
d_->state = WEXITSTATUS(status) ? FINISHED_FAILURE : FINISHED_SUCCESS;
} else if (WIFSIGNALED(status)) {
d_->state = FINISHED_FAILURE;
}
return true;
} else {
/* prevent callers from getting odd erros if they check for errno */
if (pid == 0)
errno = 0;
return (pid == -1 && errno == ECHILD);
}
}
bool xorg::testing::Process::KillSelf(int signal, unsigned int timeout) {
enum State state = GetState();
switch (state) {
case FINISHED_SUCCESS:
case FINISHED_FAILURE:
case TERMINATED:
return true;
case ERROR:
case NONE:
return false;
default:
break;
}
if (d_->pid == -1) {
return false;
} else if (d_->pid == 0) {
/* Child */
throw std::runtime_error("Child process tried to kill itself");
} else { /* Parent */
if (kill(d_->pid, signal) < 0) {
d_->pid = -1;
d_->state = ERROR;
return false;
}
if (timeout > 0) {
bool wait_success = true;
wait_success = WaitForExit(timeout);
if (wait_success)
d_->pid = -1;
return wait_success;
}
d_->pid = -1;
}
d_->state = TERMINATED;
return true;
}
bool xorg::testing::Process::Terminate(unsigned int timeout) {
return KillSelf(SIGTERM, timeout);
}
bool xorg::testing::Process::Kill(unsigned int timeout) {
return KillSelf(SIGKILL, timeout);
}
void xorg::testing::Process::SetEnv(const std::string& name,
const std::string& value, bool overwrite) {
if (setenv(name.c_str(), value.c_str(), overwrite) != 0)
throw std::runtime_error("Failed to set environment variable in process");
return;
}
std::string xorg::testing::Process::GetEnv(const std::string& name,
bool* exists) {
const char* var = getenv(name.c_str());
if (exists != NULL)
*exists = (var != NULL);
return std::string(var);
}
pid_t xorg::testing::Process::Pid() const {
return d_->pid;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/shell/shell_browser_main.h"
#include <iostream>
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/sys_string_conversions.h"
#include "base/threading/thread_restrictions.h"
#include "base/utf_string_conversions.h"
#include "content/public/browser/browser_main_runner.h"
#include "content/shell/shell.h"
#include "content/shell/shell_switches.h"
#include "content/shell/webkit_test_controller.h"
#include "net/base/net_util.h"
#include "webkit/support/webkit_support.h"
namespace {
GURL GetURLForLayoutTest(const std::string& test_name,
base::FilePath* current_working_directory,
bool* enable_pixel_dumping,
std::string* expected_pixel_hash) {
// A test name is formated like file:///path/to/test'--pixel-test'pixelhash
std::string path_or_url = test_name;
std::string pixel_switch;
std::string pixel_hash;
std::string::size_type separator_position = path_or_url.find('\'');
if (separator_position != std::string::npos) {
pixel_switch = path_or_url.substr(separator_position + 1);
path_or_url.erase(separator_position);
}
separator_position = pixel_switch.find('\'');
if (separator_position != std::string::npos) {
pixel_hash = pixel_switch.substr(separator_position + 1);
pixel_switch.erase(separator_position);
}
if (enable_pixel_dumping) {
*enable_pixel_dumping =
(pixel_switch == "--pixel-test" || pixel_switch == "-p");
}
if (expected_pixel_hash)
*expected_pixel_hash = pixel_hash;
GURL test_url(path_or_url);
if (!(test_url.is_valid() && test_url.has_scheme())) {
// We're outside of the message loop here, and this is a test.
base::ThreadRestrictions::ScopedAllowIO allow_io;
#if defined(OS_WIN)
std::wstring wide_path_or_url =
base::SysNativeMBToWide(path_or_url);
base::FilePath local_file(wide_path_or_url);
#else
base::FilePath local_file(path_or_url);
#endif
file_util::AbsolutePath(&local_file);
test_url = net::FilePathToFileURL(local_file);
}
base::FilePath local_path;
if (current_working_directory) {
// We're outside of the message loop here, and this is a test.
base::ThreadRestrictions::ScopedAllowIO allow_io;
if (net::FileURLToFilePath(test_url, &local_path))
*current_working_directory = local_path.DirName();
else
file_util::GetCurrentDirectory(current_working_directory);
}
return test_url;
}
bool GetNextTest(const CommandLine::StringVector& args,
size_t* position,
std::string* test) {
if (*position >= args.size())
return false;
if (args[*position] == FILE_PATH_LITERAL("-"))
return !!std::getline(std::cin, *test, '\n');
#if defined(OS_WIN)
*test = WideToUTF8(args[(*position)++]);
#else
*test = args[(*position)++];
#endif
return true;
}
} // namespace
// Main routine for running as the Browser process.
int ShellBrowserMain(const content::MainFunctionParams& parameters) {
bool layout_test_mode =
CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree);
base::ScopedTempDir browser_context_path_for_layout_tests;
if (layout_test_mode) {
CHECK(browser_context_path_for_layout_tests.CreateUniqueTempDir());
CHECK(!browser_context_path_for_layout_tests.path().MaybeAsASCII().empty());
CommandLine::ForCurrentProcess()->AppendSwitchASCII(
switches::kContentShellDataPath,
browser_context_path_for_layout_tests.path().MaybeAsASCII());
}
scoped_ptr<content::BrowserMainRunner> main_runner_(
content::BrowserMainRunner::Create());
int exit_code = main_runner_->Initialize(parameters);
if (exit_code >= 0)
return exit_code;
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kCheckLayoutTestSysDeps)) {
MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
main_runner_->Run();
content::Shell::CloseAllWindows();
main_runner_->Shutdown();
return 0;
}
if (layout_test_mode) {
content::WebKitTestController test_controller;
{
// We're outside of the message loop here, and this is a test.
base::ThreadRestrictions::ScopedAllowIO allow_io;
base::FilePath temp_path;
file_util::GetTempDir(&temp_path);
test_controller.SetTempPath(temp_path);
}
std::string test_string;
CommandLine::StringVector args =
CommandLine::ForCurrentProcess()->GetArgs();
size_t command_line_position = 0;
bool ran_at_least_once = false;
#if defined(OS_ANDROID)
std::cout << "#READY\n";
std::cout.flush();
#endif
while (GetNextTest(args, &command_line_position, &test_string)) {
if (test_string.empty())
continue;
if (test_string == "QUIT")
break;
bool enable_pixel_dumps;
std::string pixel_hash;
base::FilePath cwd;
GURL test_url = GetURLForLayoutTest(
test_string, &cwd, &enable_pixel_dumps, &pixel_hash);
if (!content::WebKitTestController::Get()->PrepareForLayoutTest(
test_url, cwd, enable_pixel_dumps, pixel_hash)) {
break;
}
ran_at_least_once = true;
main_runner_->Run();
if (!content::WebKitTestController::Get()->ResetAfterLayoutTest())
break;
}
if (!ran_at_least_once) {
MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
main_runner_->Run();
}
exit_code = 0;
} else {
exit_code = main_runner_->Run();
}
main_runner_->Shutdown();
return exit_code;
}
<commit_msg>Revert 189135 "[content shell] close the main window after check..."<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/shell/shell_browser_main.h"
#include <iostream>
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/sys_string_conversions.h"
#include "base/threading/thread_restrictions.h"
#include "base/utf_string_conversions.h"
#include "content/public/browser/browser_main_runner.h"
#include "content/shell/shell_switches.h"
#include "content/shell/webkit_test_controller.h"
#include "net/base/net_util.h"
#include "webkit/support/webkit_support.h"
namespace {
GURL GetURLForLayoutTest(const std::string& test_name,
base::FilePath* current_working_directory,
bool* enable_pixel_dumping,
std::string* expected_pixel_hash) {
// A test name is formated like file:///path/to/test'--pixel-test'pixelhash
std::string path_or_url = test_name;
std::string pixel_switch;
std::string pixel_hash;
std::string::size_type separator_position = path_or_url.find('\'');
if (separator_position != std::string::npos) {
pixel_switch = path_or_url.substr(separator_position + 1);
path_or_url.erase(separator_position);
}
separator_position = pixel_switch.find('\'');
if (separator_position != std::string::npos) {
pixel_hash = pixel_switch.substr(separator_position + 1);
pixel_switch.erase(separator_position);
}
if (enable_pixel_dumping) {
*enable_pixel_dumping =
(pixel_switch == "--pixel-test" || pixel_switch == "-p");
}
if (expected_pixel_hash)
*expected_pixel_hash = pixel_hash;
GURL test_url(path_or_url);
if (!(test_url.is_valid() && test_url.has_scheme())) {
// We're outside of the message loop here, and this is a test.
base::ThreadRestrictions::ScopedAllowIO allow_io;
#if defined(OS_WIN)
std::wstring wide_path_or_url =
base::SysNativeMBToWide(path_or_url);
base::FilePath local_file(wide_path_or_url);
#else
base::FilePath local_file(path_or_url);
#endif
file_util::AbsolutePath(&local_file);
test_url = net::FilePathToFileURL(local_file);
}
base::FilePath local_path;
if (current_working_directory) {
// We're outside of the message loop here, and this is a test.
base::ThreadRestrictions::ScopedAllowIO allow_io;
if (net::FileURLToFilePath(test_url, &local_path))
*current_working_directory = local_path.DirName();
else
file_util::GetCurrentDirectory(current_working_directory);
}
return test_url;
}
bool GetNextTest(const CommandLine::StringVector& args,
size_t* position,
std::string* test) {
if (*position >= args.size())
return false;
if (args[*position] == FILE_PATH_LITERAL("-"))
return !!std::getline(std::cin, *test, '\n');
#if defined(OS_WIN)
*test = WideToUTF8(args[(*position)++]);
#else
*test = args[(*position)++];
#endif
return true;
}
} // namespace
// Main routine for running as the Browser process.
int ShellBrowserMain(const content::MainFunctionParams& parameters) {
bool layout_test_mode =
CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree);
base::ScopedTempDir browser_context_path_for_layout_tests;
if (layout_test_mode) {
CHECK(browser_context_path_for_layout_tests.CreateUniqueTempDir());
CHECK(!browser_context_path_for_layout_tests.path().MaybeAsASCII().empty());
CommandLine::ForCurrentProcess()->AppendSwitchASCII(
switches::kContentShellDataPath,
browser_context_path_for_layout_tests.path().MaybeAsASCII());
}
scoped_ptr<content::BrowserMainRunner> main_runner_(
content::BrowserMainRunner::Create());
int exit_code = main_runner_->Initialize(parameters);
if (exit_code >= 0)
return exit_code;
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kCheckLayoutTestSysDeps)) {
MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
main_runner_->Run();
main_runner_->Shutdown();
return 0;
}
if (layout_test_mode) {
content::WebKitTestController test_controller;
{
// We're outside of the message loop here, and this is a test.
base::ThreadRestrictions::ScopedAllowIO allow_io;
base::FilePath temp_path;
file_util::GetTempDir(&temp_path);
test_controller.SetTempPath(temp_path);
}
std::string test_string;
CommandLine::StringVector args =
CommandLine::ForCurrentProcess()->GetArgs();
size_t command_line_position = 0;
bool ran_at_least_once = false;
#if defined(OS_ANDROID)
std::cout << "#READY\n";
std::cout.flush();
#endif
while (GetNextTest(args, &command_line_position, &test_string)) {
if (test_string.empty())
continue;
if (test_string == "QUIT")
break;
bool enable_pixel_dumps;
std::string pixel_hash;
base::FilePath cwd;
GURL test_url = GetURLForLayoutTest(
test_string, &cwd, &enable_pixel_dumps, &pixel_hash);
if (!content::WebKitTestController::Get()->PrepareForLayoutTest(
test_url, cwd, enable_pixel_dumps, pixel_hash)) {
break;
}
ran_at_least_once = true;
main_runner_->Run();
if (!content::WebKitTestController::Get()->ResetAfterLayoutTest())
break;
}
if (!ran_at_least_once) {
MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
main_runner_->Run();
}
exit_code = 0;
} else {
exit_code = main_runner_->Run();
}
main_runner_->Shutdown();
return exit_code;
}
<|endoftext|> |
<commit_before>#include <string>
#include <iostream>
#include <math.h>
#include <stdio.h>
#include <node_buffer.h>
#include "NativeArray.h"
#include "request.h"
using namespace std;
using namespace v8;
static nj::Type *getPrimitiveType(const Local<Value> &prim)
{
if(prim->IsNull()) return nj::Null_t::instance();
else if(prim->IsBoolean()) return nj::Boolean_t::instance();
else if(prim->IsNumber())
{
double v_d = prim->NumberValue();
if(trunc(v_d) == v_d) return nj::Int64_t::instance();
return nj::Float64_t::instance();
}
else if(prim->IsString()) return nj::UTF8String_t::instance();
else if(prim->IsDate()) return nj::Date_t::instance();
return 0;
}
static shared_ptr<nj::Value> createPrimitiveReq(const Local<Value> &prim)
{
shared_ptr<nj::Value> v;
if(prim->IsNull()) v.reset(new nj::Null());
else if(prim->IsBoolean()) v.reset(new nj::Boolean(prim->BooleanValue()));
else if(prim->IsNumber())
{
double v_d = prim->NumberValue();
if(trunc(v_d) == v_d) v.reset(new nj::Int64(prim->IntegerValue()));
else v.reset(new nj::Float64(v_d));
}
else if(prim->IsString())
{
Local<String> s = Local<String>::Cast(prim);
String::Utf8Value text(s);
v.reset(new nj::UTF8String(*text));
}
return v;
}
double getDateValue(const Local<Value> &val)
{
Local<Date> s = Local<Date>::Cast(val);
return s->NumberValue();
}
static shared_ptr<nj::Value> createDateReq(const Local<Value> &value)
{
double milliseconds = getDateValue(value);
return shared_ptr<nj::Value>(new nj::Date(milliseconds));
}
static shared_ptr<nj::Value> createRegexReq(const Local<Value> &value)
{
Local<RegExp> re = Local<RegExp>::Cast(value);
Local<String> s = re->GetSource();
String::Utf8Value text(s);
return shared_ptr<nj::Value>(new nj::Regex(*text));
}
static void examineArray(Local<Array> &a,size_t level,vector<size_t> &dims,nj::Type *&etype,bool &determineDimensions) throw(nj::InvalidException)
{
size_t len = a->Length();
for(size_t i = 0;i < len;i++)
{
Local<Value> el = a->Get(i);
if(determineDimensions)
{
dims.push_back(len);
if(!el->IsArray()) determineDimensions = false;
}
else
{
if(level == dims.size() || len != dims[level]) throw(nj::InvalidException("malformed array"));
if(!el->IsArray() && level != dims.size() - 1) throw(nj::InvalidException("malformed array"));
if(el->IsArray() && level == dims.size() - 1) throw(nj::InvalidException("malformed array"));
}
if(el->IsArray())
{
Local<Array> sub = Local<Array>::Cast(el);
examineArray(sub,level + 1,dims,etype,determineDimensions);
}
else
{
nj::Type *etypeNarrow = getPrimitiveType(el);
if(!etypeNarrow) throw(nj::InvalidException("unknown array element type"));
if(!etype || *etype < *etypeNarrow) etype = etypeNarrow;
if((etype->getId() == nj::int64_type || etype->getId() == nj::uint64_type) && etypeNarrow->getId() == nj::float64_type) etype = etypeNarrow;
if(etype != etypeNarrow && !(*etype < *etypeNarrow)) etype = nj::Any_t::instance();
}
}
}
static unsigned char getNullValue(const Local<Value> &val)
{
return 0;
}
static unsigned char getBooleanValue(const Local<Value> &val)
{
return val->BooleanValue();
}
static int getInt32Value(const Local<Value> &val)
{
return val->Int32Value();
}
static unsigned int getUInt32Value(const Local<Value> &val)
{
return val->Uint32Value();
}
static int64_t getInt64Value(const Local<Value> &val)
{
return val->IntegerValue();
}
static double getFloat64Value(const Local<Value> &val)
{
return val->NumberValue();
}
static string getStringValue(const Local<Value> &val)
{
String::Utf8Value text(val);
return string(*text);
}
template <typename V,V (&accessor)(const Local<Value>&)> static void fillSubArray(const vector<size_t> &dims,const vector<size_t> &strides,size_t ixNum,size_t offset,V *to,const Local<Array> &from)
{
size_t numElements = dims[ixNum];
size_t stride = strides[ixNum];
if(ixNum == dims.size() - 1)
{
for(size_t elementNum = 0;elementNum < numElements;elementNum++)
{
*(to + offset) = accessor(from->Get(elementNum));
offset += stride;
}
}
else
{
for(size_t elementNum = 0;elementNum < numElements;elementNum++)
{
Local<Array> subArray = Local<Array>::Cast(from->Get(elementNum));
fillSubArray<V,accessor>(dims,strides,ixNum + 1,offset,to,subArray);
offset += stride;
}
}
}
template <typename V,typename E,V (&accessor)(const Local<Value>&)> static void fillArray(shared_ptr<nj::Value> &to,const Local<Array> &from)
{
nj::Array<V,E> &a = static_cast<nj::Array<V,E>&>(*to);
V *p = a.ptr();
if(a.dims().size() == 1)
{
size_t length = a.dims()[0];
for(size_t index = 0;index < length;index++) *p++ = accessor(from->Get(index));
}
else if(a.dims().size() == 2)
{
size_t rows = a.dims()[0];
size_t cols = a.dims()[1];
for(size_t row = 0;row < rows;row++)
{
Local<Array> rowVector = Local<Array>::Cast(from->Get(row));
for(size_t col = 0;col < cols;col++) p[col*rows + row] = accessor(rowVector->Get(col));
}
}
else
{
vector<size_t> strides;
strides.push_back(1);
for(size_t idxNum = 1;idxNum < a.dims().size();idxNum++) strides.push_back(a.dims()[idxNum]*strides[idxNum - 1]);
fillSubArray<V,accessor>(a.dims(),strides,0,0,a.ptr(),from);
}
}
static shared_ptr<nj::Value> createArrayReqFromArray(const Local<Value> &from)
{
shared_ptr<nj::Value> to;
if(from->IsArray())
{
Local<Array> a = Local<Array>::Cast(from);
vector<size_t> dims;
bool determineDimensions = true;
nj::Type *etype = 0;
try
{
examineArray(a,0,dims,etype,determineDimensions);
if(dims[0] == 0)
{
to.reset(new nj::Array<char,nj::Any_t>(dims));
return to;
}
if(etype)
{
switch(etype->getId())
{
case nj::null_type:
to.reset(new nj::Array<unsigned char,nj::Null_t>(dims));
fillArray<unsigned char,nj::Null_t,getNullValue>(to,a);
break;
case nj::boolean_type:
to.reset(new nj::Array<unsigned char,nj::Boolean_t>(dims));
fillArray<unsigned char,nj::Boolean_t,getBooleanValue>(to,a);
break;
case nj::int32_type:
to.reset(new nj::Array<int,nj::Int32_t>(dims));
fillArray<int,nj::Int32_t,getInt32Value>(to,a);
break;
case nj::uint32_type:
to.reset(new nj::Array<unsigned int,nj::UInt32_t>(dims));
fillArray<unsigned int,nj::UInt32_t,getUInt32Value>(to,a);
break;
case nj::int64_type:
to.reset(new nj::Array<int64_t,nj::Int64_t>(dims));
fillArray<int64_t,nj::Int64_t,getInt64Value>(to,a);
break;
case nj::float64_type:
to.reset(new nj::Array<double,nj::Float64_t>(dims));
fillArray<double,nj::Float64_t,getFloat64Value>(to,a);
break;
case nj::ascii_string_type:
case nj::utf8_string_type:
to.reset(new nj::Array<string,nj::UTF8String_t>(dims));
fillArray<string,nj::UTF8String_t,getStringValue>(to,a);
break;
case nj::date_type:
to.reset(new nj::Array<double,nj::Date_t>(dims));
fillArray<double,nj::Date_t,getDateValue>(to,a);
break;
}
}
}
catch(nj::InvalidException e) {}
}
return to;
}
static shared_ptr<nj::Value> createArrayReqFromBuffer(const Local<Value> &from)
{
Local<Object> buffer = from->ToObject();
char *data = node::Buffer::Data(buffer);
size_t len = node::Buffer::Length(buffer);
shared_ptr<nj::Value> to;
vector<size_t> dims;
dims.push_back(len);
to.reset(new nj::Array<unsigned char,nj::UInt8_t>(dims));
nj::Array<unsigned char,nj::UInt8_t> &a = static_cast<nj::Array<unsigned char,nj::UInt8_t>&>(*to);
unsigned char *p = a.ptr();
for(size_t index = 0;index < len;index++) *p++ = *data++;
return to;
}
template <typename V,typename E> static shared_ptr<nj::Value> createArrayReqFromNativeArray(const Local<Object> &array)
{
shared_ptr<nj::Value> to;
nj::NativeArray<V> nat(array);
const V *data = nat.dptr();
if(data)
{
vector<size_t> dims;
dims.push_back(nat.len());
to.reset(new nj::Array<V,E>(dims));
nj::Array<V,E> &a = static_cast<nj::Array<V,E>&>(*to);
V *p = a.ptr();
for(unsigned int index = 0;index < nat.len();index++) *p++ = *data++;
}
return to;
}
shared_ptr<nj::Value> createRequest(const Local<Value> &value)
{
if(value->IsArray()) return createArrayReqFromArray(value);
else if(value->IsDate()) return createDateReq(value);
else if(value->IsRegExp()) return createRegexReq(value);
else if(node::Buffer::HasInstance(value)) return createArrayReqFromBuffer(value);
else if(value->IsObject())
{
Local<Object> obj = value->ToObject();
String::Utf8Value utf(obj->GetConstructorName());
string cname(*utf);
if(cname == "Int8Array") return createArrayReqFromNativeArray<char,nj::Int8_t>(obj);
else if(cname == "Uint8Array") return createArrayReqFromNativeArray<unsigned char,nj::UInt8_t>(obj);
else if(cname == "Int16Array") return createArrayReqFromNativeArray<short,nj::Int16_t>(obj);
else if(cname == "Uint16Array") return createArrayReqFromNativeArray<unsigned short,nj::UInt16_t>(obj);
else if(cname == "Int32Array") return createArrayReqFromNativeArray<int,nj::Int32_t>(obj);
else if(cname == "Uint32Array") return createArrayReqFromNativeArray<unsigned int,nj::UInt32_t>(obj);
else if(cname == "Float32Array") return createArrayReqFromNativeArray<float,nj::Float32_t>(obj);
else if(cname == "Float64Array") return createArrayReqFromNativeArray<double,nj::Float64_t>(obj);
}
return createPrimitiveReq(value);
}
<commit_msg>more template function args<commit_after>#include <string>
#include <iostream>
#include <math.h>
#include <stdio.h>
#include <node_buffer.h>
#include "NativeArray.h"
#include "request.h"
using namespace std;
using namespace v8;
static nj::Type *getPrimitiveType(const Local<Value> &prim)
{
if(prim->IsNull()) return nj::Null_t::instance();
else if(prim->IsBoolean()) return nj::Boolean_t::instance();
else if(prim->IsNumber())
{
double v_d = prim->NumberValue();
if(trunc(v_d) == v_d) return nj::Int64_t::instance();
return nj::Float64_t::instance();
}
else if(prim->IsString()) return nj::UTF8String_t::instance();
else if(prim->IsDate()) return nj::Date_t::instance();
return 0;
}
static shared_ptr<nj::Value> createPrimitiveReq(const Local<Value> &prim)
{
shared_ptr<nj::Value> v;
if(prim->IsNull()) v.reset(new nj::Null());
else if(prim->IsBoolean()) v.reset(new nj::Boolean(prim->BooleanValue()));
else if(prim->IsNumber())
{
double v_d = prim->NumberValue();
if(trunc(v_d) == v_d) v.reset(new nj::Int64(prim->IntegerValue()));
else v.reset(new nj::Float64(v_d));
}
else if(prim->IsString())
{
Local<String> s = Local<String>::Cast(prim);
String::Utf8Value text(s);
v.reset(new nj::UTF8String(*text));
}
return v;
}
double getDateValue(const Local<Value> &val)
{
Local<Date> s = Local<Date>::Cast(val);
return s->NumberValue();
}
static shared_ptr<nj::Value> createDateReq(const Local<Value> &value)
{
double milliseconds = getDateValue(value);
return shared_ptr<nj::Value>(new nj::Date(milliseconds));
}
static shared_ptr<nj::Value> createRegexReq(const Local<Value> &value)
{
Local<RegExp> re = Local<RegExp>::Cast(value);
Local<String> s = re->GetSource();
String::Utf8Value text(s);
return shared_ptr<nj::Value>(new nj::Regex(*text));
}
static void examineArray(Local<Array> &a,size_t level,vector<size_t> &dims,nj::Type *&etype,bool &determineDimensions) throw(nj::InvalidException)
{
size_t len = a->Length();
for(size_t i = 0;i < len;i++)
{
Local<Value> el = a->Get(i);
if(determineDimensions)
{
dims.push_back(len);
if(!el->IsArray()) determineDimensions = false;
}
else
{
if(level == dims.size() || len != dims[level]) throw(nj::InvalidException("malformed array"));
if(!el->IsArray() && level != dims.size() - 1) throw(nj::InvalidException("malformed array"));
if(el->IsArray() && level == dims.size() - 1) throw(nj::InvalidException("malformed array"));
}
if(el->IsArray())
{
Local<Array> sub = Local<Array>::Cast(el);
examineArray(sub,level + 1,dims,etype,determineDimensions);
}
else
{
nj::Type *etypeNarrow = getPrimitiveType(el);
if(!etypeNarrow) throw(nj::InvalidException("unknown array element type"));
if(!etype || *etype < *etypeNarrow) etype = etypeNarrow;
if((etype->getId() == nj::int64_type || etype->getId() == nj::uint64_type) && etypeNarrow->getId() == nj::float64_type) etype = etypeNarrow;
if(etype != etypeNarrow && !(*etype < *etypeNarrow)) etype = nj::Any_t::instance();
}
}
}
unsigned char getNullValue(const Local<Value> &val)
{
return 0;
}
unsigned char getBooleanValue(const Local<Value> &val)
{
return val->BooleanValue();
}
int getInt32Value(const Local<Value> &val)
{
return val->Int32Value();
}
unsigned int getUInt32Value(const Local<Value> &val)
{
return val->Uint32Value();
}
int64_t getInt64Value(const Local<Value> &val)
{
return val->IntegerValue();
}
double getFloat64Value(const Local<Value> &val)
{
return val->NumberValue();
}
string getStringValue(const Local<Value> &val)
{
String::Utf8Value text(val);
return string(*text);
}
template <typename V,V (&accessor)(const Local<Value>&)> static void fillSubArray(const vector<size_t> &dims,const vector<size_t> &strides,size_t ixNum,size_t offset,V *to,const Local<Array> &from)
{
size_t numElements = dims[ixNum];
size_t stride = strides[ixNum];
if(ixNum == dims.size() - 1)
{
for(size_t elementNum = 0;elementNum < numElements;elementNum++)
{
*(to + offset) = accessor(from->Get(elementNum));
offset += stride;
}
}
else
{
for(size_t elementNum = 0;elementNum < numElements;elementNum++)
{
Local<Array> subArray = Local<Array>::Cast(from->Get(elementNum));
fillSubArray<V,accessor>(dims,strides,ixNum + 1,offset,to,subArray);
offset += stride;
}
}
}
template <typename V,typename E,V (&accessor)(const Local<Value>&)> static void fillArray(shared_ptr<nj::Value> &to,const Local<Array> &from)
{
nj::Array<V,E> &a = static_cast<nj::Array<V,E>&>(*to);
V *p = a.ptr();
if(a.dims().size() == 1)
{
size_t length = a.dims()[0];
for(size_t index = 0;index < length;index++) *p++ = accessor(from->Get(index));
}
else if(a.dims().size() == 2)
{
size_t rows = a.dims()[0];
size_t cols = a.dims()[1];
for(size_t row = 0;row < rows;row++)
{
Local<Array> rowVector = Local<Array>::Cast(from->Get(row));
for(size_t col = 0;col < cols;col++) p[col*rows + row] = accessor(rowVector->Get(col));
}
}
else
{
vector<size_t> strides;
strides.push_back(1);
for(size_t idxNum = 1;idxNum < a.dims().size();idxNum++) strides.push_back(a.dims()[idxNum]*strides[idxNum - 1]);
fillSubArray<V,accessor>(a.dims(),strides,0,0,a.ptr(),from);
}
}
static shared_ptr<nj::Value> createArrayReqFromArray(const Local<Value> &from)
{
shared_ptr<nj::Value> to;
if(from->IsArray())
{
Local<Array> a = Local<Array>::Cast(from);
vector<size_t> dims;
bool determineDimensions = true;
nj::Type *etype = 0;
try
{
examineArray(a,0,dims,etype,determineDimensions);
if(dims[0] == 0)
{
to.reset(new nj::Array<char,nj::Any_t>(dims));
return to;
}
if(etype)
{
switch(etype->getId())
{
case nj::null_type:
to.reset(new nj::Array<unsigned char,nj::Null_t>(dims));
fillArray<unsigned char,nj::Null_t,getNullValue>(to,a);
break;
case nj::boolean_type:
to.reset(new nj::Array<unsigned char,nj::Boolean_t>(dims));
fillArray<unsigned char,nj::Boolean_t,getBooleanValue>(to,a);
break;
case nj::int32_type:
to.reset(new nj::Array<int,nj::Int32_t>(dims));
fillArray<int,nj::Int32_t,getInt32Value>(to,a);
break;
case nj::uint32_type:
to.reset(new nj::Array<unsigned int,nj::UInt32_t>(dims));
fillArray<unsigned int,nj::UInt32_t,getUInt32Value>(to,a);
break;
case nj::int64_type:
to.reset(new nj::Array<int64_t,nj::Int64_t>(dims));
fillArray<int64_t,nj::Int64_t,getInt64Value>(to,a);
break;
case nj::float64_type:
to.reset(new nj::Array<double,nj::Float64_t>(dims));
fillArray<double,nj::Float64_t,getFloat64Value>(to,a);
break;
case nj::ascii_string_type:
case nj::utf8_string_type:
to.reset(new nj::Array<string,nj::UTF8String_t>(dims));
fillArray<string,nj::UTF8String_t,getStringValue>(to,a);
break;
case nj::date_type:
to.reset(new nj::Array<double,nj::Date_t>(dims));
fillArray<double,nj::Date_t,getDateValue>(to,a);
break;
}
}
}
catch(nj::InvalidException e) {}
}
return to;
}
static shared_ptr<nj::Value> createArrayReqFromBuffer(const Local<Value> &from)
{
Local<Object> buffer = from->ToObject();
char *data = node::Buffer::Data(buffer);
size_t len = node::Buffer::Length(buffer);
shared_ptr<nj::Value> to;
vector<size_t> dims;
dims.push_back(len);
to.reset(new nj::Array<unsigned char,nj::UInt8_t>(dims));
nj::Array<unsigned char,nj::UInt8_t> &a = static_cast<nj::Array<unsigned char,nj::UInt8_t>&>(*to);
unsigned char *p = a.ptr();
for(size_t index = 0;index < len;index++) *p++ = *data++;
return to;
}
template <typename V,typename E> static shared_ptr<nj::Value> createArrayReqFromNativeArray(const Local<Object> &array)
{
shared_ptr<nj::Value> to;
nj::NativeArray<V> nat(array);
const V *data = nat.dptr();
if(data)
{
vector<size_t> dims;
dims.push_back(nat.len());
to.reset(new nj::Array<V,E>(dims));
nj::Array<V,E> &a = static_cast<nj::Array<V,E>&>(*to);
V *p = a.ptr();
for(unsigned int index = 0;index < nat.len();index++) *p++ = *data++;
}
return to;
}
shared_ptr<nj::Value> createRequest(const Local<Value> &value)
{
if(value->IsArray()) return createArrayReqFromArray(value);
else if(value->IsDate()) return createDateReq(value);
else if(value->IsRegExp()) return createRegexReq(value);
else if(node::Buffer::HasInstance(value)) return createArrayReqFromBuffer(value);
else if(value->IsObject())
{
Local<Object> obj = value->ToObject();
String::Utf8Value utf(obj->GetConstructorName());
string cname(*utf);
if(cname == "Int8Array") return createArrayReqFromNativeArray<char,nj::Int8_t>(obj);
else if(cname == "Uint8Array") return createArrayReqFromNativeArray<unsigned char,nj::UInt8_t>(obj);
else if(cname == "Int16Array") return createArrayReqFromNativeArray<short,nj::Int16_t>(obj);
else if(cname == "Uint16Array") return createArrayReqFromNativeArray<unsigned short,nj::UInt16_t>(obj);
else if(cname == "Int32Array") return createArrayReqFromNativeArray<int,nj::Int32_t>(obj);
else if(cname == "Uint32Array") return createArrayReqFromNativeArray<unsigned int,nj::UInt32_t>(obj);
else if(cname == "Float32Array") return createArrayReqFromNativeArray<float,nj::Float32_t>(obj);
else if(cname == "Float64Array") return createArrayReqFromNativeArray<double,nj::Float64_t>(obj);
}
return createPrimitiveReq(value);
}
<|endoftext|> |
<commit_before>//===- ModStream.cpp - PDB Module Info Stream Access ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/Raw/ModStream.h"
#include "llvm/DebugInfo/CodeView/StreamReader.h"
#include "llvm/DebugInfo/PDB/Raw/ModInfo.h"
#include "llvm/DebugInfo/PDB/Raw/PDBFile.h"
#include "llvm/DebugInfo/PDB/Raw/RawError.h"
using namespace llvm;
using namespace llvm::pdb;
ModStream::ModStream(PDBFile &File, const ModInfo &Module)
: Mod(Module), Stream(Module.getModuleStreamIndex(), File) {}
ModStream::~ModStream() {}
Error ModStream::reload() {
codeview::StreamReader Reader(Stream);
uint32_t SymbolSize = Mod.getSymbolDebugInfoByteSize();
uint32_t C11Size = Mod.getLineInfoByteSize();
uint32_t C13Size = Mod.getC13LineInfoByteSize();
if (C11Size > 0 && C13Size > 0)
return llvm::make_error<RawError>(raw_error_code::corrupt_file,
"Module has both C11 and C13 line info");
codeview::StreamRef S;
uint32_t SymbolSubstreamSig = 0;
if (auto EC = Reader.readInteger(SymbolSubstreamSig))
return EC;
if (auto EC = Reader.readArray(SymbolsSubstream, SymbolSize - 4))
return EC;
if (auto EC = Reader.readStreamRef(LinesSubstream, C11Size))
return EC;
if (auto EC = Reader.readStreamRef(C13LinesSubstream, C13Size))
return EC;
uint32_t GlobalRefsSize;
if (auto EC = Reader.readInteger(GlobalRefsSize))
return EC;
if (auto EC = Reader.readStreamRef(GlobalRefsSubstream, GlobalRefsSize))
return EC;
if (Reader.bytesRemaining() > 0)
return llvm::make_error<RawError>(raw_error_code::corrupt_file,
"Unexpected bytes in module stream.");
return Error::success();
}
iterator_range<codeview::CVSymbolArray::Iterator>
ModStream::symbols(bool *HadError) const {
return llvm::make_range(SymbolsSubstream.begin(), SymbolsSubstream.end());
}
<commit_msg>[PDB] Make ModStream::symbols report errors<commit_after>//===- ModStream.cpp - PDB Module Info Stream Access ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/Raw/ModStream.h"
#include "llvm/DebugInfo/CodeView/StreamReader.h"
#include "llvm/DebugInfo/PDB/Raw/ModInfo.h"
#include "llvm/DebugInfo/PDB/Raw/PDBFile.h"
#include "llvm/DebugInfo/PDB/Raw/RawError.h"
using namespace llvm;
using namespace llvm::pdb;
ModStream::ModStream(PDBFile &File, const ModInfo &Module)
: Mod(Module), Stream(Module.getModuleStreamIndex(), File) {}
ModStream::~ModStream() {}
Error ModStream::reload() {
codeview::StreamReader Reader(Stream);
uint32_t SymbolSize = Mod.getSymbolDebugInfoByteSize();
uint32_t C11Size = Mod.getLineInfoByteSize();
uint32_t C13Size = Mod.getC13LineInfoByteSize();
if (C11Size > 0 && C13Size > 0)
return llvm::make_error<RawError>(raw_error_code::corrupt_file,
"Module has both C11 and C13 line info");
codeview::StreamRef S;
uint32_t SymbolSubstreamSig = 0;
if (auto EC = Reader.readInteger(SymbolSubstreamSig))
return EC;
if (auto EC = Reader.readArray(SymbolsSubstream, SymbolSize - 4))
return EC;
if (auto EC = Reader.readStreamRef(LinesSubstream, C11Size))
return EC;
if (auto EC = Reader.readStreamRef(C13LinesSubstream, C13Size))
return EC;
uint32_t GlobalRefsSize;
if (auto EC = Reader.readInteger(GlobalRefsSize))
return EC;
if (auto EC = Reader.readStreamRef(GlobalRefsSubstream, GlobalRefsSize))
return EC;
if (Reader.bytesRemaining() > 0)
return llvm::make_error<RawError>(raw_error_code::corrupt_file,
"Unexpected bytes in module stream.");
return Error::success();
}
iterator_range<codeview::CVSymbolArray::Iterator>
ModStream::symbols(bool *HadError) const {
return llvm::make_range(SymbolsSubstream.begin(HadError),
SymbolsSubstream.end());
}
<|endoftext|> |
<commit_before>#include <math.h>
#include <robot_p/robothw.h>
#include <boost/math/constants/constants.hpp>
using namespace robotp;
RobotHW::RobotHW(ros::NodeHandle &nh_private)
: jnt_state_interface()
, jnt_vel_interface()
, serial_()
, full_speed_(0)
, input_buff_()
{
// connect and register the joint state interface
hardware_interface::JointStateHandle state_handle_left(
"front_left_wheel", &pos_[LEFT], &vel_[LEFT], &eff_[LEFT]);
jnt_state_interface.registerHandle(state_handle_left);
hardware_interface::JointStateHandle state_handle_right(
"front_right_wheel", &pos_[RIGHT], &vel_[RIGHT], &eff_[RIGHT]);
jnt_state_interface.registerHandle(state_handle_right);
registerInterface(&jnt_state_interface);
// connect and register the joint position interface
hardware_interface::JointHandle vel_handle_left(
jnt_state_interface.getHandle("front_left_wheel"), &cmd_[LEFT]);
jnt_vel_interface.registerHandle(vel_handle_left);
hardware_interface::JointHandle vel_handle_right(
jnt_state_interface.getHandle("front_right_wheel"), &cmd_[RIGHT]);
jnt_vel_interface.registerHandle(vel_handle_right);
registerInterface(&jnt_vel_interface);
// initialize parameters
std::string port;
int serial_baudrate = 0;
nh_private.param<double>("full_speed", full_speed_, 3.14);
nh_private.param<std::string>("serial_port", port, "/dev/ttyS0");
nh_private.param<int>("serial_baudrate", serial_baudrate, 57600);
serial_.setPort(port);
serial_.setBaudrate(serial_baudrate);
auto timeout = serial::Timeout::simpleTimeout(serial::Timeout::max());
serial_.setTimeout(timeout);
try {
serial_.open();
} catch (const std::exception &e) {
ROS_ERROR_STREAM("[ROBOTHW]: Serial exception: " << e.what());
return;
}
}
robotp::RobotHW::~RobotHW()
{
sendMsg(createVelocityMsg(0., 0.));
}
void RobotHW::read(const ros::Time &time, const ros::Duration &period)
{
// we don't read odom from controller
if (serial_.available() > 0) {
ROS_INFO_STREAM(
"ROBOT_P_CONTROL: serial: " << serial_.read(serial_.available()));
}
for (size_t i = 0; i < 2; ++i) {
vel_[i] = 0; // rad/s
pos_[i] += 0;
eff_[i] = 0;
}
}
void RobotHW::write()
{
sendMsg(createVelocityMsg(cmd_[0], cmd_[1]));
}
inline static int radiansToPWM(double vel)
{
double speed_factor = vel / full_speed;
int pwm = (int)(speed_factor * 255);
// ensure to stay in boundaries
return std::max(std::min(pwm, 255), -255);
}
robotp::RobotHW::Msg32
robotp::RobotHW::createVelocityMsg(double left_vel, double right_vel) const
{
Msg32 msg;
msg.id = 'V';
msg.crc = 0;
// input speeds are in rad/s
msg.left = radiansToPWM(left_vel);
msg.right = radiansToPWM(right_vel);
ROS_INFO_STREAM("ROBOT_P_CONTROL: speed: " << msg.left << " " << msg.right);
return msg;
}
<commit_msg>fixup! remove useless things in controller<commit_after>#include <math.h>
#include <robot_p/robothw.h>
#include <boost/math/constants/constants.hpp>
using namespace robotp;
RobotHW::RobotHW(ros::NodeHandle &nh_private)
: jnt_state_interface()
, jnt_vel_interface()
, serial_()
, full_speed_(0)
, input_buff_()
{
// connect and register the joint state interface
hardware_interface::JointStateHandle state_handle_left(
"front_left_wheel", &pos_[LEFT], &vel_[LEFT], &eff_[LEFT]);
jnt_state_interface.registerHandle(state_handle_left);
hardware_interface::JointStateHandle state_handle_right(
"front_right_wheel", &pos_[RIGHT], &vel_[RIGHT], &eff_[RIGHT]);
jnt_state_interface.registerHandle(state_handle_right);
registerInterface(&jnt_state_interface);
// connect and register the joint position interface
hardware_interface::JointHandle vel_handle_left(
jnt_state_interface.getHandle("front_left_wheel"), &cmd_[LEFT]);
jnt_vel_interface.registerHandle(vel_handle_left);
hardware_interface::JointHandle vel_handle_right(
jnt_state_interface.getHandle("front_right_wheel"), &cmd_[RIGHT]);
jnt_vel_interface.registerHandle(vel_handle_right);
registerInterface(&jnt_vel_interface);
// initialize parameters
std::string port;
int serial_baudrate = 0;
nh_private.param<double>("full_speed", full_speed_, 3.14);
nh_private.param<std::string>("serial_port", port, "/dev/ttyS0");
nh_private.param<int>("serial_baudrate", serial_baudrate, 57600);
serial_.setPort(port);
serial_.setBaudrate(serial_baudrate);
auto timeout = serial::Timeout::simpleTimeout(serial::Timeout::max());
serial_.setTimeout(timeout);
try {
serial_.open();
} catch (const std::exception &e) {
ROS_ERROR_STREAM("[ROBOTHW]: Serial exception: " << e.what());
return;
}
}
robotp::RobotHW::~RobotHW()
{
sendMsg(createVelocityMsg(0., 0.));
}
void RobotHW::read(const ros::Time &time, const ros::Duration &period)
{
// we don't read odom from controller
if (serial_.available() > 0) {
ROS_INFO_STREAM(
"ROBOT_P_CONTROL: serial: " << serial_.read(serial_.available()));
}
for (size_t i = 0; i < 2; ++i) {
vel_[i] = 0; // rad/s
pos_[i] += 0;
eff_[i] = 0;
}
}
void RobotHW::write()
{
sendMsg(createVelocityMsg(cmd_[0], cmd_[1]));
}
inline static int radiansToPWM(double vel)
{
double speed_factor = vel / full_speed_;
int pwm = (int)(speed_factor * 255);
// ensure to stay in boundaries
return std::max(std::min(pwm, 255), -255);
}
robotp::RobotHW::Msg32
robotp::RobotHW::createVelocityMsg(double left_vel, double right_vel) const
{
Msg32 msg;
msg.id = 'V';
msg.crc = 0;
// input speeds are in rad/s
msg.left = radiansToPWM(left_vel);
msg.right = radiansToPWM(right_vel);
ROS_INFO_STREAM("ROBOT_P_CONTROL: speed: " << msg.left << " " << msg.right);
return msg;
}
<|endoftext|> |
<commit_before>//=-- InstrProfWriter.cpp - Instrumented profiling writer -------------------=//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains support for writing profiling data for clang's
// instrumentation based PGO and coverage.
//
//===----------------------------------------------------------------------===//
#include "llvm/ProfileData/InstrProfWriter.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/EndianStream.h"
#include "llvm/Support/OnDiskHashTable.h"
using namespace llvm;
namespace {
static support::endianness ValueProfDataEndianness = support::little;
class InstrProfRecordTrait {
public:
typedef StringRef key_type;
typedef StringRef key_type_ref;
typedef const InstrProfWriter::ProfilingData *const data_type;
typedef const InstrProfWriter::ProfilingData *const data_type_ref;
typedef uint64_t hash_value_type;
typedef uint64_t offset_type;
static hash_value_type ComputeHash(key_type_ref K) {
return IndexedInstrProf::ComputeHash(IndexedInstrProf::HashType, K);
}
static std::pair<offset_type, offset_type>
EmitKeyDataLength(raw_ostream &Out, key_type_ref K, data_type_ref V) {
using namespace llvm::support;
endian::Writer<little> LE(Out);
offset_type N = K.size();
LE.write<offset_type>(N);
offset_type M = 0;
for (const auto &ProfileData : *V) {
const InstrProfRecord &ProfRecord = ProfileData.second;
M += sizeof(uint64_t); // The function hash
M += sizeof(uint64_t); // The size of the Counts vector
M += ProfRecord.Counts.size() * sizeof(uint64_t);
// Value data
M += ValueProfData::getSize(ProfileData.second);
}
LE.write<offset_type>(M);
return std::make_pair(N, M);
}
static void EmitKey(raw_ostream &Out, key_type_ref K, offset_type N){
Out.write(K.data(), N);
}
static void EmitData(raw_ostream &Out, key_type_ref, data_type_ref V,
offset_type) {
using namespace llvm::support;
endian::Writer<little> LE(Out);
for (const auto &ProfileData : *V) {
const InstrProfRecord &ProfRecord = ProfileData.second;
LE.write<uint64_t>(ProfileData.first); // Function hash
LE.write<uint64_t>(ProfRecord.Counts.size());
for (uint64_t I : ProfRecord.Counts)
LE.write<uint64_t>(I);
// Write value data
std::unique_ptr<ValueProfData> VDataPtr =
ValueProfData::serializeFrom(ProfileData.second);
uint32_t S = VDataPtr->getSize();
VDataPtr->swapBytesFromHost(ValueProfDataEndianness);
Out.write((const char *)VDataPtr.get(), S);
}
}
};
}
// Internal interface for testing purpose only.
void InstrProfWriter::setValueProfDataEndianness(
support::endianness Endianness) {
ValueProfDataEndianness = Endianness;
}
void InstrProfWriter::updateStringTableReferences(InstrProfRecord &I) {
I.updateStrings(&StringTable);
}
std::error_code InstrProfWriter::addRecord(InstrProfRecord &&I) {
updateStringTableReferences(I);
auto &ProfileDataMap = FunctionData[I.Name];
bool NewFunc;
ProfilingData::iterator Where;
std::tie(Where, NewFunc) =
ProfileDataMap.insert(std::make_pair(I.Hash, InstrProfRecord()));
InstrProfRecord &Dest = Where->second;
if (NewFunc) {
// We've never seen a function with this name and hash, add it.
Dest = std::move(I);
} else {
// We're updating a function we've seen before.
instrprof_error MergeResult = Dest.merge(I);
if (MergeResult != instrprof_error::success) {
return MergeResult;
}
}
// We keep track of the max function count as we go for simplicity.
if (Dest.Counts[0] > MaxFunctionCount)
MaxFunctionCount = Dest.Counts[0];
return instrprof_error::success;
}
std::pair<uint64_t, uint64_t> InstrProfWriter::writeImpl(raw_ostream &OS) {
OnDiskChainedHashTableGenerator<InstrProfRecordTrait> Generator;
// Populate the hash table generator.
for (const auto &I : FunctionData)
Generator.insert(I.getKey(), &I.getValue());
using namespace llvm::support;
endian::Writer<little> LE(OS);
// Write the header.
IndexedInstrProf::Header Header;
Header.Magic = IndexedInstrProf::Magic;
Header.Version = IndexedInstrProf::Version;
Header.MaxFunctionCount = MaxFunctionCount;
Header.HashType = static_cast<uint64_t>(IndexedInstrProf::HashType);
Header.HashOffset = 0;
int N = sizeof(IndexedInstrProf::Header) / sizeof(uint64_t);
// Only write out all the fields execpt 'HashOffset'. We need
// to remember the offset of that field to allow back patching
// later.
for (int I = 0; I < N - 1; I++)
LE.write<uint64_t>(reinterpret_cast<uint64_t *>(&Header)[I]);
// Save a space to write the hash table start location.
uint64_t HashTableStartLoc = OS.tell();
// Reserve the space for HashOffset field.
LE.write<uint64_t>(0);
// Write the hash table.
uint64_t HashTableStart = Generator.Emit(OS);
return std::make_pair(HashTableStartLoc, HashTableStart);
}
void InstrProfWriter::write(raw_fd_ostream &OS) {
// Write the hash table.
auto TableStart = writeImpl(OS);
// Go back and fill in the hash table start.
using namespace support;
OS.seek(TableStart.first);
// Now patch the HashOffset field previously reserved.
endian::Writer<little>(OS).write<uint64_t>(TableStart.second);
}
std::unique_ptr<MemoryBuffer> InstrProfWriter::writeBuffer() {
std::string Data;
llvm::raw_string_ostream OS(Data);
// Write the hash table.
auto TableStart = writeImpl(OS);
OS.flush();
// Go back and fill in the hash table start.
using namespace support;
uint64_t Bytes = endian::byte_swap<uint64_t, little>(TableStart.second);
Data.replace(TableStart.first, sizeof(uint64_t), (const char *)&Bytes,
sizeof(uint64_t));
// Return this in an aligned memory buffer.
return MemoryBuffer::getMemBufferCopy(Data);
}
<commit_msg>Fix the Windows build, include <tuple> for std::tie<commit_after>//=-- InstrProfWriter.cpp - Instrumented profiling writer -------------------=//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains support for writing profiling data for clang's
// instrumentation based PGO and coverage.
//
//===----------------------------------------------------------------------===//
#include "llvm/ProfileData/InstrProfWriter.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/EndianStream.h"
#include "llvm/Support/OnDiskHashTable.h"
#include <tuple>
using namespace llvm;
namespace {
static support::endianness ValueProfDataEndianness = support::little;
class InstrProfRecordTrait {
public:
typedef StringRef key_type;
typedef StringRef key_type_ref;
typedef const InstrProfWriter::ProfilingData *const data_type;
typedef const InstrProfWriter::ProfilingData *const data_type_ref;
typedef uint64_t hash_value_type;
typedef uint64_t offset_type;
static hash_value_type ComputeHash(key_type_ref K) {
return IndexedInstrProf::ComputeHash(IndexedInstrProf::HashType, K);
}
static std::pair<offset_type, offset_type>
EmitKeyDataLength(raw_ostream &Out, key_type_ref K, data_type_ref V) {
using namespace llvm::support;
endian::Writer<little> LE(Out);
offset_type N = K.size();
LE.write<offset_type>(N);
offset_type M = 0;
for (const auto &ProfileData : *V) {
const InstrProfRecord &ProfRecord = ProfileData.second;
M += sizeof(uint64_t); // The function hash
M += sizeof(uint64_t); // The size of the Counts vector
M += ProfRecord.Counts.size() * sizeof(uint64_t);
// Value data
M += ValueProfData::getSize(ProfileData.second);
}
LE.write<offset_type>(M);
return std::make_pair(N, M);
}
static void EmitKey(raw_ostream &Out, key_type_ref K, offset_type N){
Out.write(K.data(), N);
}
static void EmitData(raw_ostream &Out, key_type_ref, data_type_ref V,
offset_type) {
using namespace llvm::support;
endian::Writer<little> LE(Out);
for (const auto &ProfileData : *V) {
const InstrProfRecord &ProfRecord = ProfileData.second;
LE.write<uint64_t>(ProfileData.first); // Function hash
LE.write<uint64_t>(ProfRecord.Counts.size());
for (uint64_t I : ProfRecord.Counts)
LE.write<uint64_t>(I);
// Write value data
std::unique_ptr<ValueProfData> VDataPtr =
ValueProfData::serializeFrom(ProfileData.second);
uint32_t S = VDataPtr->getSize();
VDataPtr->swapBytesFromHost(ValueProfDataEndianness);
Out.write((const char *)VDataPtr.get(), S);
}
}
};
}
// Internal interface for testing purpose only.
void InstrProfWriter::setValueProfDataEndianness(
support::endianness Endianness) {
ValueProfDataEndianness = Endianness;
}
void InstrProfWriter::updateStringTableReferences(InstrProfRecord &I) {
I.updateStrings(&StringTable);
}
std::error_code InstrProfWriter::addRecord(InstrProfRecord &&I) {
updateStringTableReferences(I);
auto &ProfileDataMap = FunctionData[I.Name];
bool NewFunc;
ProfilingData::iterator Where;
std::tie(Where, NewFunc) =
ProfileDataMap.insert(std::make_pair(I.Hash, InstrProfRecord()));
InstrProfRecord &Dest = Where->second;
if (NewFunc) {
// We've never seen a function with this name and hash, add it.
Dest = std::move(I);
} else {
// We're updating a function we've seen before.
instrprof_error MergeResult = Dest.merge(I);
if (MergeResult != instrprof_error::success) {
return MergeResult;
}
}
// We keep track of the max function count as we go for simplicity.
if (Dest.Counts[0] > MaxFunctionCount)
MaxFunctionCount = Dest.Counts[0];
return instrprof_error::success;
}
std::pair<uint64_t, uint64_t> InstrProfWriter::writeImpl(raw_ostream &OS) {
OnDiskChainedHashTableGenerator<InstrProfRecordTrait> Generator;
// Populate the hash table generator.
for (const auto &I : FunctionData)
Generator.insert(I.getKey(), &I.getValue());
using namespace llvm::support;
endian::Writer<little> LE(OS);
// Write the header.
IndexedInstrProf::Header Header;
Header.Magic = IndexedInstrProf::Magic;
Header.Version = IndexedInstrProf::Version;
Header.MaxFunctionCount = MaxFunctionCount;
Header.HashType = static_cast<uint64_t>(IndexedInstrProf::HashType);
Header.HashOffset = 0;
int N = sizeof(IndexedInstrProf::Header) / sizeof(uint64_t);
// Only write out all the fields execpt 'HashOffset'. We need
// to remember the offset of that field to allow back patching
// later.
for (int I = 0; I < N - 1; I++)
LE.write<uint64_t>(reinterpret_cast<uint64_t *>(&Header)[I]);
// Save a space to write the hash table start location.
uint64_t HashTableStartLoc = OS.tell();
// Reserve the space for HashOffset field.
LE.write<uint64_t>(0);
// Write the hash table.
uint64_t HashTableStart = Generator.Emit(OS);
return std::make_pair(HashTableStartLoc, HashTableStart);
}
void InstrProfWriter::write(raw_fd_ostream &OS) {
// Write the hash table.
auto TableStart = writeImpl(OS);
// Go back and fill in the hash table start.
using namespace support;
OS.seek(TableStart.first);
// Now patch the HashOffset field previously reserved.
endian::Writer<little>(OS).write<uint64_t>(TableStart.second);
}
std::unique_ptr<MemoryBuffer> InstrProfWriter::writeBuffer() {
std::string Data;
llvm::raw_string_ostream OS(Data);
// Write the hash table.
auto TableStart = writeImpl(OS);
OS.flush();
// Go back and fill in the hash table start.
using namespace support;
uint64_t Bytes = endian::byte_swap<uint64_t, little>(TableStart.second);
Data.replace(TableStart.first, sizeof(uint64_t), (const char *)&Bytes,
sizeof(uint64_t));
// Return this in an aligned memory buffer.
return MemoryBuffer::getMemBufferCopy(Data);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "init.h"
#include "main.h"
#include "net.h"
#include "netbase.h"
#include "rpcserver.h"
#include "util.h"
#ifdef ENABLE_WALLET
#include "wallet.h"
#include "walletdb.h"
#endif
#include <stdint.h>
#include <boost/assign/list_of.hpp>
#include "json/json_spirit_utils.h"
#include "json/json_spirit_value.h"
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
Value getinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getinfo\n"
"Returns an object containing various state info.\n"
"\nResult:\n"
"{\n"
" \"version\": xxxxx, (numeric) the server version\n"
" \"protocolversion\": xxxxx, (numeric) the protocol version\n"
" \"walletversion\": xxxxx, (numeric) the wallet version\n"
" \"balance\": xxxxxxx, (numeric) the total auroracoin balance of the wallet\n"
" \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
" \"timeoffset\": xxxxx, (numeric) the time offset\n"
" \"connections\": xxxxx, (numeric) the number of connections\n"
" \"proxy\": \"host:port\", (string, optional) the proxy used by the server\n"
" \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
" \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since GMT epoch) of the oldest pre-generated key in the key pool\n"
" \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated\n"
" \"unlocked_until\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n"
" \"paytxfee\": x.xxxx, (numeric) the transaction fee set in aur/kb\n"
" \"relayfee\": x.xxxx, (numeric) minimum relay fee for non-free transactions in aur/kb\n"
" \"errors\": \"...\" (string) any error messages\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getinfo", "")
+ HelpExampleRpc("getinfo", "")
);
proxyType proxy;
GetProxy(NET_IPV4, proxy);
Object obj;
obj.push_back(Pair("version", (int)CLIENT_VERSION));
obj.push_back(Pair("protocolversion", (int)PROTOCOL_VERSION));
#ifdef ENABLE_WALLET
if (pwalletMain) {
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
}
#endif
obj.push_back(Pair("blocks", (int)chainActive.Height()));
obj.push_back(Pair("timeoffset", GetTimeOffset()));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string())));
obj.push_back(Pair("pow_algo_id", miningAlgo));
obj.push_back(Pair("pow_algo", GetAlgoName(miningAlgo)));
obj.push_back(Pair("difficulty", (double)GetDifficulty(NULL, miningAlgo)));
obj.push_back(Pair("difficulty_sha256d", (double)GetDifficulty(NULL, ALGO_SHA256D)));
obj.push_back(Pair("difficulty_scrypt", (double)GetDifficulty(NULL, ALGO_SCRYPT)));
obj.push_back(Pair("difficulty_groestl", (double)GetDifficulty(NULL, ALGO_GROESTL)));
obj.push_back(Pair("difficulty_skein", (double)GetDifficulty(NULL, ALGO_SKEIN)));
obj.push_back(Pair("difficulty_qubit", (double)GetDifficulty(NULL, ALGO_QUBIT)));
#ifdef ENABLE_WALLET
if (pwalletMain) {
obj.push_back(Pair("keypoololdest", pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize()));
}
if (pwalletMain && pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", nWalletUnlockTime));
obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
#endif
obj.push_back(Pair("relayfee", ValueFromAmount(CTransaction::nMinRelayTxFee)));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
return obj;
}
#ifdef ENABLE_WALLET
class DescribeAddressVisitor : public boost::static_visitor<Object>
{
public:
Object operator()(const CNoDestination &dest) const { return Object(); }
Object operator()(const CKeyID &keyID) const {
Object obj;
CPubKey vchPubKey;
pwalletMain->GetPubKey(keyID, vchPubKey);
obj.push_back(Pair("isscript", false));
obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
return obj;
}
Object operator()(const CScriptID &scriptID) const {
Object obj;
obj.push_back(Pair("isscript", true));
CScript subscript;
pwalletMain->GetCScript(scriptID, subscript);
std::vector<CTxDestination> addresses;
txnouttype whichType;
int nRequired;
ExtractDestinations(subscript, whichType, addresses, nRequired);
obj.push_back(Pair("script", GetTxnOutputType(whichType)));
obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end())));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
obj.push_back(Pair("addresses", a));
if (whichType == TX_MULTISIG)
obj.push_back(Pair("sigsrequired", nRequired));
return obj;
}
};
#endif
Value validateaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"validateaddress \"auroracoinaddress\"\n"
"\nReturn information about the given auroracoin address.\n"
"\nArguments:\n"
"1. \"auroracoinaddress\" (string, required) The auroracoin address to validate\n"
"\nResult:\n"
"{\n"
" \"isvalid\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\n"
" \"address\" : \"auroracoinaddress\", (string) The auroracoin address validated\n"
" \"ismine\" : true|false, (boolean) If the address is yours or not\n"
" \"isscript\" : true|false, (boolean) If the key is a script\n"
" \"pubkey\" : \"publickeyhex\", (string) The hex value of the raw public key\n"
" \"iscompressed\" : true|false, (boolean) If the address is compressed\n"
" \"account\" : \"account\" (string) The account associated with the address, \"\" is the default account\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")
+ HelpExampleRpc("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")
);
CBitcoinAddress address(params[0].get_str());
bool isValid = address.IsValid();
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
#ifdef ENABLE_WALLET
bool fMine = pwalletMain ? IsMine(*pwalletMain, dest) : false;
ret.push_back(Pair("ismine", fMine));
if (fMine) {
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain && pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest].name));
#endif
}
return ret;
}
//
// Used by addmultisigaddress / createmultisig:
//
CScript _createmultisig(const Array& params)
{
int nRequired = params[0].get_int();
const Array& keys = params[1].get_array();
// Gather public keys
if (nRequired < 1)
throw runtime_error("a multisignature address must require at least one key to redeem");
if ((int)keys.size() < nRequired)
throw runtime_error(
strprintf("not enough keys supplied "
"(got %u keys, but need at least %d to redeem)", keys.size(), nRequired));
std::vector<CPubKey> pubkeys;
pubkeys.resize(keys.size());
for (unsigned int i = 0; i < keys.size(); i++)
{
const std::string& ks = keys[i].get_str();
#ifdef ENABLE_WALLET
// Case 1: Bitcoin address and we have full public key:
CBitcoinAddress address(ks);
if (pwalletMain && address.IsValid())
{
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw runtime_error(
strprintf("%s does not refer to a key",ks));
CPubKey vchPubKey;
if (!pwalletMain->GetPubKey(keyID, vchPubKey))
throw runtime_error(
strprintf("no full public key for address %s",ks));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: "+ks);
pubkeys[i] = vchPubKey;
}
// Case 2: hex public key
else
#endif
if (IsHex(ks))
{
CPubKey vchPubKey(ParseHex(ks));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: "+ks);
pubkeys[i] = vchPubKey;
}
else
{
throw runtime_error(" Invalid public key: "+ks);
}
}
CScript result;
result.SetMultisig(nRequired, pubkeys);
return result;
}
Value createmultisig(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 2)
{
string msg = "createmultisig nrequired [\"key\",...]\n"
"\nCreates a multi-signature address with n signature of m keys required.\n"
"It returns a json object with the address and redeemScript.\n"
"\nArguments:\n"
"1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
"2. \"keys\" (string, required) A json array of keys which are auroracoin addresses or hex-encoded public keys\n"
" [\n"
" \"key\" (string) auroracoin address or hex-encoded public key\n"
" ,...\n"
" ]\n"
"\nResult:\n"
"{\n"
" \"address\":\"multisigaddress\", (string) The value of the new multisig address.\n"
" \"redeemScript\":\"script\" (string) The string value of the hex-encoded redemption script.\n"
"}\n"
"\nExamples:\n"
"\nCreate a multisig address from 2 addresses\n"
+ HelpExampleCli("createmultisig", "2 \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("createmultisig", "2, \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"")
;
throw runtime_error(msg);
}
// Construct using pay-to-script-hash:
CScript inner = _createmultisig(params);
CScriptID innerID = inner.GetID();
CBitcoinAddress address(innerID);
Object result;
result.push_back(Pair("address", address.ToString()));
result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end())));
return result;
}
Value verifymessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw runtime_error(
"verifymessage \"auroracoinaddress\" \"signature\" \"message\"\n"
"\nVerify a signed message\n"
"\nArguments:\n"
"1. \"auroracoinaddress\" (string, required) The auroracoin address to use for the signature.\n"
"2. \"signature\" (string, required) The signature provided by the signer in base 64 encoding (see signmessage).\n"
"3. \"message\" (string, required) The message that was signed.\n"
"\nResult:\n"
"true|false (boolean) If the signature is verified or not.\n"
"\nExamples:\n"
"\nUnlock the wallet for 30 seconds\n"
+ HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
"\nCreate the signature\n"
+ HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"my message\"") +
"\nVerify the signature\n"
+ HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"signature\" \"my message\"") +
"\nAs json rpc\n"
+ HelpExampleRpc("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\", \"signature\", \"my message\"")
);
string strAddress = params[0].get_str();
string strSign = params[1].get_str();
string strMessage = params[2].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
bool fInvalid = false;
vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CPubKey pubkey;
if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
return false;
return (pubkey.GetID() == keyID);
}
<commit_msg>Build_Date in getinfo test<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "init.h"
#include "main.h"
#include "net.h"
#include "netbase.h"
#include "rpcserver.h"
#include "util.h"
#ifdef ENABLE_WALLET
#include "wallet.h"
#include "walletdb.h"
#endif
#include <stdint.h>
#include <boost/assign/list_of.hpp>
#include "json/json_spirit_utils.h"
#include "json/json_spirit_value.h"
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
Value getinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getinfo\n"
"Returns an object containing various state info.\n"
"\nResult:\n"
"{\n"
" \"version\": xxxxx, (numeric) the server version\n"
" \"protocolversion\": xxxxx, (numeric) the protocol version\n"
" \"build_date\": xxxxx, (string) the wallet build date\n"
" \"balance\": xxxxxxx, (numeric) the total auroracoin balance of the wallet\n"
" \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
" \"timeoffset\": xxxxx, (numeric) the time offset\n"
" \"connections\": xxxxx, (numeric) the number of connections\n"
" \"proxy\": \"host:port\", (string, optional) the proxy used by the server\n"
" \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
" \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since GMT epoch) of the oldest pre-generated key in the key pool\n"
" \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated\n"
" \"unlocked_until\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n"
" \"paytxfee\": x.xxxx, (numeric) the transaction fee set in aur/kb\n"
" \"relayfee\": x.xxxx, (numeric) minimum relay fee for non-free transactions in aur/kb\n"
" \"errors\": \"...\" (string) any error messages\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getinfo", "")
+ HelpExampleRpc("getinfo", "")
);
proxyType proxy;
GetProxy(NET_IPV4, proxy);
Object obj;
obj.push_back(Pair("version", (int)CLIENT_VERSION));
obj.push_back(Pair("protocolversion", (int)PROTOCOL_VERSION));
obj.push_back(Pair("build_date", CLIENT_DATE : string()));
#ifdef ENABLE_WALLET
if (pwalletMain) {
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
}
#endif
obj.push_back(Pair("blocks", (int)chainActive.Height()));
obj.push_back(Pair("timeoffset", GetTimeOffset()));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string())));
obj.push_back(Pair("pow_algo_id", miningAlgo));
obj.push_back(Pair("pow_algo", GetAlgoName(miningAlgo)));
obj.push_back(Pair("difficulty", (double)GetDifficulty(NULL, miningAlgo)));
obj.push_back(Pair("difficulty_sha256d", (double)GetDifficulty(NULL, ALGO_SHA256D)));
obj.push_back(Pair("difficulty_scrypt", (double)GetDifficulty(NULL, ALGO_SCRYPT)));
obj.push_back(Pair("difficulty_groestl", (double)GetDifficulty(NULL, ALGO_GROESTL)));
obj.push_back(Pair("difficulty_skein", (double)GetDifficulty(NULL, ALGO_SKEIN)));
obj.push_back(Pair("difficulty_qubit", (double)GetDifficulty(NULL, ALGO_QUBIT)));
#ifdef ENABLE_WALLET
if (pwalletMain) {
obj.push_back(Pair("keypoololdest", pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize()));
}
if (pwalletMain && pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", nWalletUnlockTime));
obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
#endif
obj.push_back(Pair("relayfee", ValueFromAmount(CTransaction::nMinRelayTxFee)));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
return obj;
}
#ifdef ENABLE_WALLET
class DescribeAddressVisitor : public boost::static_visitor<Object>
{
public:
Object operator()(const CNoDestination &dest) const { return Object(); }
Object operator()(const CKeyID &keyID) const {
Object obj;
CPubKey vchPubKey;
pwalletMain->GetPubKey(keyID, vchPubKey);
obj.push_back(Pair("isscript", false));
obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
return obj;
}
Object operator()(const CScriptID &scriptID) const {
Object obj;
obj.push_back(Pair("isscript", true));
CScript subscript;
pwalletMain->GetCScript(scriptID, subscript);
std::vector<CTxDestination> addresses;
txnouttype whichType;
int nRequired;
ExtractDestinations(subscript, whichType, addresses, nRequired);
obj.push_back(Pair("script", GetTxnOutputType(whichType)));
obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end())));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
obj.push_back(Pair("addresses", a));
if (whichType == TX_MULTISIG)
obj.push_back(Pair("sigsrequired", nRequired));
return obj;
}
};
#endif
Value validateaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"validateaddress \"auroracoinaddress\"\n"
"\nReturn information about the given auroracoin address.\n"
"\nArguments:\n"
"1. \"auroracoinaddress\" (string, required) The auroracoin address to validate\n"
"\nResult:\n"
"{\n"
" \"isvalid\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\n"
" \"address\" : \"auroracoinaddress\", (string) The auroracoin address validated\n"
" \"ismine\" : true|false, (boolean) If the address is yours or not\n"
" \"isscript\" : true|false, (boolean) If the key is a script\n"
" \"pubkey\" : \"publickeyhex\", (string) The hex value of the raw public key\n"
" \"iscompressed\" : true|false, (boolean) If the address is compressed\n"
" \"account\" : \"account\" (string) The account associated with the address, \"\" is the default account\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")
+ HelpExampleRpc("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")
);
CBitcoinAddress address(params[0].get_str());
bool isValid = address.IsValid();
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
#ifdef ENABLE_WALLET
bool fMine = pwalletMain ? IsMine(*pwalletMain, dest) : false;
ret.push_back(Pair("ismine", fMine));
if (fMine) {
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain && pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest].name));
#endif
}
return ret;
}
//
// Used by addmultisigaddress / createmultisig:
//
CScript _createmultisig(const Array& params)
{
int nRequired = params[0].get_int();
const Array& keys = params[1].get_array();
// Gather public keys
if (nRequired < 1)
throw runtime_error("a multisignature address must require at least one key to redeem");
if ((int)keys.size() < nRequired)
throw runtime_error(
strprintf("not enough keys supplied "
"(got %u keys, but need at least %d to redeem)", keys.size(), nRequired));
std::vector<CPubKey> pubkeys;
pubkeys.resize(keys.size());
for (unsigned int i = 0; i < keys.size(); i++)
{
const std::string& ks = keys[i].get_str();
#ifdef ENABLE_WALLET
// Case 1: Bitcoin address and we have full public key:
CBitcoinAddress address(ks);
if (pwalletMain && address.IsValid())
{
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw runtime_error(
strprintf("%s does not refer to a key",ks));
CPubKey vchPubKey;
if (!pwalletMain->GetPubKey(keyID, vchPubKey))
throw runtime_error(
strprintf("no full public key for address %s",ks));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: "+ks);
pubkeys[i] = vchPubKey;
}
// Case 2: hex public key
else
#endif
if (IsHex(ks))
{
CPubKey vchPubKey(ParseHex(ks));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: "+ks);
pubkeys[i] = vchPubKey;
}
else
{
throw runtime_error(" Invalid public key: "+ks);
}
}
CScript result;
result.SetMultisig(nRequired, pubkeys);
return result;
}
Value createmultisig(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 2)
{
string msg = "createmultisig nrequired [\"key\",...]\n"
"\nCreates a multi-signature address with n signature of m keys required.\n"
"It returns a json object with the address and redeemScript.\n"
"\nArguments:\n"
"1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
"2. \"keys\" (string, required) A json array of keys which are auroracoin addresses or hex-encoded public keys\n"
" [\n"
" \"key\" (string) auroracoin address or hex-encoded public key\n"
" ,...\n"
" ]\n"
"\nResult:\n"
"{\n"
" \"address\":\"multisigaddress\", (string) The value of the new multisig address.\n"
" \"redeemScript\":\"script\" (string) The string value of the hex-encoded redemption script.\n"
"}\n"
"\nExamples:\n"
"\nCreate a multisig address from 2 addresses\n"
+ HelpExampleCli("createmultisig", "2 \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("createmultisig", "2, \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"")
;
throw runtime_error(msg);
}
// Construct using pay-to-script-hash:
CScript inner = _createmultisig(params);
CScriptID innerID = inner.GetID();
CBitcoinAddress address(innerID);
Object result;
result.push_back(Pair("address", address.ToString()));
result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end())));
return result;
}
Value verifymessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw runtime_error(
"verifymessage \"auroracoinaddress\" \"signature\" \"message\"\n"
"\nVerify a signed message\n"
"\nArguments:\n"
"1. \"auroracoinaddress\" (string, required) The auroracoin address to use for the signature.\n"
"2. \"signature\" (string, required) The signature provided by the signer in base 64 encoding (see signmessage).\n"
"3. \"message\" (string, required) The message that was signed.\n"
"\nResult:\n"
"true|false (boolean) If the signature is verified or not.\n"
"\nExamples:\n"
"\nUnlock the wallet for 30 seconds\n"
+ HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
"\nCreate the signature\n"
+ HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"my message\"") +
"\nVerify the signature\n"
+ HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"signature\" \"my message\"") +
"\nAs json rpc\n"
+ HelpExampleRpc("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\", \"signature\", \"my message\"")
);
string strAddress = params[0].get_str();
string strSign = params[1].get_str();
string strMessage = params[2].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
bool fInvalid = false;
vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CPubKey pubkey;
if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
return false;
return (pubkey.GetID() == keyID);
}
<|endoftext|> |
<commit_before>//===-- X86TargetAsmInfo.cpp - X86 asm properties ---------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by James M. Laskey and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declarations of the X86TargetAsmInfo properties.
//
//===----------------------------------------------------------------------===//
#include "X86TargetAsmInfo.h"
#include "X86TargetMachine.h"
#include "X86Subtarget.h"
#include "llvm/InlineAsm.h"
#include "llvm/Instructions.h"
#include "llvm/Module.h"
#include "llvm/ADT/StringExtras.h"
using namespace llvm;
static const char* x86_asm_table[] = {"{si}", "S",
"{di}", "D",
"{ax}", "a",
"{cx}", "c",
"{memory}", "memory",
"{flags}", "",
"{dirflag}", "",
"{fpsr}", "",
"{cc}", "cc",
0,0};
X86TargetAsmInfo::X86TargetAsmInfo(const X86TargetMachine &TM) {
const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
// FIXME - Should be simplified.
AsmTransCBE = x86_asm_table;
switch (Subtarget->TargetType) {
case X86Subtarget::isDarwin:
AlignmentIsInBytes = false;
GlobalPrefix = "_";
if (!Subtarget->is64Bit())
Data64bitsDirective = 0; // we can't emit a 64-bit unit
ZeroDirective = "\t.space\t"; // ".space N" emits N zeros.
PrivateGlobalPrefix = "L"; // Marker for constant pool idxs
ConstantPoolSection = "\t.const\n";
JumpTableDataSection = "\t.const\n";
CStringSection = "\t.cstring";
FourByteConstantSection = "\t.literal4\n";
EightByteConstantSection = "\t.literal8\n";
if (Subtarget->is64Bit())
SixteenByteConstantSection = "\t.literal16\n";
LCOMMDirective = "\t.lcomm\t";
COMMDirectiveTakesAlignment = false;
HasDotTypeDotSizeDirective = false;
StaticCtorsSection = ".mod_init_func";
StaticDtorsSection = ".mod_term_func";
InlineAsmStart = "# InlineAsm Start";
InlineAsmEnd = "# InlineAsm End";
SetDirective = "\t.set";
UsedDirective = "\t.no_dead_strip\t";
NeedsSet = true;
DwarfAbbrevSection = ".section __DWARF,__debug_abbrev,regular,debug";
DwarfInfoSection = ".section __DWARF,__debug_info,regular,debug";
DwarfLineSection = ".section __DWARF,__debug_line,regular,debug";
DwarfFrameSection = ".section __DWARF,__debug_frame,regular,debug";
DwarfPubNamesSection = ".section __DWARF,__debug_pubnames,regular,debug";
DwarfPubTypesSection = ".section __DWARF,__debug_pubtypes,regular,debug";
DwarfStrSection = ".section __DWARF,__debug_str,regular,debug";
DwarfLocSection = ".section __DWARF,__debug_loc,regular,debug";
DwarfARangesSection = ".section __DWARF,__debug_aranges,regular,debug";
DwarfRangesSection = ".section __DWARF,__debug_ranges,regular,debug";
DwarfMacInfoSection = ".section __DWARF,__debug_macinfo,regular,debug";
break;
case X86Subtarget::isELF:
// Set up DWARF directives
HasLEB128 = true; // Target asm supports leb128 directives (little-endian)
// bool HasLEB128; // Defaults to false.
// hasDotLoc - True if target asm supports .loc directives.
// bool HasDotLoc; // Defaults to false.
// HasDotFile - True if target asm supports .file directives.
// bool HasDotFile; // Defaults to false.
PrivateGlobalPrefix = "."; // Prefix for private global symbols
DwarfRequiresFrameSection = false;
DwarfAbbrevSection = "\t.section\t.debug_abbrev,\"\",@progbits";
DwarfInfoSection = "\t.section\t.debug_info,\"\",@progbits";
DwarfLineSection = "\t.section\t.debug_line,\"\",@progbits";
DwarfFrameSection = "\t.section\t.debug_frame,\"\",@progbits";
DwarfPubNamesSection ="\t.section\t.debug_pubnames,\"\",@progbits";
DwarfPubTypesSection ="\t.section\t.debug_pubtypes,\"\",@progbits";
DwarfStrSection = "\t.section\t.debug_str,\"\",@progbits";
DwarfLocSection = "\t.section\t.debug_loc,\"\",@progbits";
DwarfARangesSection = "\t.section\t.debug_aranges,\"\",@progbits";
DwarfRangesSection = "\t.section\t.debug_ranges,\"\",@progbits";
DwarfMacInfoSection = "\t.section\t.debug_macinfo,\"\",@progbits";
break;
case X86Subtarget::isCygwin:
GlobalPrefix = "_";
COMMDirectiveTakesAlignment = false;
HasDotTypeDotSizeDirective = false;
StaticCtorsSection = "\t.section .ctors,\"aw\"";
StaticDtorsSection = "\t.section .dtors,\"aw\"";
// Set up DWARF directives
HasLEB128 = true; // Target asm supports leb128 directives (little-endian)
PrivateGlobalPrefix = "L"; // Prefix for private global symbols
DwarfRequiresFrameSection = false;
DwarfAbbrevSection = "\t.section\t.debug_abbrev,\"dr\"";
DwarfInfoSection = "\t.section\t.debug_info,\"dr\"";
DwarfLineSection = "\t.section\t.debug_line,\"dr\"";
DwarfFrameSection = "\t.section\t.debug_frame,\"dr\"";
DwarfPubNamesSection ="\t.section\t.debug_pubnames,\"dr\"";
DwarfPubTypesSection ="\t.section\t.debug_pubtypes,\"dr\"";
DwarfStrSection = "\t.section\t.debug_str,\"dr\"";
DwarfLocSection = "\t.section\t.debug_loc,\"dr\"";
DwarfARangesSection = "\t.section\t.debug_aranges,\"dr\"";
DwarfRangesSection = "\t.section\t.debug_ranges,\"dr\"";
DwarfMacInfoSection = "\t.section\t.debug_macinfo,\"dr\"";
break;
break;
case X86Subtarget::isWindows:
GlobalPrefix = "_";
HasDotTypeDotSizeDirective = false;
break;
default: break;
}
if (Subtarget->isFlavorIntel()) {
GlobalPrefix = "_";
CommentString = ";";
PrivateGlobalPrefix = "$";
AlignDirective = "\talign\t";
ZeroDirective = "\tdb\t";
ZeroDirectiveSuffix = " dup(0)";
AsciiDirective = "\tdb\t";
AscizDirective = 0;
Data8bitsDirective = "\tdb\t";
Data16bitsDirective = "\tdw\t";
Data32bitsDirective = "\tdd\t";
Data64bitsDirective = "\tdq\t";
HasDotTypeDotSizeDirective = false;
TextSection = "_text";
DataSection = "_data";
SwitchToSectionDirective = "";
TextSectionStartSuffix = "\tsegment 'CODE'";
DataSectionStartSuffix = "\tsegment 'DATA'";
SectionEndDirectiveSuffix = "\tends\n";
}
}
bool X86TargetAsmInfo::LowerToBSwap(CallInst *CI) const {
// FIXME: this should verify that we are targetting a 486 or better. If not,
// we will turn this bswap into something that will be lowered to logical ops
// instead of emitting the bswap asm. For now, we don't support 486 or lower
// so don't worry about this.
// Verify this is a simple bswap.
if (CI->getNumOperands() != 2 ||
CI->getType() != CI->getOperand(1)->getType() ||
!CI->getType()->isInteger())
return false;
const Type *Ty = CI->getType()->getUnsignedVersion();
const char *IntName;
switch (Ty->getTypeID()) {
default: return false;
case Type::UShortTyID: IntName = "llvm.bswap.i16"; break;
case Type::UIntTyID: IntName = "llvm.bswap.i32"; break;
case Type::ULongTyID: IntName = "llvm.bswap.i64"; break;
}
// Okay, we can do this xform, do so now.
Module *M = CI->getParent()->getParent()->getParent();
Function *Int = M->getOrInsertFunction(IntName, Ty, Ty, (Type*)0);
Value *Op = CI->getOperand(1);
if (CI->getOperand(1)->getType() != Ty)
Op = new BitCastInst(Op, Ty, Op->getName(), CI);
Op = new CallInst(Int, Op, CI->getName(), CI);
if (Op->getType() != CI->getType())
Op = new BitCastInst(Op, CI->getType(), Op->getName(), CI);
CI->replaceAllUsesWith(Op);
CI->eraseFromParent();
return true;
}
bool X86TargetAsmInfo::ExpandInlineAsm(CallInst *CI) const {
InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
//std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
std::string AsmStr = IA->getAsmString();
// TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
std::vector<std::string> AsmPieces;
SplitString(AsmStr, AsmPieces, "\n"); // ; as separator?
switch (AsmPieces.size()) {
default: return false;
case 1:
AsmStr = AsmPieces[0];
AsmPieces.clear();
SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
if (AsmPieces.size() == 2 &&
AsmPieces[0] == "bswap" && AsmPieces[1] == "$0") {
// No need to check constraints, nothing other than the equivalent of
// "=r,0" would be valid here.
return LowerToBSwap(CI);
}
break;
}
return false;
}
<commit_msg>Upgrade the ugly darwin 64-bit bswap idiom (bswap %eax / bswap %edx / xchgl %eax, %edx) to llvm.bswap.i64. This compiles:<commit_after>//===-- X86TargetAsmInfo.cpp - X86 asm properties ---------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by James M. Laskey and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declarations of the X86TargetAsmInfo properties.
//
//===----------------------------------------------------------------------===//
#include "X86TargetAsmInfo.h"
#include "X86TargetMachine.h"
#include "X86Subtarget.h"
#include "llvm/InlineAsm.h"
#include "llvm/Instructions.h"
#include "llvm/Module.h"
#include "llvm/ADT/StringExtras.h"
using namespace llvm;
static const char* x86_asm_table[] = {"{si}", "S",
"{di}", "D",
"{ax}", "a",
"{cx}", "c",
"{memory}", "memory",
"{flags}", "",
"{dirflag}", "",
"{fpsr}", "",
"{cc}", "cc",
0,0};
X86TargetAsmInfo::X86TargetAsmInfo(const X86TargetMachine &TM) {
const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
// FIXME - Should be simplified.
AsmTransCBE = x86_asm_table;
switch (Subtarget->TargetType) {
case X86Subtarget::isDarwin:
AlignmentIsInBytes = false;
GlobalPrefix = "_";
if (!Subtarget->is64Bit())
Data64bitsDirective = 0; // we can't emit a 64-bit unit
ZeroDirective = "\t.space\t"; // ".space N" emits N zeros.
PrivateGlobalPrefix = "L"; // Marker for constant pool idxs
ConstantPoolSection = "\t.const\n";
JumpTableDataSection = "\t.const\n";
CStringSection = "\t.cstring";
FourByteConstantSection = "\t.literal4\n";
EightByteConstantSection = "\t.literal8\n";
if (Subtarget->is64Bit())
SixteenByteConstantSection = "\t.literal16\n";
LCOMMDirective = "\t.lcomm\t";
COMMDirectiveTakesAlignment = false;
HasDotTypeDotSizeDirective = false;
StaticCtorsSection = ".mod_init_func";
StaticDtorsSection = ".mod_term_func";
InlineAsmStart = "# InlineAsm Start";
InlineAsmEnd = "# InlineAsm End";
SetDirective = "\t.set";
UsedDirective = "\t.no_dead_strip\t";
NeedsSet = true;
DwarfAbbrevSection = ".section __DWARF,__debug_abbrev,regular,debug";
DwarfInfoSection = ".section __DWARF,__debug_info,regular,debug";
DwarfLineSection = ".section __DWARF,__debug_line,regular,debug";
DwarfFrameSection = ".section __DWARF,__debug_frame,regular,debug";
DwarfPubNamesSection = ".section __DWARF,__debug_pubnames,regular,debug";
DwarfPubTypesSection = ".section __DWARF,__debug_pubtypes,regular,debug";
DwarfStrSection = ".section __DWARF,__debug_str,regular,debug";
DwarfLocSection = ".section __DWARF,__debug_loc,regular,debug";
DwarfARangesSection = ".section __DWARF,__debug_aranges,regular,debug";
DwarfRangesSection = ".section __DWARF,__debug_ranges,regular,debug";
DwarfMacInfoSection = ".section __DWARF,__debug_macinfo,regular,debug";
break;
case X86Subtarget::isELF:
// Set up DWARF directives
HasLEB128 = true; // Target asm supports leb128 directives (little-endian)
// bool HasLEB128; // Defaults to false.
// hasDotLoc - True if target asm supports .loc directives.
// bool HasDotLoc; // Defaults to false.
// HasDotFile - True if target asm supports .file directives.
// bool HasDotFile; // Defaults to false.
PrivateGlobalPrefix = "."; // Prefix for private global symbols
DwarfRequiresFrameSection = false;
DwarfAbbrevSection = "\t.section\t.debug_abbrev,\"\",@progbits";
DwarfInfoSection = "\t.section\t.debug_info,\"\",@progbits";
DwarfLineSection = "\t.section\t.debug_line,\"\",@progbits";
DwarfFrameSection = "\t.section\t.debug_frame,\"\",@progbits";
DwarfPubNamesSection ="\t.section\t.debug_pubnames,\"\",@progbits";
DwarfPubTypesSection ="\t.section\t.debug_pubtypes,\"\",@progbits";
DwarfStrSection = "\t.section\t.debug_str,\"\",@progbits";
DwarfLocSection = "\t.section\t.debug_loc,\"\",@progbits";
DwarfARangesSection = "\t.section\t.debug_aranges,\"\",@progbits";
DwarfRangesSection = "\t.section\t.debug_ranges,\"\",@progbits";
DwarfMacInfoSection = "\t.section\t.debug_macinfo,\"\",@progbits";
break;
case X86Subtarget::isCygwin:
GlobalPrefix = "_";
COMMDirectiveTakesAlignment = false;
HasDotTypeDotSizeDirective = false;
StaticCtorsSection = "\t.section .ctors,\"aw\"";
StaticDtorsSection = "\t.section .dtors,\"aw\"";
// Set up DWARF directives
HasLEB128 = true; // Target asm supports leb128 directives (little-endian)
PrivateGlobalPrefix = "L"; // Prefix for private global symbols
DwarfRequiresFrameSection = false;
DwarfAbbrevSection = "\t.section\t.debug_abbrev,\"dr\"";
DwarfInfoSection = "\t.section\t.debug_info,\"dr\"";
DwarfLineSection = "\t.section\t.debug_line,\"dr\"";
DwarfFrameSection = "\t.section\t.debug_frame,\"dr\"";
DwarfPubNamesSection ="\t.section\t.debug_pubnames,\"dr\"";
DwarfPubTypesSection ="\t.section\t.debug_pubtypes,\"dr\"";
DwarfStrSection = "\t.section\t.debug_str,\"dr\"";
DwarfLocSection = "\t.section\t.debug_loc,\"dr\"";
DwarfARangesSection = "\t.section\t.debug_aranges,\"dr\"";
DwarfRangesSection = "\t.section\t.debug_ranges,\"dr\"";
DwarfMacInfoSection = "\t.section\t.debug_macinfo,\"dr\"";
break;
break;
case X86Subtarget::isWindows:
GlobalPrefix = "_";
HasDotTypeDotSizeDirective = false;
break;
default: break;
}
if (Subtarget->isFlavorIntel()) {
GlobalPrefix = "_";
CommentString = ";";
PrivateGlobalPrefix = "$";
AlignDirective = "\talign\t";
ZeroDirective = "\tdb\t";
ZeroDirectiveSuffix = " dup(0)";
AsciiDirective = "\tdb\t";
AscizDirective = 0;
Data8bitsDirective = "\tdb\t";
Data16bitsDirective = "\tdw\t";
Data32bitsDirective = "\tdd\t";
Data64bitsDirective = "\tdq\t";
HasDotTypeDotSizeDirective = false;
TextSection = "_text";
DataSection = "_data";
SwitchToSectionDirective = "";
TextSectionStartSuffix = "\tsegment 'CODE'";
DataSectionStartSuffix = "\tsegment 'DATA'";
SectionEndDirectiveSuffix = "\tends\n";
}
}
bool X86TargetAsmInfo::LowerToBSwap(CallInst *CI) const {
// FIXME: this should verify that we are targetting a 486 or better. If not,
// we will turn this bswap into something that will be lowered to logical ops
// instead of emitting the bswap asm. For now, we don't support 486 or lower
// so don't worry about this.
// Verify this is a simple bswap.
if (CI->getNumOperands() != 2 ||
CI->getType() != CI->getOperand(1)->getType() ||
!CI->getType()->isInteger())
return false;
const Type *Ty = CI->getType()->getUnsignedVersion();
const char *IntName;
switch (Ty->getTypeID()) {
default: return false;
case Type::UShortTyID: IntName = "llvm.bswap.i16"; break;
case Type::UIntTyID: IntName = "llvm.bswap.i32"; break;
case Type::ULongTyID: IntName = "llvm.bswap.i64"; break;
}
// Okay, we can do this xform, do so now.
Module *M = CI->getParent()->getParent()->getParent();
Function *Int = M->getOrInsertFunction(IntName, Ty, Ty, (Type*)0);
Value *Op = CI->getOperand(1);
if (CI->getOperand(1)->getType() != Ty)
Op = new BitCastInst(Op, Ty, Op->getName(), CI);
Op = new CallInst(Int, Op, CI->getName(), CI);
if (Op->getType() != CI->getType())
Op = new BitCastInst(Op, CI->getType(), Op->getName(), CI);
CI->replaceAllUsesWith(Op);
CI->eraseFromParent();
return true;
}
bool X86TargetAsmInfo::ExpandInlineAsm(CallInst *CI) const {
InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
std::string AsmStr = IA->getAsmString();
// TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
std::vector<std::string> AsmPieces;
SplitString(AsmStr, AsmPieces, "\n"); // ; as separator?
switch (AsmPieces.size()) {
default: return false;
case 1:
AsmStr = AsmPieces[0];
AsmPieces.clear();
SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
// bswap $0
if (AsmPieces.size() == 2 &&
AsmPieces[0] == "bswap" && AsmPieces[1] == "$0") {
// No need to check constraints, nothing other than the equivalent of
// "=r,0" would be valid here.
return LowerToBSwap(CI);
}
break;
case 3:
if (CI->getType() == Type::ULongTy && Constraints.size() >= 2 &&
Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
// bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
std::vector<std::string> Words;
SplitString(AsmPieces[0], Words, " \t");
if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
Words.clear();
SplitString(AsmPieces[1], Words, " \t");
if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
Words.clear();
SplitString(AsmPieces[2], Words, " \t,");
if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
Words[2] == "%edx") {
return LowerToBSwap(CI);
}
}
}
}
break;
}
return false;
}
<|endoftext|> |
<commit_before>#pragma once
#include <string>
#include <vector>
namespace sstd{
std::string getPath (const char* pPath);
std::string getPath_owWC (const char* pPath); // _owWC: without wild card
std::string getDirName (const char* pPath);
uint getDirName_begin_idx (const char* pPath);
uint getDirName_end_idx (const char* pPath);
uint getDirName_end_idx_owWC (const char* pPath); // _owWC: without wild card
char* getFileName (const char* pPath);
std::string getFileName_withoutExtension(const char* pPath);
char* getExtension (const char* pPath);
std::vector<std::string> parsePath (const char* pPath);
std::vector<std::string> parsePath_withBase(const char* pPath);
bool isFile(const char* pPath);
bool isFile(const std::string& path);
bool isDir (const char* pPath);
bool isDir (const std::string& path);
bool fileExist(const char* pPath);
bool fileExist(const std::string& path);
bool dirExist(const char* pPath);
bool dirExist(const std::string& path);
bool pathExist(const char* pPath);
bool pathExist(const std::string& path);
}
/*
How to use this?
*/
/*
int main() {
printf("■ DirPathAndNameSolver\n");
const char* pPath="./abc/def/text.abc.txt\0";
printf("Output getPath: %s\n", sstd::getPath(pPath).c_str());
printf("Output getFileName: %s\n", sstd::getFileName(pPath));
printf("Output getFileNameWithoutExtension: %s\n", sstd::getFileNameWithoutExtension(pPath).c_str());
printf("Output getFileExtension: %s\n", sstd::getExtension(pPath));
printf("\n");
return 0;
}
*/
/*
Input pPath: ./abc/def/text.abc.txt
Output GetPath: ./abc/def/
Output GetFileName: text.abc.txt
Output GetFileNameWithoutExtension: text.abc
Output GetFileExtension: txt
*/
// http://dobon.net/vb/dotnet/file/pathclass.html
//
// ■: 実装済み
//
// GetDirectoryName: ディレクトリ名の取得
// ■GetPath: パスの取得
// ■GetFileName: ファイル名の取得
// ■GetFileNameWithoutExtension: ファイル名 (拡張子なし) の取得
// ■GetExtension: 拡張子の取得
// GetPathRoot: ルートディレクトリ名の取得
// GetFullPath: 絶対パスの取得
// HasExtension: 拡張子を持っているか
// IsPathRooted: ルートが含まれているか (詳細)
// Directory.GetDirectoryRoot ボリューム、ルート情報の取得
// Directory.GetParent 親ディレクトリの取得
<commit_msg>fix bug<commit_after>#pragma once
#include <string>
#include <vector>
#include "../typeDef.h"
namespace sstd{
std::string getPath (const char* pPath);
std::string getPath_owWC (const char* pPath); // _owWC: without wild card
std::string getDirName (const char* pPath);
uint getDirName_begin_idx (const char* pPath);
uint getDirName_end_idx (const char* pPath);
uint getDirName_end_idx_owWC (const char* pPath); // _owWC: without wild card
char* getFileName (const char* pPath);
std::string getFileName_withoutExtension(const char* pPath);
char* getExtension (const char* pPath);
std::vector<std::string> parsePath (const char* pPath);
std::vector<std::string> parsePath_withBase(const char* pPath);
bool isFile(const char* pPath);
bool isFile(const std::string& path);
bool isDir (const char* pPath);
bool isDir (const std::string& path);
bool fileExist(const char* pPath);
bool fileExist(const std::string& path);
bool dirExist(const char* pPath);
bool dirExist(const std::string& path);
bool pathExist(const char* pPath);
bool pathExist(const std::string& path);
}
/*
How to use this?
*/
/*
int main() {
printf("■ DirPathAndNameSolver\n");
const char* pPath="./abc/def/text.abc.txt\0";
printf("Output getPath: %s\n", sstd::getPath(pPath).c_str());
printf("Output getFileName: %s\n", sstd::getFileName(pPath));
printf("Output getFileNameWithoutExtension: %s\n", sstd::getFileNameWithoutExtension(pPath).c_str());
printf("Output getFileExtension: %s\n", sstd::getExtension(pPath));
printf("\n");
return 0;
}
*/
/*
Input pPath: ./abc/def/text.abc.txt
Output GetPath: ./abc/def/
Output GetFileName: text.abc.txt
Output GetFileNameWithoutExtension: text.abc
Output GetFileExtension: txt
*/
// http://dobon.net/vb/dotnet/file/pathclass.html
//
// ■: 実装済み
//
// GetDirectoryName: ディレクトリ名の取得
// ■GetPath: パスの取得
// ■GetFileName: ファイル名の取得
// ■GetFileNameWithoutExtension: ファイル名 (拡張子なし) の取得
// ■GetExtension: 拡張子の取得
// GetPathRoot: ルートディレクトリ名の取得
// GetFullPath: 絶対パスの取得
// HasExtension: 拡張子を持っているか
// IsPathRooted: ルートが含まれているか (詳細)
// Directory.GetDirectoryRoot ボリューム、ルート情報の取得
// Directory.GetParent 親ディレクトリの取得
<|endoftext|> |
<commit_before><commit_msg>Resolves: rhbz#818557 crash with NULL shell post template update<commit_after><|endoftext|> |
<commit_before>/**
* Copyright (c) 2011-2017 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* This program 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.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <bitcoin/server/workers/query_worker.hpp>
#include <functional>
#include <string>
#include <bitcoin/protocol.hpp>
#include <bitcoin/server/define.hpp>
#include <bitcoin/server/interface/blockchain.hpp>
#include <bitcoin/server/interface/subscribe.hpp>
#include <bitcoin/server/interface/transaction_pool.hpp>
#include <bitcoin/server/interface/unsubscribe.hpp>
#include <bitcoin/server/messages/message.hpp>
#include <bitcoin/server/server_node.hpp>
namespace libbitcoin {
namespace server {
using namespace std::placeholders;
using namespace bc::protocol;
query_worker::query_worker(zmq::authenticator& authenticator,
server_node& node, bool secure)
: worker(priority(node.server_settings().priority)),
secure_(secure),
verbose_(node.network_settings().verbose),
settings_(node.server_settings()),
authenticator_(authenticator),
node_(node)
{
// The same interface is attached to the secure and public interfaces.
attach_interface();
}
// Implement worker as a dealer to the query service.
// v2 libbitcoin-client DEALER does not add delimiter frame.
// The dealer drops messages for lost peers (query service) and high water.
void query_worker::work()
{
// Use a dealer for this synchronous response because notifications are
// sent asynchronously to the same identity via the same dealer. Using a
// router is okay but it adds an additional address to the envelope that
// would have to be stripped by the notification dealer so this is simpler.
zmq::socket dealer(authenticator_, zmq::socket::role::dealer);
// Connect socket to the service endpoint.
if (!started(connect(dealer)))
return;
zmq::poller poller;
poller.add(dealer);
while (!poller.terminated() && !stopped())
{
if (poller.wait().contains(dealer.id()))
query(dealer);
}
// Disconnect the socket and exit this thread.
finished(disconnect(dealer));
}
// Connect/Disconnect.
//-----------------------------------------------------------------------------
bool query_worker::connect(zmq::socket& dealer)
{
const auto security = secure_ ? "secure" : "public";
const auto& endpoint = secure_ ? query_service::secure_worker :
query_service::public_worker;
const auto ec = dealer.connect(endpoint);
if (ec)
{
LOG_ERROR(LOG_SERVER)
<< "Failed to connect " << security << " query worker to "
<< endpoint << " : " << ec.message();
return false;
}
LOG_INFO(LOG_SERVER)
<< "Connected " << security << " query worker to " << endpoint;
return true;
}
bool query_worker::disconnect(zmq::socket& dealer)
{
const auto security = secure_ ? "secure" : "public";
// Don't log stop success.
if (dealer.stop())
return true;
LOG_ERROR(LOG_SERVER)
<< "Failed to disconnect " << security << " query worker.";
return false;
}
// Query Execution.
// The dealer send blocks until the query service dealer is available.
//-----------------------------------------------------------------------------
// private/static
void query_worker::send(const message& response, zmq::socket& dealer)
{
const auto ec = response.send(dealer);
if (ec && ec != error::service_stopped)
LOG_WARNING(LOG_SERVER)
<< "Failed to send query response to "
<< response.route().display() << " " << ec.message();
}
// Because the socket is a router we may simply drop invalid queries.
// As a single thread worker this router should not reach high water.
// If we implemented as a replier we would need to always provide a response.
void query_worker::query(zmq::socket& dealer)
{
if (stopped())
return;
message request(secure_);
const auto ec = request.receive(dealer);
if (ec == error::service_stopped)
return;
if (ec)
{
LOG_DEBUG(LOG_SERVER)
<< "Failed to receive query from " << request.route().display()
<< " " << ec.message();
send(message(request, ec), dealer);
return;
}
// Locate the request handler for this command.
const auto handler = command_handlers_.find(request.command());
if (handler == command_handlers_.end())
{
LOG_DEBUG(LOG_SERVER)
<< "Invalid query command from " << request.route().display();
send(message(request, error::not_found), dealer);
return;
}
if (verbose_)
LOG_INFO(LOG_SERVER)
<< "Query " << request.command() << " from "
<< request.route().display();
// The query executor is the delegate bound by the attach method.
const auto& query_execute = handler->second;
// Execute the request and send the result.
// Example: address.renew(node_, request, sender);
// Example: blockchain.fetch_history3(node_, request, sender);
query_execute(request,
std::bind(&query_worker::send,
_1, std::ref(dealer)));
}
// Query Interface.
// ----------------------------------------------------------------------------
// Class and method names must match protocol expectations (do not change).
#define ATTACH(class_name, method_name, node) \
attach(#class_name "." #method_name, \
std::bind(&bc::server::class_name::method_name, \
std::ref(node), _1, _2));
void query_worker::attach(const std::string& command,
command_handler handler)
{
command_handlers_[command] = handler;
}
//=============================================================================
// TODO: add to client and bx:
// blockchain.fetch_spend
// blockchain.fetch_block_height
// blockchain.fetch_block_transaction_hashes
// blockchain.fetch_stealth_transaction_hashes [document name change]
// subscribe.block (pub-sub)
// subscribe.transaction (pub-sub)
// subscribe.address
// subscribe.stealth
// unsubscribe.address
// unsubscribe.stealth
// TODO: add fetch_block (full)
//=============================================================================
// address.fetch_history is obsoleted in v3 (no unconfirmed tx indexing).
// address.renew is obsoleted in v3.
// address.subscribe is obsoleted in v3.
//-----------------------------------------------------------------------------
// blockchain.validate is new in v3 (blocks).
// blockchain.broadcast is new in v3 (blocks).
// blockchain.fetch_history is obsoleted in v3 (hash reversal).
// blockchain.fetch_history2 was new in v3.
// blockchain.fetch_history2 is obsoleted in v3.1 (version byte unused)
// blockchain.fetch_history3 is new in v3.1 (no version byte)
// blockchain.fetch_stealth is obsoleted in v3 (hash reversal).
// blockchain.fetch_stealth2 is new in v3.
// blockchain.fetch_stealth_transaction_hashes is new in v3 (safe version).
//-----------------------------------------------------------------------------
// transaction_pool.validate is obsoleted in v3 (unconfirmed outputs).
// transaction_pool.validate2 is new in v3.
// transaction_pool.broadcast is new in v3 (rename).
// transaction_pool.fetch_transaction is enhanced in v3 (adds confirmed txs).
//-----------------------------------------------------------------------------
// protocol.broadcast_transaction is obsoleted in v3 (renamed).
// protocol.total_connections is obsoleted in v3 (administrative).
//-----------------------------------------------------------------------------
// subscribe.address is new in v3, also call for renew.
// subscribe.stealth is new in v3, also call for renew.
//-----------------------------------------------------------------------------
// unsubscribe.address is new in v3 (there was never address.unsubscribe).
// unsubscribe.stealth is new in v3 (there was never stealth.unsubscribe).
//=============================================================================
// Interface class.method names must match protocol names.
void query_worker::attach_interface()
{
// Subscription was not operational in version 3.0.
////ATTACH(address, renew, node_); // obsoleted (3.0)
////ATTACH(address, subscribe, node_); // obsoleted (3.0)
////ATTACH(address, fetch_history, node_); // obsoleted (3.0)
ATTACH(subscribe, address, node_); // new (3.1)
ATTACH(subscribe, stealth, node_); // new (3.1)
ATTACH(unsubscribe, address, node_); // new (3.1)
ATTACH(unsubscribe, stealth, node_); // new (3.1)
////ATTACH(blockchain, fetch_stealth, node_); // obsoleted
////ATTACH(blockchain, fetch_history, node_); // obsoleted
////ATTACH(blockchain, fetch_history2, node_); // obsoleted
ATTACH(blockchain, fetch_block_header, node_); // original
ATTACH(blockchain, fetch_block_height, node_); // original
ATTACH(blockchain, fetch_block_transaction_hashes, node_); // original
ATTACH(blockchain, fetch_last_height, node_); // original
ATTACH(blockchain, fetch_transaction, node_); // original
ATTACH(blockchain, fetch_transaction_index, node_); // original
ATTACH(blockchain, fetch_spend, node_); // original
ATTACH(blockchain, fetch_history3, node_); // new (3.1)
ATTACH(blockchain, fetch_stealth2, node_); // new (3.0)
ATTACH(blockchain, fetch_stealth_transaction_hashes, node_);// new (3.0)
ATTACH(blockchain, broadcast, node_); // new (3.0)
ATTACH(blockchain, validate, node_); // new (3.0)
////ATTACH(transaction_pool, validate, node_); // obsoleted
ATTACH(transaction_pool, fetch_transaction, node_); // enhanced
ATTACH(transaction_pool, broadcast, node_); // new (3.0)
ATTACH(transaction_pool, validate2, node_); // new (3.0)
////ATTACH(protocol, broadcast_transaction, node_); // obsoleted
////ATTACH(protocol, total_connections, node_); // obsoleted
}
#undef ATTACH
} // namespace server
} // namespace libbitcoin
<commit_msg>Log internal query service connections to debug log.<commit_after>/**
* Copyright (c) 2011-2017 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* This program 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.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <bitcoin/server/workers/query_worker.hpp>
#include <functional>
#include <string>
#include <bitcoin/protocol.hpp>
#include <bitcoin/server/define.hpp>
#include <bitcoin/server/interface/blockchain.hpp>
#include <bitcoin/server/interface/subscribe.hpp>
#include <bitcoin/server/interface/transaction_pool.hpp>
#include <bitcoin/server/interface/unsubscribe.hpp>
#include <bitcoin/server/messages/message.hpp>
#include <bitcoin/server/server_node.hpp>
namespace libbitcoin {
namespace server {
using namespace std::placeholders;
using namespace bc::protocol;
query_worker::query_worker(zmq::authenticator& authenticator,
server_node& node, bool secure)
: worker(priority(node.server_settings().priority)),
secure_(secure),
verbose_(node.network_settings().verbose),
settings_(node.server_settings()),
authenticator_(authenticator),
node_(node)
{
// The same interface is attached to the secure and public interfaces.
attach_interface();
}
// Implement worker as a dealer to the query service.
// v2 libbitcoin-client DEALER does not add delimiter frame.
// The dealer drops messages for lost peers (query service) and high water.
void query_worker::work()
{
// Use a dealer for this synchronous response because notifications are
// sent asynchronously to the same identity via the same dealer. Using a
// router is okay but it adds an additional address to the envelope that
// would have to be stripped by the notification dealer so this is simpler.
zmq::socket dealer(authenticator_, zmq::socket::role::dealer);
// Connect socket to the service endpoint.
if (!started(connect(dealer)))
return;
zmq::poller poller;
poller.add(dealer);
while (!poller.terminated() && !stopped())
{
if (poller.wait().contains(dealer.id()))
query(dealer);
}
// Disconnect the socket and exit this thread.
finished(disconnect(dealer));
}
// Connect/Disconnect.
//-----------------------------------------------------------------------------
bool query_worker::connect(zmq::socket& dealer)
{
const auto security = secure_ ? "secure" : "public";
const auto& endpoint = secure_ ? query_service::secure_worker :
query_service::public_worker;
const auto ec = dealer.connect(endpoint);
if (ec)
{
LOG_ERROR(LOG_SERVER)
<< "Failed to connect " << security << " query worker to "
<< endpoint << " : " << ec.message();
return false;
}
LOG_DEBUG(LOG_SERVER)
<< "Connected " << security << " query worker to " << endpoint;
return true;
}
bool query_worker::disconnect(zmq::socket& dealer)
{
const auto security = secure_ ? "secure" : "public";
// Don't log stop success.
if (dealer.stop())
return true;
LOG_ERROR(LOG_SERVER)
<< "Failed to disconnect " << security << " query worker.";
return false;
}
// Query Execution.
// The dealer send blocks until the query service dealer is available.
//-----------------------------------------------------------------------------
// private/static
void query_worker::send(const message& response, zmq::socket& dealer)
{
const auto ec = response.send(dealer);
if (ec && ec != error::service_stopped)
LOG_WARNING(LOG_SERVER)
<< "Failed to send query response to "
<< response.route().display() << " " << ec.message();
}
// Because the socket is a router we may simply drop invalid queries.
// As a single thread worker this router should not reach high water.
// If we implemented as a replier we would need to always provide a response.
void query_worker::query(zmq::socket& dealer)
{
if (stopped())
return;
message request(secure_);
const auto ec = request.receive(dealer);
if (ec == error::service_stopped)
return;
if (ec)
{
LOG_DEBUG(LOG_SERVER)
<< "Failed to receive query from " << request.route().display()
<< " " << ec.message();
send(message(request, ec), dealer);
return;
}
// Locate the request handler for this command.
const auto handler = command_handlers_.find(request.command());
if (handler == command_handlers_.end())
{
LOG_DEBUG(LOG_SERVER)
<< "Invalid query command from " << request.route().display();
send(message(request, error::not_found), dealer);
return;
}
if (verbose_)
LOG_INFO(LOG_SERVER)
<< "Query " << request.command() << " from "
<< request.route().display();
// The query executor is the delegate bound by the attach method.
const auto& query_execute = handler->second;
// Execute the request and send the result.
// Example: address.renew(node_, request, sender);
// Example: blockchain.fetch_history3(node_, request, sender);
query_execute(request,
std::bind(&query_worker::send,
_1, std::ref(dealer)));
}
// Query Interface.
// ----------------------------------------------------------------------------
// Class and method names must match protocol expectations (do not change).
#define ATTACH(class_name, method_name, node) \
attach(#class_name "." #method_name, \
std::bind(&bc::server::class_name::method_name, \
std::ref(node), _1, _2));
void query_worker::attach(const std::string& command,
command_handler handler)
{
command_handlers_[command] = handler;
}
//=============================================================================
// TODO: add to client and bx:
// blockchain.fetch_spend
// blockchain.fetch_block_height
// blockchain.fetch_block_transaction_hashes
// blockchain.fetch_stealth_transaction_hashes [document name change]
// subscribe.block (pub-sub)
// subscribe.transaction (pub-sub)
// subscribe.address
// subscribe.stealth
// unsubscribe.address
// unsubscribe.stealth
// TODO: add fetch_block (full)
//=============================================================================
// address.fetch_history is obsoleted in v3 (no unconfirmed tx indexing).
// address.renew is obsoleted in v3.
// address.subscribe is obsoleted in v3.
//-----------------------------------------------------------------------------
// blockchain.validate is new in v3 (blocks).
// blockchain.broadcast is new in v3 (blocks).
// blockchain.fetch_history is obsoleted in v3 (hash reversal).
// blockchain.fetch_history2 was new in v3.
// blockchain.fetch_history2 is obsoleted in v3.1 (version byte unused)
// blockchain.fetch_history3 is new in v3.1 (no version byte)
// blockchain.fetch_stealth is obsoleted in v3 (hash reversal).
// blockchain.fetch_stealth2 is new in v3.
// blockchain.fetch_stealth_transaction_hashes is new in v3 (safe version).
//-----------------------------------------------------------------------------
// transaction_pool.validate is obsoleted in v3 (unconfirmed outputs).
// transaction_pool.validate2 is new in v3.
// transaction_pool.broadcast is new in v3 (rename).
// transaction_pool.fetch_transaction is enhanced in v3 (adds confirmed txs).
//-----------------------------------------------------------------------------
// protocol.broadcast_transaction is obsoleted in v3 (renamed).
// protocol.total_connections is obsoleted in v3 (administrative).
//-----------------------------------------------------------------------------
// subscribe.address is new in v3, also call for renew.
// subscribe.stealth is new in v3, also call for renew.
//-----------------------------------------------------------------------------
// unsubscribe.address is new in v3 (there was never address.unsubscribe).
// unsubscribe.stealth is new in v3 (there was never stealth.unsubscribe).
//=============================================================================
// Interface class.method names must match protocol names.
void query_worker::attach_interface()
{
// Subscription was not operational in version 3.0.
////ATTACH(address, renew, node_); // obsoleted (3.0)
////ATTACH(address, subscribe, node_); // obsoleted (3.0)
////ATTACH(address, fetch_history, node_); // obsoleted (3.0)
ATTACH(subscribe, address, node_); // new (3.1)
ATTACH(subscribe, stealth, node_); // new (3.1)
ATTACH(unsubscribe, address, node_); // new (3.1)
ATTACH(unsubscribe, stealth, node_); // new (3.1)
////ATTACH(blockchain, fetch_stealth, node_); // obsoleted
////ATTACH(blockchain, fetch_history, node_); // obsoleted
////ATTACH(blockchain, fetch_history2, node_); // obsoleted
ATTACH(blockchain, fetch_block_header, node_); // original
ATTACH(blockchain, fetch_block_height, node_); // original
ATTACH(blockchain, fetch_block_transaction_hashes, node_); // original
ATTACH(blockchain, fetch_last_height, node_); // original
ATTACH(blockchain, fetch_transaction, node_); // original
ATTACH(blockchain, fetch_transaction_index, node_); // original
ATTACH(blockchain, fetch_spend, node_); // original
ATTACH(blockchain, fetch_history3, node_); // new (3.1)
ATTACH(blockchain, fetch_stealth2, node_); // new (3.0)
ATTACH(blockchain, fetch_stealth_transaction_hashes, node_);// new (3.0)
ATTACH(blockchain, broadcast, node_); // new (3.0)
ATTACH(blockchain, validate, node_); // new (3.0)
////ATTACH(transaction_pool, validate, node_); // obsoleted
ATTACH(transaction_pool, fetch_transaction, node_); // enhanced
ATTACH(transaction_pool, broadcast, node_); // new (3.0)
ATTACH(transaction_pool, validate2, node_); // new (3.0)
////ATTACH(protocol, broadcast_transaction, node_); // obsoleted
////ATTACH(protocol, total_connections, node_); // obsoleted
}
#undef ATTACH
} // namespace server
} // namespace libbitcoin
<|endoftext|> |
<commit_before>/**********************************************************************
* *
* *
**********************************************************************/
#include "Minuit2/FunctionMinimum.h"
#include "Minuit2/MnMigrad.h"
#include "Minuit2/MnMinos.h"
#include "Minuit2/MnMinimize.h"
#include "Minuit2/MnUserParameters.h"
#include "Minuit2/MnPrint.h"
#include "Minuit2/FCNBase.h"
#include "Minuit2/MnScan.h"
#include "Minuit2/MnPlot.h"
#include "Minuit2/MnContours.h"
#include "Pulsar/Archive.h"
#include "Pulsar/Integration.h"
#include "Pulsar/Profile.h"
//#include "Pulsar/Interpreter.h"
#include "Pulsar/FaradayRotation.h"
#include "Pulsar/PolnProfileStats.h"
#include "RVMKJ_Fcn.C"
#include "write_results.h"
#include "getopt.h"
#include "string.h"
#include "stdio.h"
#include "stdlib.h"
#define R2D (180.0/M_PI)
using namespace std;
using namespace ROOT::Minuit2;
using namespace Pulsar;
int main(int argc, char **argv) {
int nfree = 0;
double threshold=3;
double alpha=80.0, beta=6.0, phi0=18.0, psi0=30.0;
bool alpha_fixed=false, beta_fixed=false, phi0_fixed=false, psi0_fixed=false, output=false;
char filename[128]="test.pa";
char label[16];
static struct option long_opts[] = {
{"thresh", 1, NULL, 't'},
{"alpha", 1, NULL, 'a'},
{"beta", 1, NULL, 'b'},
{"phi0", 1, NULL, 'p'},
{"psi0", 1, NULL, 'z'},
{"Alpha", 0, NULL, 'A'},
{"Beta", 0, NULL, 'B'},
{"Phi0", 0, NULL, 'P'},
{"Psi0", 0, NULL, 'Z'},
{"help", 0, NULL, 'h'},
{"file", 0, NULL, 'f'},
{0,0,0,0}
};
int opt, opti;
while ((opt=getopt_long(argc,argv,"t:a:b:p:z:ABPZohf:",long_opts,&opti))!=-1) {
switch (opt) {
case 't':
threshold = atof(optarg);
break;
case 'a':
alpha = atof(optarg);
break;
case 'b':
beta = atof(optarg);
break;
case 'p':
phi0 = atof(optarg);
break;
case 'z':
psi0 = atof(optarg);
break;
case 'A':
alpha_fixed = true;
break;
case 'B':
beta_fixed = true;
break;
case 'P':
phi0_fixed = true;
break;
case 'Z':
psi0_fixed = true;
break;
case 'o':
output = true;
break;
case 'f':
strncpy(filename, optarg, 127);
break;
case 'h':
default:
//usage();
exit(0);
break;
}
}
vector<int> phase_bin;
vector<double> phase;
vector<double> totI, L, Q, U, V;
Reference::To< Archive > archive = Archive::load( filename );
if( !archive ) return -1;
// correct PA to infinite frequency
FaradayRotation xform;
xform.set_reference_wavelength( 0 );
xform.set_measure( archive->get_rotation_measure() );
xform.execute( archive );
// Scrunch and Remove baseline
archive->tscrunch();
archive->fscrunch();
if( archive->get_state() != Signal::Stokes) archive->convert_state(Signal::Stokes);
archive->remove_baseline();
// Get Data
Pulsar::Integration* integration = archive->get_Integration(0);
Pulsar::PolnProfileStats stats;
stats.set_profile(integration->new_PolnProfile(0));
Estimate<double> rmsI = sqrt( stats.get_baseline_variance(0) );
Estimate<double> rmsQ = sqrt( stats.get_baseline_variance(1) );
Estimate<double> rmsU = sqrt( stats.get_baseline_variance(2) );
double max_L=0.;
double ph;
/* 1906 - specific */
double ex1l = .013867128125, ex1h=.470;
double ex2l = .542178828125, ex2h=.986787109375;
double mjd = (double)integration->get_epoch().intday() + integration->get_epoch().fracday();
#if 0
if (mjd < 54700) {ex1l = .0111;}
if ( mjd > 53700) {ex1h = .480;}
if ( mjd > 54300) {ex1h = .490398828125;}
if ( mjd > 54150 && mjd < 54200) { ex1h = .480468828125;}
//if ( mjd > 54200 && mjd < 54300) { ex1l = .008298828125; ex1h = .489298828125; ex2l = .533898828125;}
if ( mjd > 54200 && mjd < 54300) { ex1l = .008298828125; ex1h = .49298828125; ex2l = .533898828125; ex2h = .99; }
if ( mjd > 54400 && mjd < 54480) {ex2l = .527298828125; ex1h = .498099499499; ex2h = .9888; ex1l = 0.0138;}
//if ( mjd > 54400 && mjd < 54480) {ex2l = .526298828125; ex1h = .500198828125; ex2h = .989; ex1l = 0.014;}
if ( mjd > 55000) {ex1h = .494; ex2l=0.549;}
//if ( mjd > 55000) {ex1h = .505;}
#endif
for (int ibin=0; ibin<archive->get_nbin(); ibin++) {
ph = ibin/(double) archive->get_nbin();
#if 0
if ((ex1l <= ph && ph <= ex1h) || (ex2l <= ph && ph <= ex2h)) continue;
#endif
//if ((ex1l <= ph && ph <= ex1h) || (ex2l <= ph && ph <= ex2h) || (ex3l <= ph && ph <= ex3h)) continue;
if (integration->get_Profile(0,0)->get_amps()[ibin] > threshold * rmsI.get_value()) {
phase.push_back((ibin+.5)*(2*M_PI/(double)archive->get_nbin()));
phase_bin.push_back(ibin);
totI.push_back(integration->get_Profile(0,0)->get_amps()[ibin]);
Q.push_back(integration->get_Profile(1,0)->get_amps()[ibin]);
U.push_back(integration->get_Profile(2,0)->get_amps()[ibin]);
V.push_back(integration->get_Profile(3,0)->get_amps()[ibin]);
L.push_back( sqrt(U.back()*U.back() + Q.back()*Q.back()));
//cout << totI[ibin] << " " << Q[ibin]<< " " << U[ibin]<<endl;
cout << ibin << " " <<totI.back() << " " << 0.5 * atan2(U.back(), Q.back()) <<endl;
if (L.back() > max_L) max_L = L.back();
}
}
RVM_Fcn fFCN(phase, Q, U, rmsQ.get_value(), rmsU.get_value());
MnUserParameters upar;
upar.Add("alpha", alpha, 10.);
upar.Add("beta", beta , 40.);
upar.Add("phi0", phi0 , 90.);
upar.Add("psi0", psi0 , 90.);
nfree = 4;
if (alpha_fixed) {upar.Fix("alpha"); nfree--;}
if (beta_fixed) {upar.Fix("beta"); nfree--;}
if (phi0_fixed) {upar.Fix("phi0"); nfree--;}
if (psi0_fixed) {upar.Fix("psi0"); nfree--;}
cout<<"initial parameters: "<<upar<<endl;
cout<<"start migrad "<<endl;
MnMinimize migrad(fFCN, upar);
FunctionMinimum min = migrad();
/*if(!min.IsValid()) {
//try with higher strategy
cout<<"FM is invalid, try with strategy = 2."<<endl;
MnMigrad migrad2(fFCN, min.UserState(), MnStrategy(2));
min = migrad2();
} */
cout<<"minimum: "<<min<<endl;
cout<<"Number of points: "<<phase.size()<<endl;
cout<<"chi**2: " << min.Fval()<<endl;
cout<<"R chi**2: " << min.Fval()/(double)((int)Q.size() - nfree - 1) <<endl;
cout<<"start Minos"<<endl;
fFCN.setErrorDef(1.0);
fFCN.setErrorDef(4.);
MnMinos Minos(fFCN, min, MnStrategy(2));
pair<double, double> e0, e1, e2, e3;
if (!alpha_fixed) e0 = Minos(0);
if (!beta_fixed) e1 = Minos(1);
if (!phi0_fixed) e2 = Minos(2);
if (!psi0_fixed) e3 = Minos(3);
if (!alpha_fixed) cout<<"par0: "<<min.UserState().Value("alpha")<<" + "<<e0.first<<" "<<e0.second<<endl;
if (!beta_fixed) cout<<"par1: "<<min.UserState().Value("beta")<<" + "<<e1.first<<" "<<e1.second<<endl;
if (!phi0_fixed) cout<<"par2: "<<min.UserState().Value("phi0")<<" + "<<e2.first<<" "<<e2.second<<endl;
if (!psi0_fixed) cout<<"par3: "<<min.UserState().Value("psi0")<<" + "<<e3.first<<" "<<e3.second<<endl;
{
// create contours factory with FCN and minimum
MnContours contours(fFCN, min);
//fFCN.setErrorDef(5.99);
vector<pair<double,double> > cont4 = contours(0, 1, 20);
// plot the contours
MnPlot plot;
//cont4.insert(cont4.end(), cont.begin(), cont.end());
plot(min.UserState().Value("alpha"), min.UserState().Value("beta"), cont4);
}
cout <<"RVMnuit> "<< mjd<< " " <<min.UserState().Value("alpha")<<" "<<e0.first<<" "<<e0.second <<" "<<min.UserState().Value("beta")<< " "<<e1.first<<" "<<e1.second<<" " <<min.UserState().Value("phi0")<<" "<<e2.first<<" "<<e2.second <<" "<<min.UserState().Value("psi0")<<" "<<e3.first<<" "<<e3.second<< " "<<min.Fval()/(phase.size() - 4 - 1)<<endl;
printf("RVMnuit-tex> %.1f \& \$%.2f\_\{%.2f\}\^\{+%.2f\}\$ \& \$%.2f\_\{%.2f\}\^\{+%.2f\}\$ \& \$%.2f\_\{%.2f\}\^\{+%.2f\}\$ \& \$%.2f\_\{%.2f\}\^\{+%.2f\}\$ \& %.1f \& %d \n", mjd,
min.UserState().Value("alpha"), e0.first, e0.second,
min.UserState().Value("beta"), e1.first, e1.second,
min.UserState().Value("phi0"), e2.first, e2.second,
min.UserState().Value("psi0"), e3.first, e3.second,
min.Fval(), phase.size());
cout << "chi**2: " << min.Fval() << endl;
printf("chi**2: %.14f\n", min.Fval());
if (output) {
write_results(filename, mjd, archive->get_nbin(), rmsI.get_value(), integration->get_Profile(0,0)->get_amps(), integration->get_Profile(1,0)->get_amps(), integration->get_Profile(2,0)->get_amps(), integration->get_Profile(3,0)->get_amps(), phase_bin, Q, U, min.UserState().Value("alpha"), min.UserState().Value("beta"), min.UserState().Value("phi0"), min.UserState().Value("psi0"));
}
return 0;
}
<commit_msg>Improved ascii output of RVMnuit<commit_after>/**********************************************************************
* *
* *
**********************************************************************/
#include "Minuit2/FunctionMinimum.h"
#include "Minuit2/MnMigrad.h"
#include "Minuit2/MnMinos.h"
#include "Minuit2/MnMinimize.h"
#include "Minuit2/MnUserParameters.h"
#include "Minuit2/MnPrint.h"
#include "Minuit2/FCNBase.h"
#include "Minuit2/MnScan.h"
#include "Minuit2/MnPlot.h"
#include "Minuit2/MnContours.h"
#include "Pulsar/Archive.h"
#include "Pulsar/Integration.h"
#include "Pulsar/Profile.h"
//#include "Pulsar/Interpreter.h"
#include "Pulsar/FaradayRotation.h"
#include "Pulsar/PolnProfileStats.h"
#include "RVMKJ_Fcn.C"
#include "write_results.h"
#include "getopt.h"
#include "string.h"
#include "stdio.h"
#include "stdlib.h"
#define R2D (180.0/M_PI)
using namespace std;
using namespace ROOT::Minuit2;
using namespace Pulsar;
int main(int argc, char **argv) {
int nfree = 0;
double threshold=3;
double alpha=80.0, beta=6.0, phi0=18.0, psi0=30.0;
bool alpha_fixed=false, beta_fixed=false, phi0_fixed=false, psi0_fixed=false, output=false;
char filename[128]="test.pa";
char label[16];
static struct option long_opts[] = {
{"thresh", 1, NULL, 't'},
{"alpha", 1, NULL, 'a'},
{"beta", 1, NULL, 'b'},
{"phi0", 1, NULL, 'p'},
{"psi0", 1, NULL, 'z'},
{"Alpha", 0, NULL, 'A'},
{"Beta", 0, NULL, 'B'},
{"Phi0", 0, NULL, 'P'},
{"Psi0", 0, NULL, 'Z'},
{"help", 0, NULL, 'h'},
{"file", 0, NULL, 'f'},
{0,0,0,0}
};
int opt, opti;
while ((opt=getopt_long(argc,argv,"t:a:b:p:z:ABPZohf:",long_opts,&opti))!=-1) {
switch (opt) {
case 't':
threshold = atof(optarg);
break;
case 'a':
alpha = atof(optarg);
break;
case 'b':
beta = atof(optarg);
break;
case 'p':
phi0 = atof(optarg);
break;
case 'z':
psi0 = atof(optarg);
break;
case 'A':
alpha_fixed = true;
break;
case 'B':
beta_fixed = true;
break;
case 'P':
phi0_fixed = true;
break;
case 'Z':
psi0_fixed = true;
break;
case 'o':
output = true;
break;
case 'f':
strncpy(filename, optarg, 127);
break;
case 'h':
default:
//usage();
exit(0);
break;
}
}
vector<int> phase_bin;
vector<double> phase;
vector<double> totI, L, Q, U, V;
Reference::To< Archive > archive = Archive::load( filename );
if( !archive ) return -1;
// correct PA to infinite frequency
FaradayRotation xform;
xform.set_reference_wavelength( 0 );
xform.set_measure( archive->get_rotation_measure() );
xform.execute( archive );
// Scrunch and Remove baseline
archive->tscrunch();
archive->fscrunch();
if( archive->get_state() != Signal::Stokes) archive->convert_state(Signal::Stokes);
archive->remove_baseline();
// Get Data
Pulsar::Integration* integration = archive->get_Integration(0);
Pulsar::PolnProfileStats stats;
stats.set_profile(integration->new_PolnProfile(0));
Estimate<double> rmsI = sqrt( stats.get_baseline_variance(0) );
Estimate<double> rmsQ = sqrt( stats.get_baseline_variance(1) );
Estimate<double> rmsU = sqrt( stats.get_baseline_variance(2) );
double max_L=0.;
double ph;
/* 1906 - specific */
double ex1l = .013867128125, ex1h=.470;
double ex2l = .542178828125, ex2h=.986787109375;
double ex3l, ex3h;
ex1l = 0.0; ex1h=.25;
ex2l = 0.39; ex2h = 0.78;
ex3l = 0.92; ex3h = 1.0;
double mjd = (double)integration->get_epoch().intday() + integration->get_epoch().fracday();
#if 0
if (mjd < 54700) {ex1l = .0111;}
if ( mjd > 53700) {ex1h = .480;}
if ( mjd > 54300) {ex1h = .490398828125;}
if ( mjd > 54150 && mjd < 54200) { ex1h = .480468828125;}
//if ( mjd > 54200 && mjd < 54300) { ex1l = .008298828125; ex1h = .489298828125; ex2l = .533898828125;}
if ( mjd > 54200 && mjd < 54300) { ex1l = .008298828125; ex1h = .49298828125; ex2l = .533898828125; ex2h = .99; }
if ( mjd > 54400 && mjd < 54480) {ex2l = .527298828125; ex1h = .498099499499; ex2h = .9888; ex1l = 0.0138;}
//if ( mjd > 54400 && mjd < 54480) {ex2l = .526298828125; ex1h = .500198828125; ex2h = .989; ex1l = 0.014;}
if ( mjd > 55000) {ex1h = .494; ex2l=0.549;}
//if ( mjd > 55000) {ex1h = .505;}
#endif
for (int ibin=0; ibin<archive->get_nbin(); ibin++) {
ph = ibin/(double) archive->get_nbin();
//if ((ex1l <= ph && ph <= ex1h) || (ex2l <= ph && ph <= ex2h)) continue;
if ((ex1l <= ph && ph <= ex1h) || (ex2l <= ph && ph <= ex2h) || (ex3l <= ph && ph <= ex3h)) continue;
if (integration->get_Profile(0,0)->get_amps()[ibin] > threshold * rmsI.get_value()) {
phase.push_back((ibin+.5)*(2*M_PI/(double)archive->get_nbin()));
phase_bin.push_back(ibin);
totI.push_back(integration->get_Profile(0,0)->get_amps()[ibin]);
Q.push_back(integration->get_Profile(1,0)->get_amps()[ibin]);
U.push_back(integration->get_Profile(2,0)->get_amps()[ibin]);
V.push_back(integration->get_Profile(3,0)->get_amps()[ibin]);
L.push_back( sqrt(U.back()*U.back() + Q.back()*Q.back()));
//cout << totI[ibin] << " " << Q[ibin]<< " " << U[ibin]<<endl;
//cout << ibin << " " <<totI.back() << " " << 0.5 * atan2(U.back(), Q.back()) <<endl;
if (L.back() > max_L) max_L = L.back();
}
}
RVM_Fcn fFCN(phase, Q, U, rmsQ.get_value(), rmsU.get_value());
MnUserParameters upar;
upar.Add("alpha", alpha, 10.);
upar.Add("beta", beta , 40.);
upar.Add("phi0", phi0 , 90.);
upar.Add("psi0", psi0 , 90.);
nfree = 4;
if (alpha_fixed) {upar.Fix("alpha"); nfree--;}
if (beta_fixed) {upar.Fix("beta"); nfree--;}
if (phi0_fixed) {upar.Fix("phi0"); nfree--;}
if (psi0_fixed) {upar.Fix("psi0"); nfree--;}
cout<<"initial parameters: "<<upar<<endl;
cout<<"start migrad "<<endl;
MnMinimize migrad(fFCN, upar);
FunctionMinimum min = migrad();
/*if(!min.IsValid()) {
//try with higher strategy
cout<<"FM is invalid, try with strategy = 2."<<endl;
MnMigrad migrad2(fFCN, min.UserState(), MnStrategy(2));
min = migrad2();
} */
cout<<"minimum: "<<min<<endl;
cout<<"Number of points: "<<phase.size()<<endl;
cout<<"chi**2: " << min.Fval()<<endl;
cout<<"R chi**2: " << min.Fval()/(double)((int)Q.size() - nfree - 1) <<endl;
cout<<"start Minos"<<endl;
fFCN.setErrorDef(1.0);
fFCN.setErrorDef(4.);
MnMinos Minos(fFCN, min, MnStrategy(2));
pair<double, double> e0, e1, e2, e3;
if (!alpha_fixed) e0 = Minos(0);
if (!beta_fixed) e1 = Minos(1);
if (!phi0_fixed) e2 = Minos(2);
if (!psi0_fixed) e3 = Minos(3);
if (!alpha_fixed) cout<<"Alpha: "<<min.UserState().Value("alpha")<<" + "<<e0.first<<" "<<e0.second<<endl;
if (!beta_fixed) cout<<"Beta: "<<min.UserState().Value("beta")<<" + "<<e1.first<<" "<<e1.second<<endl;
if (!phi0_fixed) cout<<"Phi0: "<<min.UserState().Value("phi0")<<" + "<<e2.first<<" "<<e2.second<<endl;
if (!psi0_fixed) cout<<"Psi0: "<<min.UserState().Value("psi0")<<" + "<<e3.first<<" "<<e3.second<<endl;
if (!alpha_fixed and !beta_fixed) {
// create contours factory with FCN and minimum
MnContours contours(fFCN, min);
//fFCN.setErrorDef(5.99);
vector<pair<double,double> > cont4 = contours(0, 1, 20);
// plot the contours
MnPlot plot;
//cont4.insert(cont4.end(), cont.begin(), cont.end());
plot(min.UserState().Value("alpha"), min.UserState().Value("beta"), cont4);
}
cout <<"RVMnuit> "<< mjd<< " ";
if (!alpha_fixed) cout << min.UserState().Value("alpha")<<" "<<e0.first<<" "<<e0.second <<" ";
if (!beta_fixed) cout << min.UserState().Value("beta")<< " "<<e1.first<<" "<<e1.second <<" ";
if (!phi0_fixed) cout << min.UserState().Value("phi0")<<" "<<e2.first<<" "<<e2.second <<" ";
if (!psi0_fixed) cout << min.UserState().Value("psi0")<<" "<<e3.first<<" "<<e3.second<< " ";
cout << min.Fval()/(phase.size() - 4 - 1)<<endl;
/*
printf("RVMnuit-tex> %.1f \& \$%.2f\_\{%.2f\}\^\{+%.2f\}\$ \& \$%.2f\_\{%.2f\}\^\{+%.2f\}\$ \& \$%.2f\_\{%.2f\}\^\{+%.2f\}\$ \& \$%.2f\_\{%.2f\}\^\{+%.2f\}\$ \& %.1f \& %d \n", mjd,
min.UserState().Value("alpha"), e0.first, e0.second,
min.UserState().Value("beta"), e1.first, e1.second,
min.UserState().Value("phi0"), e2.first, e2.second,
min.UserState().Value("psi0"), e3.first, e3.second,
min.Fval(), phase.size());*/
cout << "RVMnuit-tex> " << mjd << " ";
if (!alpha_fixed) cout <<"\& \$"<< min.UserState().Value("alpha")<<" \_\{ "<<e0.first<<"\}\^\{+ "<<e0.second <<"\}\$ ";
if (!beta_fixed) cout <<"\& \$"<< min.UserState().Value("beta")<< " \_\{ "<<e1.first<<"\}\^\{+ "<<e1.second <<"\}\$ ";
if (!phi0_fixed) cout <<"\& \$"<< min.UserState().Value("phi0")<<" \_\{ "<<e2.first<<"\}\^\{+ "<<e2.second <<"\}\$ ";
if (!psi0_fixed) cout <<"\& \$"<< min.UserState().Value("psi0")<<" \_\{ "<<e3.first<<"\}\^\{+ "<<e3.second<< "\}\$ ";
cout << min.Fval() << " "<< (phase.size())<<endl;
cout << "chi**2: " << min.Fval() << endl;
printf("chi**2: %.14f\n", min.Fval());
if (output) {
write_results(filename, mjd, archive->get_nbin(), rmsI.get_value(), integration->get_Profile(0,0)->get_amps(), integration->get_Profile(1,0)->get_amps(), integration->get_Profile(2,0)->get_amps(), integration->get_Profile(3,0)->get_amps(), phase_bin, Q, U, min.UserState().Value("alpha"), min.UserState().Value("beta"), min.UserState().Value("phi0"), min.UserState().Value("psi0"));
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) 2014 Pavel Strakhov
*
* 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 "ToolWindowManagerArea.h"
#include "ToolWindowManager.h"
#include <QApplication>
#include <QMouseEvent>
#include <QDebug>
ToolWindowManagerArea::ToolWindowManagerArea(ToolWindowManager *manager, QWidget *parent) :
QTabWidget(parent)
, m_manager(manager)
{
m_dragCanStart = false;
m_tabDragCanStart = false;
m_inTabMoved = false;
setMovable(true);
setTabsClosable(true);
setDocumentMode(true);
tabBar()->installEventFilter(this);
m_manager->m_areas << this;
QObject::connect(tabBar(), &QTabBar::tabMoved, this, &ToolWindowManagerArea::tabMoved);
}
ToolWindowManagerArea::~ToolWindowManagerArea() {
m_manager->m_areas.removeOne(this);
}
void ToolWindowManagerArea::addToolWindow(QWidget *toolWindow) {
addToolWindows(QList<QWidget*>() << toolWindow);
}
void ToolWindowManagerArea::addToolWindows(const QList<QWidget *> &toolWindows) {
int index = 0;
foreach(QWidget* toolWindow, toolWindows) {
index = addTab(toolWindow, toolWindow->windowIcon(), toolWindow->windowTitle());
if(m_manager->toolWindowProperties(toolWindow) & ToolWindowManager::HideCloseButton) {
tabBar()->tabButton(index, QTabBar::RightSide)->resize(0, 0);
}
}
setCurrentIndex(index);
m_manager->m_lastUsedArea = this;
}
QList<QWidget *> ToolWindowManagerArea::toolWindows() {
QList<QWidget *> result;
for(int i = 0; i < count(); i++) {
result << widget(i);
}
return result;
}
void ToolWindowManagerArea::updateToolWindow(QWidget* toolWindow) {
int index = indexOf(toolWindow);
if(index >= 0) {
if(m_manager->toolWindowProperties(toolWindow) & ToolWindowManager::HideCloseButton) {
tabBar()->tabButton(index, QTabBar::RightSide)->resize(0, 0);
} else {
tabBar()->tabButton(index, QTabBar::RightSide)->resize(16, 16);
}
tabBar()->setTabText(index, toolWindow->windowTitle());
}
}
void ToolWindowManagerArea::mousePressEvent(QMouseEvent *) {
if (qApp->mouseButtons() == Qt::LeftButton) {
m_dragCanStart = true;
}
}
void ToolWindowManagerArea::mouseReleaseEvent(QMouseEvent *) {
m_dragCanStart = false;
m_manager->updateDragPosition();
}
void ToolWindowManagerArea::mouseMoveEvent(QMouseEvent *) {
check_mouse_move();
}
bool ToolWindowManagerArea::eventFilter(QObject *object, QEvent *event) {
if (object == tabBar()) {
if (event->type() == QEvent::MouseButtonPress &&
qApp->mouseButtons() == Qt::LeftButton) {
int tabIndex = tabBar()->tabAt(static_cast<QMouseEvent*>(event)->pos());
// can start tab drag only if mouse is at some tab, not at empty tabbar space
if (tabIndex >= 0) {
m_tabDragCanStart = true;
if (m_manager->toolWindowProperties(widget(tabIndex)) & ToolWindowManager::DisableDraggableTab) {
setMovable(false);
} else {
setMovable(true);
}
} else {
m_dragCanStart = true;
}
} else if (event->type() == QEvent::MouseButtonRelease) {
m_tabDragCanStart = false;
m_dragCanStart = false;
m_manager->updateDragPosition();
} else if (event->type() == QEvent::MouseMove) {
m_manager->updateDragPosition();
if (m_tabDragCanStart) {
if (tabBar()->rect().contains(static_cast<QMouseEvent*>(event)->pos())) {
return false;
}
if (qApp->mouseButtons() != Qt::LeftButton) {
return false;
}
QWidget* toolWindow = currentWidget();
if (!toolWindow || !m_manager->m_toolWindows.contains(toolWindow)) {
return false;
}
m_tabDragCanStart = false;
//stop internal tab drag in QTabBar
QMouseEvent* releaseEvent = new QMouseEvent(QEvent::MouseButtonRelease,
static_cast<QMouseEvent*>(event)->pos(),
Qt::LeftButton, Qt::LeftButton, 0);
qApp->sendEvent(tabBar(), releaseEvent);
m_manager->startDrag(QList<QWidget*>() << toolWindow);
} else if (m_dragCanStart) {
check_mouse_move();
}
}
}
return QTabWidget::eventFilter(object, event);
}
QVariantMap ToolWindowManagerArea::saveState() {
QVariantMap result;
result["type"] = "area";
result["currentIndex"] = currentIndex();
QStringList objectNames;
for(int i = 0; i < count(); i++) {
QString name = widget(i)->objectName();
if (name.isEmpty()) {
qWarning("cannot save state of tool window without object name");
} else {
objectNames << name;
}
}
result["objectNames"] = objectNames;
return result;
}
void ToolWindowManagerArea::restoreState(const QVariantMap &data) {
foreach(QVariant objectNameValue, data["objectNames"].toList()) {
QString objectName = objectNameValue.toString();
if (objectName.isEmpty()) { continue; }
bool found = false;
foreach(QWidget* toolWindow, m_manager->m_toolWindows) {
if (toolWindow->objectName() == objectName) {
addToolWindow(toolWindow);
found = true;
break;
}
}
if (!found) {
qWarning("tool window with name '%s' not found", objectName.toLocal8Bit().constData());
}
}
setCurrentIndex(data["currentIndex"].toInt());
}
void ToolWindowManagerArea::check_mouse_move() {
m_manager->updateDragPosition();
if (qApp->mouseButtons() == Qt::LeftButton &&
!rect().contains(mapFromGlobal(QCursor::pos())) &&
m_dragCanStart) {
m_dragCanStart = false;
QList<QWidget*> toolWindows;
for(int i = 0; i < count(); i++) {
QWidget* toolWindow = widget(i);
if (!m_manager->m_toolWindows.contains(toolWindow)) {
qWarning("tab widget contains unmanaged widget");
} else {
toolWindows << toolWindow;
}
}
m_manager->startDrag(toolWindows);
}
}
void ToolWindowManagerArea::tabMoved(int from, int to) {
if(m_inTabMoved) return;
QWidget *a = widget(from);
QWidget *b = widget(to);
if(!a || !b) return;
if(m_manager->toolWindowProperties(a) & ToolWindowManager::DisableDraggableTab ||
m_manager->toolWindowProperties(b) & ToolWindowManager::DisableDraggableTab)
{
m_inTabMoved = true;
tabBar()->moveTab(to, from);
m_inTabMoved = false;
}
}
<commit_msg>Serialise area objects as [name, data] pairs, with custom persist data<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2014 Pavel Strakhov
*
* 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 "ToolWindowManagerArea.h"
#include "ToolWindowManager.h"
#include <QApplication>
#include <QMouseEvent>
#include <QDebug>
ToolWindowManagerArea::ToolWindowManagerArea(ToolWindowManager *manager, QWidget *parent) :
QTabWidget(parent)
, m_manager(manager)
{
m_dragCanStart = false;
m_tabDragCanStart = false;
m_inTabMoved = false;
setMovable(true);
setTabsClosable(true);
setDocumentMode(true);
tabBar()->installEventFilter(this);
m_manager->m_areas << this;
QObject::connect(tabBar(), &QTabBar::tabMoved, this, &ToolWindowManagerArea::tabMoved);
}
ToolWindowManagerArea::~ToolWindowManagerArea() {
m_manager->m_areas.removeOne(this);
}
void ToolWindowManagerArea::addToolWindow(QWidget *toolWindow) {
addToolWindows(QList<QWidget*>() << toolWindow);
}
void ToolWindowManagerArea::addToolWindows(const QList<QWidget *> &toolWindows) {
int index = 0;
foreach(QWidget* toolWindow, toolWindows) {
index = addTab(toolWindow, toolWindow->windowIcon(), toolWindow->windowTitle());
if(m_manager->toolWindowProperties(toolWindow) & ToolWindowManager::HideCloseButton) {
tabBar()->tabButton(index, QTabBar::RightSide)->resize(0, 0);
}
}
setCurrentIndex(index);
m_manager->m_lastUsedArea = this;
}
QList<QWidget *> ToolWindowManagerArea::toolWindows() {
QList<QWidget *> result;
for(int i = 0; i < count(); i++) {
result << widget(i);
}
return result;
}
void ToolWindowManagerArea::updateToolWindow(QWidget* toolWindow) {
int index = indexOf(toolWindow);
if(index >= 0) {
if(m_manager->toolWindowProperties(toolWindow) & ToolWindowManager::HideCloseButton) {
tabBar()->tabButton(index, QTabBar::RightSide)->resize(0, 0);
} else {
tabBar()->tabButton(index, QTabBar::RightSide)->resize(16, 16);
}
tabBar()->setTabText(index, toolWindow->windowTitle());
}
}
void ToolWindowManagerArea::mousePressEvent(QMouseEvent *) {
if (qApp->mouseButtons() == Qt::LeftButton) {
m_dragCanStart = true;
}
}
void ToolWindowManagerArea::mouseReleaseEvent(QMouseEvent *) {
m_dragCanStart = false;
m_manager->updateDragPosition();
}
void ToolWindowManagerArea::mouseMoveEvent(QMouseEvent *) {
check_mouse_move();
}
bool ToolWindowManagerArea::eventFilter(QObject *object, QEvent *event) {
if (object == tabBar()) {
if (event->type() == QEvent::MouseButtonPress &&
qApp->mouseButtons() == Qt::LeftButton) {
int tabIndex = tabBar()->tabAt(static_cast<QMouseEvent*>(event)->pos());
// can start tab drag only if mouse is at some tab, not at empty tabbar space
if (tabIndex >= 0) {
m_tabDragCanStart = true;
if (m_manager->toolWindowProperties(widget(tabIndex)) & ToolWindowManager::DisableDraggableTab) {
setMovable(false);
} else {
setMovable(true);
}
} else {
m_dragCanStart = true;
}
} else if (event->type() == QEvent::MouseButtonRelease) {
m_tabDragCanStart = false;
m_dragCanStart = false;
m_manager->updateDragPosition();
} else if (event->type() == QEvent::MouseMove) {
m_manager->updateDragPosition();
if (m_tabDragCanStart) {
if (tabBar()->rect().contains(static_cast<QMouseEvent*>(event)->pos())) {
return false;
}
if (qApp->mouseButtons() != Qt::LeftButton) {
return false;
}
QWidget* toolWindow = currentWidget();
if (!toolWindow || !m_manager->m_toolWindows.contains(toolWindow)) {
return false;
}
m_tabDragCanStart = false;
//stop internal tab drag in QTabBar
QMouseEvent* releaseEvent = new QMouseEvent(QEvent::MouseButtonRelease,
static_cast<QMouseEvent*>(event)->pos(),
Qt::LeftButton, Qt::LeftButton, 0);
qApp->sendEvent(tabBar(), releaseEvent);
m_manager->startDrag(QList<QWidget*>() << toolWindow);
} else if (m_dragCanStart) {
check_mouse_move();
}
}
}
return QTabWidget::eventFilter(object, event);
}
QVariantMap ToolWindowManagerArea::saveState() {
QVariantMap result;
result["type"] = "area";
result["currentIndex"] = currentIndex();
QVariantList objects;
objects.reserve(count());
for(int i = 0; i < count(); i++) {
QWidget *w = widget(i);
QString name = w->objectName();
if (name.isEmpty()) {
qWarning("cannot save state of tool window without object name");
} else {
QVariantMap objectData;
objectData["name"] = name;
objectData["data"] = w->property("persistData");
objects.push_back(objectData);
}
}
result["objects"] = objects;
return result;
}
void ToolWindowManagerArea::restoreState(const QVariantMap &data) {
foreach(QVariant object, data["objects"].toList()) {
QVariantMap objectData = object.toMap();
if (objectData.isEmpty()) { continue; }
QString objectName = objectData["name"].toString();
if (objectName.isEmpty()) { continue; }
QWidget *t = NULL;
foreach(QWidget* toolWindow, m_manager->m_toolWindows) {
if (toolWindow->objectName() == objectName) {
t = toolWindow;
break;
}
}
if (t) {
t->setProperty("persistData", objectData["data"]);
addToolWindow(t);
} else {
qWarning("tool window with name '%s' not found or created", objectName.toLocal8Bit().constData());
}
}
setCurrentIndex(data["currentIndex"].toInt());
}
void ToolWindowManagerArea::check_mouse_move() {
m_manager->updateDragPosition();
if (qApp->mouseButtons() == Qt::LeftButton &&
!rect().contains(mapFromGlobal(QCursor::pos())) &&
m_dragCanStart) {
m_dragCanStart = false;
QList<QWidget*> toolWindows;
for(int i = 0; i < count(); i++) {
QWidget* toolWindow = widget(i);
if (!m_manager->m_toolWindows.contains(toolWindow)) {
qWarning("tab widget contains unmanaged widget");
} else {
toolWindows << toolWindow;
}
}
m_manager->startDrag(toolWindows);
}
}
void ToolWindowManagerArea::tabMoved(int from, int to) {
if(m_inTabMoved) return;
QWidget *a = widget(from);
QWidget *b = widget(to);
if(!a || !b) return;
if(m_manager->toolWindowProperties(a) & ToolWindowManager::DisableDraggableTab ||
m_manager->toolWindowProperties(b) & ToolWindowManager::DisableDraggableTab)
{
m_inTabMoved = true;
tabBar()->moveTab(to, from);
m_inTabMoved = false;
}
}
<|endoftext|> |
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2006 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#include "GraphicsTest.h"
#include "FBOImage.h"
#include "GPUBrightnessFilter.h"
#include "GPUBlurFilter.h"
#include "GPUBandpassFilter.h"
#include "OGLImagingContext.h"
#include "../base/TestSuite.h"
#include <iostream>
using namespace avg;
using namespace std;
class FBOTest: public GraphicsTest {
public:
FBOTest()
: GraphicsTest("FBOTest", 2)
{
}
void runTests()
{
runImageTests("i8-64x64", GL_UNSIGNED_BYTE, I8);
runImageTests("rgb24-64x64", GL_UNSIGNED_BYTE);
runImageTests("rgb24alpha-64x64", GL_UNSIGNED_BYTE);
runImageTests("i8-64x64", GL_FLOAT, I8);
runImageTests("rgb24-64x64", GL_FLOAT);
runImageTests("rgb24alpha-64x64", GL_FLOAT);
runParameterPBOTest();
}
private:
void runImageTests(const string& sFName, int precision, PixelFormat pf = R8G8B8X8)
{
BitmapPtr pBmp = loadTestBmp(sFName, pf);
cerr << " Testing " << sFName << " (" << pBmp->getPixelFormatString() << ")" << endl;
cerr << " PBO:" << endl;
PBOImage pbo(pBmp->getSize(), pBmp->getPixelFormat(), precision, true, true);
runPBOImageTest(pbo, pBmp, string("pbo_")+sFName);
if (pf != I8) {
cerr << " FBO:" << endl;
FBOImage fbo(pBmp->getSize(), pBmp->getPixelFormat(), precision, true, true);
runPBOImageTest(fbo, pBmp, string("fbo_")+sFName);
}
}
void runParameterPBOTest()
{
cerr << " Testing parameter PBO" << endl;
PBOImage pbo(IntPoint(11, 1), I8, GL_FLOAT, false, false);
float data[11];
pbo.setImage(data);
}
void runPBOImageTest(PBOImage& pbo, BitmapPtr pBmp, const string& sFName)
{
pbo.setImage(pBmp);
BitmapPtr pNewBmp = pbo.getImage();
testEqual(*pNewBmp, *pBmp, sFName);
}
};
class BrightnessFilterTest: public GraphicsTest {
public:
BrightnessFilterTest()
: GraphicsTest("BrightnessFilterTest", 2)
{
}
void runTests()
{
runImageTests("rgb24-64x64");
runImageTests("rgb24alpha-64x64");
}
private:
void runImageTests(const string& sFName)
{
cerr << " Testing " << sFName << endl;
BitmapPtr pBmp = loadTestBmp(sFName);
BitmapPtr pDestBmp;
pDestBmp = GPUBrightnessFilter(pBmp->getSize(), pBmp->getPixelFormat(), 1).apply(pBmp);
testEqual(*pDestBmp, *pBmp, string("brightness_")+sFName);
}
};
class BlurFilterTest: public GraphicsTest {
public:
BlurFilterTest()
: GraphicsTest("BlurFilterTest", 2)
{
}
void runTests()
{
BitmapPtr pBmp;
BitmapPtr pDestBmp;
/*
// This has the effect of printing out all the brightness differences for different
// kernel sizes.
pBmp = loadTestBmp("spike");
for (double stddev = 0.5; stddev < 5; stddev += 0.25) {
pDestBmp = GPUBlurFilter(pBmp->getSize(), pBmp->getPixelFormat(), stddev).apply(pBmp);
testEqualBrightness(*pDestBmp, *pBmp, 1);
}
*/
cerr << " Testing spike, stddev 0.5" << endl;
pBmp = loadTestBmp("spike");
pDestBmp = GPUBlurFilter(pBmp->getSize(), pBmp->getPixelFormat(), 0.5).apply(pBmp);
testEqualBrightness(*pDestBmp, *pBmp, 5);
testEqual(*pDestBmp, "blur05_spike");
cerr << " Testing spike, stddev 1" << endl;
pDestBmp = GPUBlurFilter(pBmp->getSize(), pBmp->getPixelFormat(), 1).apply(pBmp);
// testEqualBrightness(*pDestBmp, *pBmp, 5);
testEqual(*pDestBmp, "blur1_spike");
cerr << " Testing spike, stddev 3" << endl;
pDestBmp = GPUBlurFilter(pBmp->getSize(), pBmp->getPixelFormat(), 3).apply(pBmp);
// testEqualBrightness(*pDestBmp, *pBmp, 5);
testEqual(*pDestBmp, "blur5_spike");
cerr << " Testing flat, stddev 5" << endl;
pBmp = loadTestBmp("flat");
pDestBmp = GPUBlurFilter(pBmp->getSize(), pBmp->getPixelFormat(), 5).apply(pBmp);
testEqualBrightness(*pDestBmp, *pBmp, 1);
testEqual(*pDestBmp, *pBmp, "blur05_flat");
runImageTests("rgb24-64x64");
runImageTests("rgb24alpha-64x64");
}
private:
void runImageTests(const string& sFName)
{
cerr << " Testing " << sFName << endl;
BitmapPtr pBmp = loadTestBmp(sFName);
BitmapPtr pDestBmp;
pDestBmp = GPUBlurFilter(pBmp->getSize(), pBmp->getPixelFormat(), 10).apply(pBmp);
testEqual(*pDestBmp, string("blur_")+sFName);
}
};
class BandpassFilterTest: public GraphicsTest {
public:
BandpassFilterTest()
: GraphicsTest("BandpassFilterTest", 2)
{
}
void runTests()
{
runImageTests("spike", B8G8R8X8);
runImageTests("i8-64x64", I8);
}
private:
void runImageTests(const string& sFName, PixelFormat pf)
{
cerr << " Testing " << sFName << endl;
BitmapPtr pBmp = loadTestBmp(sFName, pf);
GPUBandpassFilter f(pBmp->getSize(), pf, 0.5, 1.5, 1, false);
BitmapPtr pDestBmp = f.apply(pBmp);
cerr << " " << pDestBmp->avg() << endl;
TEST(fabs(pDestBmp->avg() -128) < 0.05);
testEqual(*pDestBmp, "bandpass_"+sFName, pf);
TEST(pDestBmp->getPixelFormat() == pf);
}
};
class GPUTestSuite: public TestSuite {
public:
GPUTestSuite()
: TestSuite("GPUTestSuite")
{
addTest(TestPtr(new FBOTest));
addTest(TestPtr(new BrightnessFilterTest));
addTest(TestPtr(new BlurFilterTest));
addTest(TestPtr(new BandpassFilterTest));
}
};
int main(int nargs, char** args)
{
GraphicsTest::createResultImgDir();
OGLImagingContext context(IntPoint(64, 64));
bool bOK;
if (!FBOImage::isFBOSupported()) {
bOK = true;
cerr << " GL_EXT_framebuffer_object not supported. Skipping FBO test." << endl;
} else {
GPUTestSuite Suite;
Suite.runTests();
bOK = Suite.isOk();
}
if (bOK) {
return 0;
} else {
return 1;
}
}
<commit_msg>More lenient gpu test epsilons due to failures on GeForce 7600.<commit_after>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2006 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#include "GraphicsTest.h"
#include "FBOImage.h"
#include "GPUBrightnessFilter.h"
#include "GPUBlurFilter.h"
#include "GPUBandpassFilter.h"
#include "OGLImagingContext.h"
#include "../base/TestSuite.h"
#include <iostream>
using namespace avg;
using namespace std;
class FBOTest: public GraphicsTest {
public:
FBOTest()
: GraphicsTest("FBOTest", 2)
{
}
void runTests()
{
runImageTests("i8-64x64", GL_UNSIGNED_BYTE, I8);
runImageTests("rgb24-64x64", GL_UNSIGNED_BYTE);
runImageTests("rgb24alpha-64x64", GL_UNSIGNED_BYTE);
runImageTests("i8-64x64", GL_FLOAT, I8);
runImageTests("rgb24-64x64", GL_FLOAT);
runImageTests("rgb24alpha-64x64", GL_FLOAT);
runParameterPBOTest();
}
private:
void runImageTests(const string& sFName, int precision, PixelFormat pf = R8G8B8X8)
{
BitmapPtr pBmp = loadTestBmp(sFName, pf);
cerr << " Testing " << sFName << " (" << pBmp->getPixelFormatString() << ")" << endl;
cerr << " PBO:" << endl;
PBOImage pbo(pBmp->getSize(), pBmp->getPixelFormat(), precision, true, true);
runPBOImageTest(pbo, pBmp, string("pbo_")+sFName);
if (pf != I8) {
cerr << " FBO:" << endl;
FBOImage fbo(pBmp->getSize(), pBmp->getPixelFormat(), precision, true, true);
runPBOImageTest(fbo, pBmp, string("fbo_")+sFName);
}
}
void runParameterPBOTest()
{
cerr << " Testing parameter PBO" << endl;
PBOImage pbo(IntPoint(11, 1), I8, GL_FLOAT, false, false);
float data[11];
pbo.setImage(data);
}
void runPBOImageTest(PBOImage& pbo, BitmapPtr pBmp, const string& sFName)
{
pbo.setImage(pBmp);
BitmapPtr pNewBmp = pbo.getImage();
testEqual(*pNewBmp, *pBmp, sFName);
}
};
class BrightnessFilterTest: public GraphicsTest {
public:
BrightnessFilterTest()
: GraphicsTest("BrightnessFilterTest", 2)
{
}
void runTests()
{
runImageTests("rgb24-64x64");
runImageTests("rgb24alpha-64x64");
}
private:
void runImageTests(const string& sFName)
{
cerr << " Testing " << sFName << endl;
BitmapPtr pBmp = loadTestBmp(sFName);
BitmapPtr pDestBmp;
pDestBmp = GPUBrightnessFilter(pBmp->getSize(), pBmp->getPixelFormat(), 1).apply(pBmp);
testEqual(*pDestBmp, *pBmp, string("brightness_")+sFName);
}
};
class BlurFilterTest: public GraphicsTest {
public:
BlurFilterTest()
: GraphicsTest("BlurFilterTest", 2)
{
}
void runTests()
{
BitmapPtr pBmp;
BitmapPtr pDestBmp;
/*
// This has the effect of printing out all the brightness differences for different
// kernel sizes.
pBmp = loadTestBmp("spike");
for (double stddev = 0.5; stddev < 5; stddev += 0.25) {
pDestBmp = GPUBlurFilter(pBmp->getSize(), pBmp->getPixelFormat(), stddev).apply(pBmp);
testEqualBrightness(*pDestBmp, *pBmp, 1);
}
*/
cerr << " Testing spike, stddev 0.5" << endl;
pBmp = loadTestBmp("spike");
pDestBmp = GPUBlurFilter(pBmp->getSize(), pBmp->getPixelFormat(), 0.5).apply(pBmp);
testEqualBrightness(*pDestBmp, *pBmp, 7);
testEqual(*pDestBmp, "blur05_spike");
cerr << " Testing spike, stddev 1" << endl;
pDestBmp = GPUBlurFilter(pBmp->getSize(), pBmp->getPixelFormat(), 1).apply(pBmp);
// testEqualBrightness(*pDestBmp, *pBmp, 5);
testEqual(*pDestBmp, "blur1_spike");
cerr << " Testing spike, stddev 3" << endl;
pDestBmp = GPUBlurFilter(pBmp->getSize(), pBmp->getPixelFormat(), 3).apply(pBmp);
// testEqualBrightness(*pDestBmp, *pBmp, 5);
testEqual(*pDestBmp, "blur5_spike");
cerr << " Testing flat, stddev 5" << endl;
pBmp = loadTestBmp("flat");
pDestBmp = GPUBlurFilter(pBmp->getSize(), pBmp->getPixelFormat(), 5).apply(pBmp);
testEqualBrightness(*pDestBmp, *pBmp, 1);
testEqual(*pDestBmp, *pBmp, "blur05_flat");
runImageTests("rgb24-64x64");
runImageTests("rgb24alpha-64x64");
}
private:
void runImageTests(const string& sFName)
{
cerr << " Testing " << sFName << endl;
BitmapPtr pBmp = loadTestBmp(sFName);
BitmapPtr pDestBmp;
pDestBmp = GPUBlurFilter(pBmp->getSize(), pBmp->getPixelFormat(), 10).apply(pBmp);
testEqual(*pDestBmp, string("blur_")+sFName);
}
};
class BandpassFilterTest: public GraphicsTest {
public:
BandpassFilterTest()
: GraphicsTest("BandpassFilterTest", 2)
{
}
void runTests()
{
runImageTests("spike", B8G8R8X8);
runImageTests("i8-64x64", I8);
}
private:
void runImageTests(const string& sFName, PixelFormat pf)
{
cerr << " Testing " << sFName << endl;
BitmapPtr pBmp = loadTestBmp(sFName, pf);
GPUBandpassFilter f(pBmp->getSize(), pf, 0.5, 1.5, 1, false);
BitmapPtr pDestBmp = f.apply(pBmp);
cerr << " " << pDestBmp->avg() << endl;
TEST(fabs(pDestBmp->avg() -128) < 0.06);
testEqual(*pDestBmp, "bandpass_"+sFName, pf);
TEST(pDestBmp->getPixelFormat() == pf);
}
};
class GPUTestSuite: public TestSuite {
public:
GPUTestSuite()
: TestSuite("GPUTestSuite")
{
addTest(TestPtr(new FBOTest));
addTest(TestPtr(new BrightnessFilterTest));
addTest(TestPtr(new BlurFilterTest));
addTest(TestPtr(new BandpassFilterTest));
}
};
int main(int nargs, char** args)
{
GraphicsTest::createResultImgDir();
OGLImagingContext context(IntPoint(64, 64));
bool bOK;
if (!FBOImage::isFBOSupported()) {
bOK = true;
cerr << " GL_EXT_framebuffer_object not supported. Skipping FBO test." << endl;
} else {
GPUTestSuite Suite;
Suite.runTests();
bOK = Suite.isOk();
}
if (bOK) {
return 0;
} else {
return 1;
}
}
<|endoftext|> |
<commit_before>#include "graphics/texture.h"
#include "graphics/opengl.h"
#include <array>
#include <SDL_assert.h>
#include <transcoder/basisu_transcoder.h>
namespace {
basist::transcoder_texture_format uastcLoadFormat(const glm::uvec2& size, bool has_alpha, const std::optional<glm::uvec2>& threshold)
{
using format_t = basist::transcoder_texture_format;
if (threshold.has_value())
{
// Do we want uncompressed (texture atlas)
auto dims = threshold.value();
if (size.x <= dims.x || size.y <= dims.y)
return format_t::cTFRGBA32;
}
// Use GPU capabilities, in order of preference.
// ASTC
if (GLAD_GL_KHR_texture_compression_astc_ldr)
return format_t::cTFASTC_4x4_RGBA; // No RGB variant.
// ETC2
if (SP_texture_compression_etc2)
return format_t::cTFETC2_RGBA;
// PVRTC2
if (GLAD_GL_IMG_texture_compression_pvrtc2)
return has_alpha ? format_t::cTFPVRTC2_4_RGBA : format_t::cTFPVRTC2_4_RGB;
// PVRTC1
if (GLAD_GL_IMG_texture_compression_pvrtc)
return has_alpha ? format_t::cTFPVRTC1_4_RGBA : format_t::cTFPVRTC1_4_RGB;
// S3TC/DXT.
if (GLAD_GL_EXT_texture_compression_s3tc)
return has_alpha ? format_t::cTFBC3_RGBA : format_t::cTFBC1_RGB;
// ETC1.
if (GLAD_GL_OES_compressed_ETC1_RGB8_texture && !has_alpha)
return format_t::cTFETC1_RGB;
return format_t::cTFRGBA32;
}
constexpr GLenum basistFormatCast(basist::transcoder_texture_format format)
{
// https://github.com/BinomialLLC/basis_universal/wiki/OpenGL-texture-format-enums-table
using format_t = basist::transcoder_texture_format;
switch (format)
{
// ASTC
case format_t::cTFASTC_4x4_RGBA:
return GL_COMPRESSED_RGBA_ASTC_4x4_KHR;
// ETC2 RGBA
case format_t::cTFETC2_RGBA:
return GL_COMPRESSED_RGBA8_ETC2_EAC;
// PVRTC2
case format_t::cTFPVRTC2_4_RGB:
[[fallthrough]];
case format_t::cTFPVRTC2_4_RGBA:
return GL_COMPRESSED_RGBA_PVRTC_4BPPV2_IMG;
// PVRTC1
case format_t::cTFPVRTC1_4_RGB:
return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
case format_t::cTFPVRTC1_4_RGBA:
return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
// S3TC/DXT
case format_t::cTFBC1_RGB:
return GL_COMPRESSED_RGB_S3TC_DXT1_EXT;
case format_t::cTFBC3_RGBA:
return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
// ETC1
case format_t::cTFETC1_RGB:
return GL_ETC1_RGB8_OES;
default: // unknown?
[[fallthrough]];
// no compression.
case format_t::cTFRGBA32:
return 0;
}
}
constexpr uint32_t bytesPerBlock(GLenum format)
{
switch (format)
{
// 16 B (RGBA formats)
case GL_COMPRESSED_RGBA_ASTC_4x4_KHR: // ASTC
[[fallthrough]];
case GL_COMPRESSED_RGBA8_ETC2_EAC: // ETC2
[[fallthrough]];
case GL_COMPRESSED_RGBA_PVRTC_4BPPV2_IMG: // PVRTC2
[[fallthrough]];
case GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG: // PVRTC1 (RGBA)
[[fallthrough]];
case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: // BC3 (RGBA)
return 16;
// 8 B (RGB formats)
case GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG: // PVRTC1 (RGB)
[[fallthrough]];
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: // BC1
[[fallthrough]];
case GL_ETC1_RGB8_OES: // ETC1
return 8;
default:
return 0; // not a block format/unrecognized.
}
}
}
namespace sp {
Image Texture::loadUASTC(const P<ResourceStream>& stream, std::optional<glm::uvec2> threshold)
{
static std::unique_ptr<basist::etc1_global_selector_codebook> codebook;
if (!codebook)
{
basist::basisu_transcoder_init();
codebook = std::make_unique<basist::etc1_global_selector_codebook>(basist::g_global_selector_cb_size, basist::g_global_selector_cb);
}
basist::ktx2_transcoder transcoder(codebook.get());
auto data = stream->readAll();
if (transcoder.init(data.data(), static_cast<uint32_t>(data.size())))
{
if (transcoder.start_transcoding())
{
const glm::uvec2 source_size{ transcoder.get_width(), transcoder.get_height() };
const auto format = uastcLoadFormat(source_size, transcoder.get_has_alpha(), threshold);
std::vector<glm::u8vec4> pixels;
if (basist::basis_transcoder_format_is_uncompressed(format))
pixels.resize(transcoder.get_width() * transcoder.get_height());
else
{
auto block_size = basist::basis_get_bytes_per_block_or_pixel(format);
auto blocks_width = (transcoder.get_width() + 4 - 1) / 4;
auto blocks_height = (transcoder.get_height() + 4 - 1) / 4;
pixels.resize(blocks_width * blocks_height * block_size / 4);
}
if (transcoder.transcode_image_level(0, 0, 0, pixels.data(), static_cast<uint32_t>(pixels.size() * 4), format))
return Image(glm::ivec2{ static_cast<int32_t>(transcoder.get_width()), static_cast<int32_t>(transcoder.get_height()) }, std::move(pixels), basistFormatCast(format));
}
}
return {};
}
void BasicTexture::setRepeated(bool)
{
}
void BasicTexture::setSmooth(bool value)
{
smooth = value;
}
void BasicTexture::loadFromImage(Image&& image)
{
this->image = std::move(image);
}
void BasicTexture::bind()
{
if (handle == 0)
{
glGenTextures(1, &handle);
glBindTexture(GL_TEXTURE_2D, handle);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, smooth ? GL_LINEAR : GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, smooth ? GL_LINEAR : GL_NEAREST);
if (image.getFormat() != 0)
{
auto block_size = bytesPerBlock(image.getFormat());
auto blocks_width = (image.getSize().x + 4 - 1) / 4;
auto blocks_height = (image.getSize().y + 4 - 1) / 4;
const auto compressed_size = blocks_width * blocks_height * block_size;
glCompressedTexImage2D(GL_TEXTURE_2D, 0, image.getFormat(), image.getSize().x, image.getSize().y, 0, static_cast<GLsizei>(compressed_size), image.getPtr());
}
else
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.getSize().x, image.getSize().y, 0, GL_RGBA, GL_UNSIGNED_BYTE, image.getPtr());
}
image = {};
}
glBindTexture(GL_TEXTURE_2D, handle);
}
}
<commit_msg>Minor tweaks (mainly readability<commit_after>#include "graphics/texture.h"
#include "graphics/opengl.h"
#include <array>
#include <SDL_assert.h>
#include <transcoder/basisu_transcoder.h>
namespace {
// one block per 4x4(=16) pixels.
constexpr uint32_t pixels_per_block = 4 * 4;
constexpr uint32_t getBlockCount(const glm::uvec2& size)
{
return (size.x * size.y + pixels_per_block - 1) / pixels_per_block;
}
basist::transcoder_texture_format uastcLoadFormat(const glm::uvec2& size, bool has_alpha, const std::optional<glm::uvec2>& threshold)
{
using format_t = basist::transcoder_texture_format;
if (threshold.has_value())
{
// Do we want uncompressed (texture atlas)
auto dims = threshold.value();
if (size.x <= dims.x || size.y <= dims.y)
return format_t::cTFRGBA32;
}
// Use GPU capabilities, in order of preference.
// ASTC
if (GLAD_GL_KHR_texture_compression_astc_ldr)
return format_t::cTFASTC_4x4_RGBA; // No RGB variant.
// ETC2
if (SP_texture_compression_etc2)
return format_t::cTFETC2_RGBA;
// PVRTC2
if (GLAD_GL_IMG_texture_compression_pvrtc2)
return has_alpha ? format_t::cTFPVRTC2_4_RGBA : format_t::cTFPVRTC2_4_RGB;
// PVRTC1
if (GLAD_GL_IMG_texture_compression_pvrtc)
return has_alpha ? format_t::cTFPVRTC1_4_RGBA : format_t::cTFPVRTC1_4_RGB;
// S3TC/DXT.
if (GLAD_GL_EXT_texture_compression_s3tc)
return has_alpha ? format_t::cTFBC3_RGBA : format_t::cTFBC1_RGB;
// ETC1.
if (GLAD_GL_OES_compressed_ETC1_RGB8_texture && !has_alpha)
return format_t::cTFETC1_RGB;
return format_t::cTFRGBA32;
}
constexpr GLenum basistFormatCast(basist::transcoder_texture_format format)
{
// https://github.com/BinomialLLC/basis_universal/wiki/OpenGL-texture-format-enums-table
using format_t = basist::transcoder_texture_format;
switch (format)
{
// ASTC
case format_t::cTFASTC_4x4_RGBA:
return GL_COMPRESSED_RGBA_ASTC_4x4_KHR;
// ETC2 RGBA
case format_t::cTFETC2_RGBA:
return GL_COMPRESSED_RGBA8_ETC2_EAC;
// PVRTC2
case format_t::cTFPVRTC2_4_RGB:
[[fallthrough]];
case format_t::cTFPVRTC2_4_RGBA:
return GL_COMPRESSED_RGBA_PVRTC_4BPPV2_IMG;
// PVRTC1
case format_t::cTFPVRTC1_4_RGB:
return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
case format_t::cTFPVRTC1_4_RGBA:
return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
// S3TC/DXT
case format_t::cTFBC1_RGB:
return GL_COMPRESSED_RGB_S3TC_DXT1_EXT;
case format_t::cTFBC3_RGBA:
return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
// ETC1
case format_t::cTFETC1_RGB:
return GL_ETC1_RGB8_OES;
default: // unknown?
[[fallthrough]];
// no compression.
case format_t::cTFRGBA32:
return 0;
}
}
constexpr uint32_t bytesPerBlock(GLenum format)
{
switch (format)
{
// 16 B (RGBA formats)
case GL_COMPRESSED_RGBA_ASTC_4x4_KHR: // ASTC
[[fallthrough]];
case GL_COMPRESSED_RGBA8_ETC2_EAC: // ETC2
[[fallthrough]];
case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: // BC3 (RGBA)
return 16;
// 8 B (RGB formats)
case GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG: // PVRTC1
[[fallthrough]];
case GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG: // PVRTC1 (RGBA)
[[fallthrough]];
case GL_COMPRESSED_RGBA_PVRTC_4BPPV2_IMG: // PVRTC2
[[fallthrough]];
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: // BC1
[[fallthrough]];
case GL_ETC1_RGB8_OES: // ETC1
return 8;
default:
return 0; // not a block format/unrecognized.
}
}
}
namespace sp {
Image Texture::loadUASTC(const P<ResourceStream>& stream, std::optional<glm::uvec2> threshold)
{
static std::unique_ptr<basist::etc1_global_selector_codebook> codebook;
if (!codebook)
{
basist::basisu_transcoder_init();
codebook = std::make_unique<basist::etc1_global_selector_codebook>(basist::g_global_selector_cb_size, basist::g_global_selector_cb);
}
basist::ktx2_transcoder transcoder(codebook.get());
auto data = stream->readAll();
if (transcoder.init(data.data(), static_cast<uint32_t>(data.size())))
{
if (transcoder.start_transcoding())
{
const glm::uvec2 source_size{ transcoder.get_width(), transcoder.get_height() };
const auto format = uastcLoadFormat(source_size, transcoder.get_has_alpha(), threshold);
std::vector<glm::u8vec4> pixels;
if (basist::basis_transcoder_format_is_uncompressed(format))
pixels.resize(transcoder.get_width() * transcoder.get_height());
else
{
auto block_size = basist::basis_get_bytes_per_block_or_pixel(format);
// each item in the pixels array is 4B.
pixels.resize(getBlockCount(source_size) * bytesPerBlock(basistFormatCast(format)) / 4);
}
if (transcoder.transcode_image_level(0, 0, 0, pixels.data(), static_cast<uint32_t>(pixels.size() * 4), format))
return Image(glm::ivec2{ static_cast<int32_t>(transcoder.get_width()), static_cast<int32_t>(transcoder.get_height()) }, std::move(pixels), basistFormatCast(format));
}
}
return {};
}
void BasicTexture::setRepeated(bool)
{
}
void BasicTexture::setSmooth(bool value)
{
smooth = value;
}
void BasicTexture::loadFromImage(Image&& image)
{
this->image = std::move(image);
}
void BasicTexture::bind()
{
if (handle == 0)
{
glGenTextures(1, &handle);
glBindTexture(GL_TEXTURE_2D, handle);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, smooth ? GL_LINEAR : GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, smooth ? GL_LINEAR : GL_NEAREST);
if (image.getFormat() != 0)
{
const auto compressed_size = getBlockCount(image.getSize()) * bytesPerBlock(image.getFormat());
glCompressedTexImage2D(GL_TEXTURE_2D, 0, image.getFormat(), image.getSize().x, image.getSize().y, 0, static_cast<GLsizei>(compressed_size), image.getPtr());
}
else
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.getSize().x, image.getSize().y, 0, GL_RGBA, GL_UNSIGNED_BYTE, image.getPtr());
}
image = {};
}
glBindTexture(GL_TEXTURE_2D, handle);
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2019-2021 Baldur Karlsson
*
* 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 "amd_isa.h"
#include "common/common.h"
#include "common/formatting.h"
#include "core/plugins.h"
#include "official/RGA/Common/AmdDxGsaCompile.h"
#include "official/RGA/elf/elf32.h"
#include "amd_isa_devices.h"
#if ENABLED(RDOC_X64)
#define DLL_NAME "atidxx64.dll"
#else
#define DLL_NAME "atidxx32.dll"
#endif
namespace GCNISA
{
extern rdcstr pluginPath;
static HMODULE GetAMDModule()
{
// first try in the plugin locations
HMODULE module = LoadLibraryA(LocatePluginFile(GCNISA::pluginPath, DLL_NAME).c_str());
// if that failed then try checking for it just in the default search path
if(module == NULL)
module = LoadLibraryA(DLL_NAME);
return module;
}
HRESULT SafelyCompile(PfnAmdDxGsaCompileShader compileShader, AmdDxGsaCompileShaderInput &in,
AmdDxGsaCompileShaderOutput &out)
{
HRESULT ret = E_FAIL;
__try
{
ret = compileShader(&in, &out);
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
RDCLOG("Exception occurred while compiling shader for ISA");
out.pShaderBinary = NULL;
out.shaderBinarySize = 0;
}
return ret;
}
rdcstr DisassembleDXBC(const bytebuf &shaderBytes, const rdcstr &target)
{
HMODULE mod = GetAMDModule();
if(mod == NULL)
return "; Error loading " DLL_NAME R"(.
; Currently )" DLL_NAME R"( from AMD's driver package is required for GCN disassembly and it cannot be
; distributed with RenderDoc.
; To see instructions on how to download and configure it on your system, go to:
; https://github.com/baldurk/renderdoc/wiki/GCN-ISA)";
// if shaderBytes is empty we're testing support, so return empty string - indicating no error
// initialising
if(shaderBytes.empty() || target == "")
return "";
PfnAmdDxGsaCompileShader compileShader =
(PfnAmdDxGsaCompileShader)GetProcAddress(mod, "AmdDxGsaCompileShader");
PfnAmdDxGsaFreeCompiledShader freeShader =
(PfnAmdDxGsaFreeCompiledShader)GetProcAddress(mod, "AmdDxGsaFreeCompiledShader");
AmdDxGsaCompileShaderInput in = {};
AmdDxGsaCompileShaderOutput out = {};
AmdDxGsaCompileOption opts[1] = {};
in.inputType = GsaInputDxAsmBin;
in.numCompileOptions = 0;
in.pCompileOptions = opts;
for(int i = 0; i < asicCount; i++)
{
const asic &a = asicInfo[i];
if(target == a.name)
{
in.chipFamily = a.chipFamily;
in.chipRevision = a.chipRevision;
break;
}
}
bool amdil = false;
if(target == "AMDIL")
{
in.chipFamily = asicInfo[0].chipFamily;
in.chipRevision = asicInfo[0].chipRevision;
amdil = true;
}
if(in.chipFamily == 0)
return "; Invalid ISA Target specified";
// we do a little mini parse of the DXBC file, just enough to get the shader code out. This is
// because we're getting called from outside the D3D backend where the shader bytes are opaque.
const char *dxbcParseError = "; Failed to fetch D3D shader code from DXBC";
const byte *base = shaderBytes.data();
const uint32_t *end = (const uint32_t *)(base + shaderBytes.size());
const uint32_t *dxbc = (const uint32_t *)base;
if(*dxbc != MAKE_FOURCC('D', 'X', 'B', 'C'))
return dxbcParseError;
dxbc++; // fourcc
dxbc += 4; // hash
dxbc++; // unknown
dxbc++; // fileLength
if(dxbc >= end)
return dxbcParseError;
const uint32_t numChunks = *dxbc;
dxbc++;
rdcarray<uint32_t> chunkOffsets;
for(uint32_t i = 0; i < numChunks; i++)
{
if(dxbc >= end)
return dxbcParseError;
chunkOffsets.push_back(*dxbc);
dxbc++;
}
in.pShaderByteCode = NULL;
in.byteCodeLength = 0;
for(uint32_t offs : chunkOffsets)
{
dxbc = (const uint32_t *)(base + offs);
if(dxbc + 2 >= end)
return dxbcParseError;
if(*dxbc == MAKE_FOURCC('S', 'H', 'E', 'X') || *dxbc == MAKE_FOURCC('S', 'H', 'D', 'R'))
{
dxbc++;
in.byteCodeLength = *dxbc;
dxbc++;
in.pShaderByteCode = dxbc;
if(dxbc + (in.byteCodeLength / 4) > end)
return dxbcParseError;
break;
}
}
if(in.byteCodeLength == 0)
return dxbcParseError;
out.size = sizeof(out);
HRESULT hr = SafelyCompile(compileShader, in, out);
if(out.pShaderBinary == NULL || out.shaderBinarySize < 16)
{
RDCLOG("Failed to disassemble shader: %p/%zu (%s)", out.pShaderBinary, out.shaderBinarySize,
ToStr(hr).c_str());
return "; Failed to disassemble shader";
}
const uint8_t *elf = (const uint8_t *)out.pShaderBinary;
const Elf32_Ehdr *elfHeader = (const Elf32_Ehdr *)elf;
rdcstr ret;
// minimal code to extract data from ELF. We assume the ELF we got back is well-formed.
if(IS_ELF(*elfHeader) && elfHeader->e_ident[EI_CLASS] == ELFCLASS32)
{
const Elf32_Shdr *strtab =
(const Elf32_Shdr *)(elf + elfHeader->e_shoff + sizeof(Elf32_Shdr) * elfHeader->e_shstrndx);
const uint8_t *strtabData = elf + strtab->sh_offset;
const AmdDxGsaCompileStats *stats = NULL;
for(int section = 1; section < elfHeader->e_shnum; section++)
{
if(section == elfHeader->e_shstrndx)
continue;
const Elf32_Shdr *sectHeader =
(const Elf32_Shdr *)(elf + elfHeader->e_shoff + sizeof(Elf32_Shdr) * section);
const char *name = (const char *)(strtabData + sectHeader->sh_name);
const uint8_t *data = elf + sectHeader->sh_offset;
if(!strcmp(name, ".stats"))
{
stats = (const AmdDxGsaCompileStats *)data;
}
else if(amdil && !strcmp(name, ".amdil_disassembly"))
{
ret.insert(0, (const char *)data, (size_t)sectHeader->sh_size);
while(ret.back() == '\0')
ret.pop_back();
}
else if(!amdil && !strcmp(name, ".disassembly"))
{
ret.insert(0, (const char *)data, (size_t)sectHeader->sh_size);
while(ret.back() == '\0')
ret.pop_back();
}
}
if(stats && !amdil)
{
ret.insert(0, StringFormat::Fmt(
R"(; -------- Statistics ---------------------
; SGPRs: %u out of %u used
; VGPRs: %u out of %u used
; LDS: %u out of %u bytes used
; %u bytes scratch space used
; Instructions: %u ALU, %u Control Flow, %u TFETCH
)",
stats->numSgprsUsed, stats->availableSgprs, stats->numVgprsUsed,
stats->availableVgprs, stats->usedLdsBytes, stats->availableLdsBytes,
stats->usedScratchBytes, stats->numAluInst, stats->numControlFlowInst,
stats->numTfetchInst));
}
ret.insert(0, StringFormat::Fmt("; Disassembly for %s\n\n", target.c_str()));
}
else
{
ret = "; Invalid ELF file generated";
}
freeShader(out.pShaderBinary);
return ret;
}
};
<commit_msg>Add specific error when failing to disassemble DXIL shaders<commit_after>/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2019-2021 Baldur Karlsson
*
* 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 "amd_isa.h"
#include "common/common.h"
#include "common/formatting.h"
#include "core/plugins.h"
#include "official/RGA/Common/AmdDxGsaCompile.h"
#include "official/RGA/elf/elf32.h"
#include "amd_isa_devices.h"
#if ENABLED(RDOC_X64)
#define DLL_NAME "atidxx64.dll"
#else
#define DLL_NAME "atidxx32.dll"
#endif
namespace GCNISA
{
extern rdcstr pluginPath;
static HMODULE GetAMDModule()
{
// first try in the plugin locations
HMODULE module = LoadLibraryA(LocatePluginFile(GCNISA::pluginPath, DLL_NAME).c_str());
// if that failed then try checking for it just in the default search path
if(module == NULL)
module = LoadLibraryA(DLL_NAME);
return module;
}
HRESULT SafelyCompile(PfnAmdDxGsaCompileShader compileShader, AmdDxGsaCompileShaderInput &in,
AmdDxGsaCompileShaderOutput &out)
{
HRESULT ret = E_FAIL;
__try
{
ret = compileShader(&in, &out);
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
RDCLOG("Exception occurred while compiling shader for ISA");
out.pShaderBinary = NULL;
out.shaderBinarySize = 0;
}
return ret;
}
rdcstr DisassembleDXBC(const bytebuf &shaderBytes, const rdcstr &target)
{
HMODULE mod = GetAMDModule();
if(mod == NULL)
return "; Error loading " DLL_NAME R"(.
; Currently )" DLL_NAME R"( from AMD's driver package is required for GCN disassembly and it cannot be
; distributed with RenderDoc.
; To see instructions on how to download and configure it on your system, go to:
; https://github.com/baldurk/renderdoc/wiki/GCN-ISA)";
// if shaderBytes is empty we're testing support, so return empty string - indicating no error
// initialising
if(shaderBytes.empty() || target == "")
return "";
PfnAmdDxGsaCompileShader compileShader =
(PfnAmdDxGsaCompileShader)GetProcAddress(mod, "AmdDxGsaCompileShader");
PfnAmdDxGsaFreeCompiledShader freeShader =
(PfnAmdDxGsaFreeCompiledShader)GetProcAddress(mod, "AmdDxGsaFreeCompiledShader");
AmdDxGsaCompileShaderInput in = {};
AmdDxGsaCompileShaderOutput out = {};
AmdDxGsaCompileOption opts[1] = {};
in.inputType = GsaInputDxAsmBin;
in.numCompileOptions = 0;
in.pCompileOptions = opts;
for(int i = 0; i < asicCount; i++)
{
const asic &a = asicInfo[i];
if(target == a.name)
{
in.chipFamily = a.chipFamily;
in.chipRevision = a.chipRevision;
break;
}
}
bool amdil = false;
if(target == "AMDIL")
{
in.chipFamily = asicInfo[0].chipFamily;
in.chipRevision = asicInfo[0].chipRevision;
amdil = true;
}
if(in.chipFamily == 0)
return "; Invalid ISA Target specified";
// we do a little mini parse of the DXBC file, just enough to get the shader code out. This is
// because we're getting called from outside the D3D backend where the shader bytes are opaque.
const char *dxbcParseError =
"; Failed to fetch D3D shader code from shader module, invalid DXBC container";
const byte *base = shaderBytes.data();
const uint32_t *end = (const uint32_t *)(base + shaderBytes.size());
const uint32_t *dxbc = (const uint32_t *)base;
if(*dxbc != MAKE_FOURCC('D', 'X', 'B', 'C'))
return dxbcParseError;
dxbc++; // fourcc
dxbc += 4; // hash
dxbc++; // unknown
dxbc++; // fileLength
if(dxbc >= end)
return dxbcParseError;
const uint32_t numChunks = *dxbc;
dxbc++;
rdcarray<uint32_t> chunkOffsets;
for(uint32_t i = 0; i < numChunks; i++)
{
if(dxbc >= end)
return dxbcParseError;
chunkOffsets.push_back(*dxbc);
dxbc++;
}
in.pShaderByteCode = NULL;
in.byteCodeLength = 0;
bool dxil = false;
for(uint32_t offs : chunkOffsets)
{
dxbc = (const uint32_t *)(base + offs);
if(dxbc + 2 >= end)
return dxbcParseError;
if(*dxbc == MAKE_FOURCC('S', 'H', 'E', 'X') || *dxbc == MAKE_FOURCC('S', 'H', 'D', 'R'))
{
dxbc++;
in.byteCodeLength = *dxbc;
dxbc++;
in.pShaderByteCode = dxbc;
if(dxbc + (in.byteCodeLength / 4) > end)
return dxbcParseError;
break;
}
else if(*dxbc == MAKE_FOURCC('D', 'X', 'I', 'L') || *dxbc == MAKE_FOURCC('I', 'L', 'D', 'B'))
{
dxil = true;
}
}
if(in.byteCodeLength == 0)
{
if(dxil)
return "; Shader disassembly for DXIL shaders is not supported.";
return dxbcParseError;
}
out.size = sizeof(out);
HRESULT hr = SafelyCompile(compileShader, in, out);
if(out.pShaderBinary == NULL || out.shaderBinarySize < 16)
{
RDCLOG("Failed to disassemble shader: %p/%zu (%s)", out.pShaderBinary, out.shaderBinarySize,
ToStr(hr).c_str());
return "; Failed to disassemble shader";
}
const uint8_t *elf = (const uint8_t *)out.pShaderBinary;
const Elf32_Ehdr *elfHeader = (const Elf32_Ehdr *)elf;
rdcstr ret;
// minimal code to extract data from ELF. We assume the ELF we got back is well-formed.
if(IS_ELF(*elfHeader) && elfHeader->e_ident[EI_CLASS] == ELFCLASS32)
{
const Elf32_Shdr *strtab =
(const Elf32_Shdr *)(elf + elfHeader->e_shoff + sizeof(Elf32_Shdr) * elfHeader->e_shstrndx);
const uint8_t *strtabData = elf + strtab->sh_offset;
const AmdDxGsaCompileStats *stats = NULL;
for(int section = 1; section < elfHeader->e_shnum; section++)
{
if(section == elfHeader->e_shstrndx)
continue;
const Elf32_Shdr *sectHeader =
(const Elf32_Shdr *)(elf + elfHeader->e_shoff + sizeof(Elf32_Shdr) * section);
const char *name = (const char *)(strtabData + sectHeader->sh_name);
const uint8_t *data = elf + sectHeader->sh_offset;
if(!strcmp(name, ".stats"))
{
stats = (const AmdDxGsaCompileStats *)data;
}
else if(amdil && !strcmp(name, ".amdil_disassembly"))
{
ret.insert(0, (const char *)data, (size_t)sectHeader->sh_size);
while(ret.back() == '\0')
ret.pop_back();
}
else if(!amdil && !strcmp(name, ".disassembly"))
{
ret.insert(0, (const char *)data, (size_t)sectHeader->sh_size);
while(ret.back() == '\0')
ret.pop_back();
}
}
if(stats && !amdil)
{
ret.insert(0, StringFormat::Fmt(
R"(; -------- Statistics ---------------------
; SGPRs: %u out of %u used
; VGPRs: %u out of %u used
; LDS: %u out of %u bytes used
; %u bytes scratch space used
; Instructions: %u ALU, %u Control Flow, %u TFETCH
)",
stats->numSgprsUsed, stats->availableSgprs, stats->numVgprsUsed,
stats->availableVgprs, stats->usedLdsBytes, stats->availableLdsBytes,
stats->usedScratchBytes, stats->numAluInst, stats->numControlFlowInst,
stats->numTfetchInst));
}
ret.insert(0, StringFormat::Fmt("; Disassembly for %s\n\n", target.c_str()));
}
else
{
ret = "; Invalid ELF file generated";
}
freeShader(out.pShaderBinary);
return ret;
}
};
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include "core/crc.h"
#include "core/frameAllocator.h"
#include "core/util/str.h"
#include "core/strings/stringFunctions.h"
#include "platform/platformVolume.h"
#include "platformPOSIX/posixVolume.h"
#ifndef PATH_MAX
#include <sys/syslimits.h>
#endif
#ifndef NGROUPS_UMAX
#define NGROUPS_UMAX 32
#endif
//#define DEBUG_SPEW
extern bool ResolvePathCaseInsensitive(char* pathName, S32 pathNameSize, bool requiredAbsolute);
namespace Torque
{
namespace Posix
{
//-----------------------------------------------------------------------------
static String buildFileName(const String& prefix,const Path& path)
{
// Need to join the path (minus the root) with our
// internal path name.
String file = prefix;
file = Path::Join(file,'/',path.getPath());
file = Path::Join(file,'/',path.getFileName());
file = Path::Join(file,'.',path.getExtension());
return file;
}
/*
static bool isFile(const String& file)
{
struct stat info;
if (stat(file.c_str(),&info) == 0)
return S_ISREG(info.st_mode);
return false;
}
static bool isDirectory(const String& file)
{
struct stat info;
if (stat(file.c_str(),&info) == 0)
return S_ISDIR(info.st_mode);
return false;
}
*/
//-----------------------------------------------------------------------------
static uid_t _Uid; // Current user id
static int _GroupCount; // Number of groups in the table
static gid_t _Groups[NGROUPS_UMAX+1]; // Table of all the user groups
static void copyStatAttributes(const struct stat& info, FileNode::Attributes* attr)
{
// We need to user and group id's in order to determin file
// read-only access permission. This information is only retrieved
// once per execution.
if (!_Uid)
{
_Uid = getuid();
_GroupCount = getgroups(NGROUPS_UMAX,_Groups);
_Groups[_GroupCount++] = getegid();
}
// Fill in the return struct. The read-only flag is determined
// by comparing file user and group ownership.
attr->flags = 0;
if (S_ISDIR(info.st_mode))
attr->flags |= FileNode::Directory;
if (S_ISREG(info.st_mode))
attr->flags |= FileNode::File;
if (info.st_uid == _Uid)
{
if (!(info.st_mode & S_IWUSR))
attr->flags |= FileNode::ReadOnly;
}
else
{
S32 i = 0;
for (; i < _GroupCount; i++)
{
if (_Groups[i] == info.st_gid)
break;
}
if (i != _GroupCount)
{
if (!(info.st_mode & S_IWGRP))
attr->flags |= FileNode::ReadOnly;
}
else
{
if (!(info.st_mode & S_IWOTH))
attr->flags |= FileNode::ReadOnly;
}
}
attr->size = info.st_size;
attr->mtime = UnixTimeToTime(info.st_mtime);
attr->atime = UnixTimeToTime(info.st_atime);
}
//-----------------------------------------------------------------------------
PosixFileSystem::PosixFileSystem(String volume)
{
_volume = volume;
}
PosixFileSystem::~PosixFileSystem()
{
}
FileNodeRef PosixFileSystem::resolve(const Path& path)
{
String file = buildFileName(_volume,path);
struct stat info;
#ifdef TORQUE_POSIX_PATH_CASE_INSENSITIVE
// Resolve the case sensitive filepath
String::SizeType fileLength = file.length();
UTF8* caseSensitivePath = new UTF8[fileLength + 1];
dMemcpy(caseSensitivePath, file.c_str(), fileLength);
caseSensitivePath[fileLength] = 0x00;
ResolvePathCaseInsensitive(caseSensitivePath, fileLength, false);
String caseSensitiveFile(caseSensitivePath);
#else
String caseSensitiveFile = file;
#endif
FileNodeRef result = 0;
if (stat(caseSensitiveFile.c_str(),&info) == 0)
{
// Construct the appropriate object
if (S_ISREG(info.st_mode))
result = new PosixFile(path,caseSensitiveFile);
if (S_ISDIR(info.st_mode))
result = new PosixDirectory(path,caseSensitiveFile);
}
#ifdef TORQUE_POSIX_PATH_CASE_INSENSITIVE
delete[] caseSensitivePath;
#endif
return result;
}
FileNodeRef PosixFileSystem::create(const Path& path, FileNode::Mode mode)
{
// The file will be created on disk when it's opened.
if (mode & FileNode::File)
return new PosixFile(path,buildFileName(_volume,path));
// Default permissions are read/write/search/executate by everyone,
// though this will be modified by the current umask
if (mode & FileNode::Directory)
{
String file = buildFileName(_volume,path);
if (mkdir(file.c_str(),S_IRWXU | S_IRWXG | S_IRWXO))
return new PosixDirectory(path,file);
}
return 0;
}
bool PosixFileSystem::remove(const Path& path)
{
// Should probably check for outstanding files or directory objects.
String file = buildFileName(_volume,path);
struct stat info;
int error = stat(file.c_str(),&info);
if (error < 0)
return false;
if (S_ISDIR(info.st_mode))
return !rmdir(file);
return !unlink(file);
}
bool PosixFileSystem::rename(const Path& from,const Path& to)
{
String fa = buildFileName(_volume,from);
String fb = buildFileName(_volume,to);
if (!::rename(fa.c_str(),fb.c_str()))
return true;
return false;
}
Path PosixFileSystem::mapTo(const Path& path)
{
return buildFileName(_volume,path);
}
Path PosixFileSystem::mapFrom(const Path& path)
{
const String::SizeType volumePathLen = _volume.length();
String pathStr = path.getFullPath();
if ( _volume.compare( pathStr, volumePathLen, String::NoCase ))
return Path();
return pathStr.substr( volumePathLen, pathStr.length() - volumePathLen );
}
//-----------------------------------------------------------------------------
PosixFile::PosixFile(const Path& path,String name)
{
_path = path;
_name = name;
_status = Closed;
_handle = 0;
}
PosixFile::~PosixFile()
{
if (_handle)
close();
}
Path PosixFile::getName() const
{
return _path;
}
FileNode::NodeStatus PosixFile::getStatus() const
{
return _status;
}
bool PosixFile::getAttributes(Attributes* attr)
{
struct stat info;
int error = _handle? fstat(fileno(_handle),&info): stat(_name.c_str(),&info);
if (error < 0)
{
_updateStatus();
return false;
}
copyStatAttributes(info,attr);
attr->name = _path;
return true;
}
U32 PosixFile::calculateChecksum()
{
if (!open( Read ))
return 0;
U64 fileSize = getSize();
U32 bufSize = 1024 * 1024 * 4;
FrameTemp< U8 > buf( bufSize );
U32 crc = CRC::INITIAL_CRC_VALUE;
while( fileSize > 0 )
{
U32 bytesRead = getMin( fileSize, bufSize );
if( read( buf, bytesRead ) != bytesRead )
{
close();
return 0;
}
fileSize -= bytesRead;
crc = CRC::calculateCRC( buf, bytesRead, crc );
}
close();
return crc;
}
bool PosixFile::open(AccessMode mode)
{
close();
if (_name.isEmpty())
{
return _status;
}
#ifdef DEBUG_SPEW
Platform::outputDebugString( "[PosixFile] opening '%s'", _name.c_str() );
#endif
const char* fmode = "r";
switch (mode)
{
case Read: fmode = "r"; break;
case Write: fmode = "w"; break;
case ReadWrite:
{
fmode = "r+";
// Ensure the file exists.
FILE* temp = fopen( _name.c_str(), "a+" );
fclose( temp );
break;
}
case WriteAppend: fmode = "a"; break;
default: break;
}
if (!(_handle = fopen(_name.c_str(), fmode)))
{
_updateStatus();
return false;
}
_status = Open;
return true;
}
bool PosixFile::close()
{
if (_handle)
{
#ifdef DEBUG_SPEW
Platform::outputDebugString( "[PosixFile] closing '%s'", _name.c_str() );
#endif
fflush(_handle);
fclose(_handle);
_handle = 0;
}
_status = Closed;
return true;
}
U32 PosixFile::getPosition()
{
if (_status == Open || _status == EndOfFile)
return ftell(_handle);
return 0;
}
U32 PosixFile::setPosition(U32 delta, SeekMode mode)
{
if (_status != Open && _status != EndOfFile)
return 0;
S32 fmode = 0;
switch (mode)
{
case Begin: fmode = SEEK_SET; break;
case Current: fmode = SEEK_CUR; break;
case End: fmode = SEEK_END; break;
default: break;
}
if (fseek(_handle, delta, fmode))
{
_status = UnknownError;
return 0;
}
_status = Open;
return ftell(_handle);
}
U32 PosixFile::read(void* dst, U32 size)
{
if (_status != Open && _status != EndOfFile)
return 0;
U32 bytesRead = fread(dst, 1, size, _handle);
if (bytesRead != size)
{
if (feof(_handle))
_status = EndOfFile;
else
_updateStatus();
}
return bytesRead;
}
U32 PosixFile::write(const void* src, U32 size)
{
if ((_status != Open && _status != EndOfFile) || !size)
return 0;
U32 bytesWritten = fwrite(src, 1, size, _handle);
if (bytesWritten != size)
_updateStatus();
return bytesWritten;
}
void PosixFile::_updateStatus()
{
switch (errno)
{
case EACCES: _status = AccessDenied; break;
case ENOSPC: _status = FileSystemFull; break;
case ENOTDIR: _status = NoSuchFile; break;
case ENOENT: _status = NoSuchFile; break;
case EISDIR: _status = AccessDenied; break;
case EROFS: _status = AccessDenied; break;
default: _status = UnknownError; break;
}
}
//-----------------------------------------------------------------------------
PosixDirectory::PosixDirectory(const Path& path,String name)
{
_path = path;
_name = name;
_status = Closed;
_handle = 0;
}
PosixDirectory::~PosixDirectory()
{
if (_handle)
close();
}
Path PosixDirectory::getName() const
{
return _path;
}
bool PosixDirectory::open()
{
if ((_handle = opendir(_name)) == 0)
{
_updateStatus();
return false;
}
_status = Open;
return true;
}
bool PosixDirectory::close()
{
if (_handle)
{
closedir(_handle);
_handle = NULL;
return true;
}
return false;
}
bool PosixDirectory::read(Attributes* entry)
{
if (_status != Open)
return false;
struct dirent* de = readdir(_handle);
if (!de)
{
_status = EndOfFile;
return false;
}
// Skip "." and ".." entries
if (de->d_name[0] == '.' && (de->d_name[1] == '\0' ||
(de->d_name[1] == '.' && de->d_name[2] == '\0')))
return read(entry);
// The dirent structure doesn't actually return much beside
// the name, so we must call stat for more info.
struct stat info;
String file = _name + "/" + de->d_name;
int error = stat(file.c_str(),&info);
if (error < 0)
{
_updateStatus();
return false;
}
copyStatAttributes(info,entry);
entry->name = de->d_name;
return true;
}
U32 PosixDirectory::calculateChecksum()
{
// Return checksum of current entry
return 0;
}
bool PosixDirectory::getAttributes(Attributes* attr)
{
struct stat info;
if (stat(_name.c_str(),&info))
{
_updateStatus();
return false;
}
copyStatAttributes(info,attr);
attr->name = _path;
return true;
}
FileNode::NodeStatus PosixDirectory::getStatus() const
{
return _status;
}
void PosixDirectory::_updateStatus()
{
switch (errno)
{
case EACCES: _status = AccessDenied; break;
case ENOTDIR: _status = NoSuchFile; break;
case ENOENT: _status = NoSuchFile; break;
default: _status = UnknownError; break;
}
}
} // Namespace POSIX
} // Namespace Torque
//-----------------------------------------------------------------------------
#ifndef TORQUE_OS_MAC // Mac has its own native FS build on top of the POSIX one.
Torque::FS::FileSystemRef Platform::FS::createNativeFS( const String &volume )
{
return new Posix::PosixFileSystem( volume );
}
#endif
String Platform::FS::getAssetDir()
{
return Platform::getExecutablePath();
}
/// Function invoked by the kernel layer to install OS specific
/// file systems.
bool Platform::FS::InstallFileSystems()
{
Platform::FS::Mount( "/", Platform::FS::createNativeFS( String() ) );
// Setup the current working dir.
char buffer[PATH_MAX];
if (::getcwd(buffer,sizeof(buffer)))
{
// add trailing '/' if it isn't there
if (buffer[dStrlen(buffer) - 1] != '/')
dStrcat(buffer, "/", PATH_MAX);
Platform::FS::SetCwd(buffer);
}
// Mount the home directory
if (char* home = getenv("HOME"))
Platform::FS::Mount( "home", Platform::FS::createNativeFS(home) );
return true;
}
<commit_msg>* BugFix: Correct usage of mkdir in posixVolume.cpp to check for the expected successful return value.<commit_after>//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include "core/crc.h"
#include "core/frameAllocator.h"
#include "core/util/str.h"
#include "core/strings/stringFunctions.h"
#include "platform/platformVolume.h"
#include "platformPOSIX/posixVolume.h"
#ifndef PATH_MAX
#include <sys/syslimits.h>
#endif
#ifndef NGROUPS_UMAX
#define NGROUPS_UMAX 32
#endif
//#define DEBUG_SPEW
extern bool ResolvePathCaseInsensitive(char* pathName, S32 pathNameSize, bool requiredAbsolute);
namespace Torque
{
namespace Posix
{
//-----------------------------------------------------------------------------
static String buildFileName(const String& prefix,const Path& path)
{
// Need to join the path (minus the root) with our
// internal path name.
String file = prefix;
file = Path::Join(file,'/',path.getPath());
file = Path::Join(file,'/',path.getFileName());
file = Path::Join(file,'.',path.getExtension());
return file;
}
/*
static bool isFile(const String& file)
{
struct stat info;
if (stat(file.c_str(),&info) == 0)
return S_ISREG(info.st_mode);
return false;
}
static bool isDirectory(const String& file)
{
struct stat info;
if (stat(file.c_str(),&info) == 0)
return S_ISDIR(info.st_mode);
return false;
}
*/
//-----------------------------------------------------------------------------
static uid_t _Uid; // Current user id
static int _GroupCount; // Number of groups in the table
static gid_t _Groups[NGROUPS_UMAX+1]; // Table of all the user groups
static void copyStatAttributes(const struct stat& info, FileNode::Attributes* attr)
{
// We need to user and group id's in order to determin file
// read-only access permission. This information is only retrieved
// once per execution.
if (!_Uid)
{
_Uid = getuid();
_GroupCount = getgroups(NGROUPS_UMAX,_Groups);
_Groups[_GroupCount++] = getegid();
}
// Fill in the return struct. The read-only flag is determined
// by comparing file user and group ownership.
attr->flags = 0;
if (S_ISDIR(info.st_mode))
attr->flags |= FileNode::Directory;
if (S_ISREG(info.st_mode))
attr->flags |= FileNode::File;
if (info.st_uid == _Uid)
{
if (!(info.st_mode & S_IWUSR))
attr->flags |= FileNode::ReadOnly;
}
else
{
S32 i = 0;
for (; i < _GroupCount; i++)
{
if (_Groups[i] == info.st_gid)
break;
}
if (i != _GroupCount)
{
if (!(info.st_mode & S_IWGRP))
attr->flags |= FileNode::ReadOnly;
}
else
{
if (!(info.st_mode & S_IWOTH))
attr->flags |= FileNode::ReadOnly;
}
}
attr->size = info.st_size;
attr->mtime = UnixTimeToTime(info.st_mtime);
attr->atime = UnixTimeToTime(info.st_atime);
}
//-----------------------------------------------------------------------------
PosixFileSystem::PosixFileSystem(String volume)
{
_volume = volume;
}
PosixFileSystem::~PosixFileSystem()
{
}
FileNodeRef PosixFileSystem::resolve(const Path& path)
{
String file = buildFileName(_volume,path);
struct stat info;
#ifdef TORQUE_POSIX_PATH_CASE_INSENSITIVE
// Resolve the case sensitive filepath
String::SizeType fileLength = file.length();
UTF8* caseSensitivePath = new UTF8[fileLength + 1];
dMemcpy(caseSensitivePath, file.c_str(), fileLength);
caseSensitivePath[fileLength] = 0x00;
ResolvePathCaseInsensitive(caseSensitivePath, fileLength, false);
String caseSensitiveFile(caseSensitivePath);
#else
String caseSensitiveFile = file;
#endif
FileNodeRef result = 0;
if (stat(caseSensitiveFile.c_str(),&info) == 0)
{
// Construct the appropriate object
if (S_ISREG(info.st_mode))
result = new PosixFile(path,caseSensitiveFile);
if (S_ISDIR(info.st_mode))
result = new PosixDirectory(path,caseSensitiveFile);
}
#ifdef TORQUE_POSIX_PATH_CASE_INSENSITIVE
delete[] caseSensitivePath;
#endif
return result;
}
FileNodeRef PosixFileSystem::create(const Path& path, FileNode::Mode mode)
{
// The file will be created on disk when it's opened.
if (mode & FileNode::File)
return new PosixFile(path,buildFileName(_volume,path));
// Default permissions are read/write/search/executate by everyone,
// though this will be modified by the current umask
if (mode & FileNode::Directory)
{
String file = buildFileName(_volume,path);
if (mkdir(file.c_str(),S_IRWXU | S_IRWXG | S_IRWXO) == 0)
return new PosixDirectory(path,file);
}
return 0;
}
bool PosixFileSystem::remove(const Path& path)
{
// Should probably check for outstanding files or directory objects.
String file = buildFileName(_volume,path);
struct stat info;
int error = stat(file.c_str(),&info);
if (error < 0)
return false;
if (S_ISDIR(info.st_mode))
return !rmdir(file);
return !unlink(file);
}
bool PosixFileSystem::rename(const Path& from,const Path& to)
{
String fa = buildFileName(_volume,from);
String fb = buildFileName(_volume,to);
if (!::rename(fa.c_str(),fb.c_str()))
return true;
return false;
}
Path PosixFileSystem::mapTo(const Path& path)
{
return buildFileName(_volume,path);
}
Path PosixFileSystem::mapFrom(const Path& path)
{
const String::SizeType volumePathLen = _volume.length();
String pathStr = path.getFullPath();
if ( _volume.compare( pathStr, volumePathLen, String::NoCase ))
return Path();
return pathStr.substr( volumePathLen, pathStr.length() - volumePathLen );
}
//-----------------------------------------------------------------------------
PosixFile::PosixFile(const Path& path,String name)
{
_path = path;
_name = name;
_status = Closed;
_handle = 0;
}
PosixFile::~PosixFile()
{
if (_handle)
close();
}
Path PosixFile::getName() const
{
return _path;
}
FileNode::NodeStatus PosixFile::getStatus() const
{
return _status;
}
bool PosixFile::getAttributes(Attributes* attr)
{
struct stat info;
int error = _handle? fstat(fileno(_handle),&info): stat(_name.c_str(),&info);
if (error < 0)
{
_updateStatus();
return false;
}
copyStatAttributes(info,attr);
attr->name = _path;
return true;
}
U32 PosixFile::calculateChecksum()
{
if (!open( Read ))
return 0;
U64 fileSize = getSize();
U32 bufSize = 1024 * 1024 * 4;
FrameTemp< U8 > buf( bufSize );
U32 crc = CRC::INITIAL_CRC_VALUE;
while( fileSize > 0 )
{
U32 bytesRead = getMin( fileSize, bufSize );
if( read( buf, bytesRead ) != bytesRead )
{
close();
return 0;
}
fileSize -= bytesRead;
crc = CRC::calculateCRC( buf, bytesRead, crc );
}
close();
return crc;
}
bool PosixFile::open(AccessMode mode)
{
close();
if (_name.isEmpty())
{
return _status;
}
#ifdef DEBUG_SPEW
Platform::outputDebugString( "[PosixFile] opening '%s'", _name.c_str() );
#endif
const char* fmode = "r";
switch (mode)
{
case Read: fmode = "r"; break;
case Write: fmode = "w"; break;
case ReadWrite:
{
fmode = "r+";
// Ensure the file exists.
FILE* temp = fopen( _name.c_str(), "a+" );
fclose( temp );
break;
}
case WriteAppend: fmode = "a"; break;
default: break;
}
if (!(_handle = fopen(_name.c_str(), fmode)))
{
_updateStatus();
return false;
}
_status = Open;
return true;
}
bool PosixFile::close()
{
if (_handle)
{
#ifdef DEBUG_SPEW
Platform::outputDebugString( "[PosixFile] closing '%s'", _name.c_str() );
#endif
fflush(_handle);
fclose(_handle);
_handle = 0;
}
_status = Closed;
return true;
}
U32 PosixFile::getPosition()
{
if (_status == Open || _status == EndOfFile)
return ftell(_handle);
return 0;
}
U32 PosixFile::setPosition(U32 delta, SeekMode mode)
{
if (_status != Open && _status != EndOfFile)
return 0;
S32 fmode = 0;
switch (mode)
{
case Begin: fmode = SEEK_SET; break;
case Current: fmode = SEEK_CUR; break;
case End: fmode = SEEK_END; break;
default: break;
}
if (fseek(_handle, delta, fmode))
{
_status = UnknownError;
return 0;
}
_status = Open;
return ftell(_handle);
}
U32 PosixFile::read(void* dst, U32 size)
{
if (_status != Open && _status != EndOfFile)
return 0;
U32 bytesRead = fread(dst, 1, size, _handle);
if (bytesRead != size)
{
if (feof(_handle))
_status = EndOfFile;
else
_updateStatus();
}
return bytesRead;
}
U32 PosixFile::write(const void* src, U32 size)
{
if ((_status != Open && _status != EndOfFile) || !size)
return 0;
U32 bytesWritten = fwrite(src, 1, size, _handle);
if (bytesWritten != size)
_updateStatus();
return bytesWritten;
}
void PosixFile::_updateStatus()
{
switch (errno)
{
case EACCES: _status = AccessDenied; break;
case ENOSPC: _status = FileSystemFull; break;
case ENOTDIR: _status = NoSuchFile; break;
case ENOENT: _status = NoSuchFile; break;
case EISDIR: _status = AccessDenied; break;
case EROFS: _status = AccessDenied; break;
default: _status = UnknownError; break;
}
}
//-----------------------------------------------------------------------------
PosixDirectory::PosixDirectory(const Path& path,String name)
{
_path = path;
_name = name;
_status = Closed;
_handle = 0;
}
PosixDirectory::~PosixDirectory()
{
if (_handle)
close();
}
Path PosixDirectory::getName() const
{
return _path;
}
bool PosixDirectory::open()
{
if ((_handle = opendir(_name)) == 0)
{
_updateStatus();
return false;
}
_status = Open;
return true;
}
bool PosixDirectory::close()
{
if (_handle)
{
closedir(_handle);
_handle = NULL;
return true;
}
return false;
}
bool PosixDirectory::read(Attributes* entry)
{
if (_status != Open)
return false;
struct dirent* de = readdir(_handle);
if (!de)
{
_status = EndOfFile;
return false;
}
// Skip "." and ".." entries
if (de->d_name[0] == '.' && (de->d_name[1] == '\0' ||
(de->d_name[1] == '.' && de->d_name[2] == '\0')))
return read(entry);
// The dirent structure doesn't actually return much beside
// the name, so we must call stat for more info.
struct stat info;
String file = _name + "/" + de->d_name;
int error = stat(file.c_str(),&info);
if (error < 0)
{
_updateStatus();
return false;
}
copyStatAttributes(info,entry);
entry->name = de->d_name;
return true;
}
U32 PosixDirectory::calculateChecksum()
{
// Return checksum of current entry
return 0;
}
bool PosixDirectory::getAttributes(Attributes* attr)
{
struct stat info;
if (stat(_name.c_str(),&info))
{
_updateStatus();
return false;
}
copyStatAttributes(info,attr);
attr->name = _path;
return true;
}
FileNode::NodeStatus PosixDirectory::getStatus() const
{
return _status;
}
void PosixDirectory::_updateStatus()
{
switch (errno)
{
case EACCES: _status = AccessDenied; break;
case ENOTDIR: _status = NoSuchFile; break;
case ENOENT: _status = NoSuchFile; break;
default: _status = UnknownError; break;
}
}
} // Namespace POSIX
} // Namespace Torque
//-----------------------------------------------------------------------------
#ifndef TORQUE_OS_MAC // Mac has its own native FS build on top of the POSIX one.
Torque::FS::FileSystemRef Platform::FS::createNativeFS( const String &volume )
{
return new Posix::PosixFileSystem( volume );
}
#endif
String Platform::FS::getAssetDir()
{
return Platform::getExecutablePath();
}
/// Function invoked by the kernel layer to install OS specific
/// file systems.
bool Platform::FS::InstallFileSystems()
{
Platform::FS::Mount( "/", Platform::FS::createNativeFS( String() ) );
// Setup the current working dir.
char buffer[PATH_MAX];
if (::getcwd(buffer,sizeof(buffer)))
{
// add trailing '/' if it isn't there
if (buffer[dStrlen(buffer) - 1] != '/')
dStrcat(buffer, "/", PATH_MAX);
Platform::FS::SetCwd(buffer);
}
// Mount the home directory
if (char* home = getenv("HOME"))
Platform::FS::Mount( "home", Platform::FS::createNativeFS(home) );
return true;
}
<|endoftext|> |
<commit_before>
//Made by Tomás Roda Martins (t_martins)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdint.h>
#include <wiringPi.h>
#include <softPwm.h>
#include "I2Cdev.h"
#include "MPU6050.h"
#include "HMC5883L.h"
int B1 = 5;
int B2 = 6;
int A1 = 3;
int A2 = 4;
int LED = 2;
int16_t ax, ay, az;
int16_t gx, gy, gz;
int16_t cx, cy, cz;
MPU6050 accelgyro;
HMC5883L magnetom;
//setup
void setup (void)
{
if (geteuid () != 0)
{
fprintf (stderr, "TM Needs to be root to run!") ;
exit (0) ;
}
if (wiringPiSetup () == -1)
exit (1) ;
softPwmCreate (A1, 0 , 100) ;
softPwmCreate (A2, 0 , 100) ;
softPwmCreate (B1, 0 , 100) ;
softPwmCreate (B2, 0 , 100) ;
printf ("Setup ... ") ; fflush (stdout) ;
pinMode (LED, OUTPUT) ;
// initialize MPU6050 and HMC5883L.
printf("Initializing I2C devices...\n");
accelgyro.initialize();
accelgyro.setI2CMasterModeEnabled(0);
accelgyro.setI2CBypassEnabled(1);
magnetom.initialize();
// verify connection
printf("Testing device connections...\n");
printf(accelgyro.testConnection() ? "MPU6050 connection successful\n" : "MPU6050 connection failed\n");
printf(magnetom.testConnection() ? "HMC5883L connection successful\n" : "HMC5883L connection failed\n");
printf ("OK\n") ;
}
//
void read_sensor () {
// read raw accel/gyro measurements from device.
magnetom.getHeading(&cx, &cy, &cz);
accelgyro.getAcceleration(&ax, &ay, &az);
accelgyro.getRotation(&gx, &gy, &gz);
//accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
}
//Sets the speed of the motor.
//SA1/2 is the speed of motor A SB1/2 is the speed os motor B
void motor_speed (int SA1,int SA2,int SB1,int SB2){
softPwmWrite (A1,SA1) ;
softPwmWrite (A2,SA2) ;
softPwmWrite (B1,SB1) ;
softPwmWrite (B2,SB2) ;
}
//Main:
int main (void)
{
setup () ;
for(;;){
motor_speed(50,0,50,0);
read_sensor ();
printf ("Acell :\n"ax);
}
}
<commit_msg>Test1<commit_after>
//Made by Tomás Roda Martins (t_martins)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdint.h>
#include <wiringPi.h>
#include <softPwm.h>
#include "I2Cdev.h"
#include "MPU6050.h"
#include "HMC5883L.h"
int B1 = 5;
int B2 = 6;
int A1 = 3;
int A2 = 4;
int LED = 2;
int16_t ax, ay, az;
int16_t gx, gy, gz;
int16_t cx, cy, cz;
MPU6050 accelgyro;
HMC5883L magnetom;
//setup
void setup (void)
{
if (geteuid () != 0)
{
fprintf (stderr, "TM Needs to be root to run!") ;
exit (0) ;
}
if (wiringPiSetup () == -1)
exit (1) ;
softPwmCreate (A1, 0 , 100) ;
softPwmCreate (A2, 0 , 100) ;
softPwmCreate (B1, 0 , 100) ;
softPwmCreate (B2, 0 , 100) ;
printf ("Setup ... ") ; fflush (stdout) ;
pinMode (LED, OUTPUT) ;
// initialize MPU6050 and HMC5883L.
printf("Initializing I2C devices...\n");
accelgyro.initialize();
accelgyro.setI2CMasterModeEnabled(0);
accelgyro.setI2CBypassEnabled(1);
magnetom.initialize();
// verify connection
printf("Testing device connections...\n");
printf(accelgyro.testConnection() ? "MPU6050 connection successful\n" : "MPU6050 connection failed\n");
printf(magnetom.testConnection() ? "HMC5883L connection successful\n" : "HMC5883L connection failed\n");
printf ("OK\n") ;
}
//
void read_sensor () {
// read raw accel/gyro measurements from device.
magnetom.getHeading(&cx, &cy, &cz);
accelgyro.getAcceleration(&ax, &ay, &az);
accelgyro.getRotation(&gx, &gy, &gz);
//accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
}
//Sets the speed of the motor.
//SA1/2 is the speed of motor A SB1/2 is the speed os motor B
void motor_speed (int SA1,int SA2,int SB1,int SB2){
softPwmWrite (A1,SA1) ;
softPwmWrite (A2,SA2) ;
softPwmWrite (B1,SB1) ;
softPwmWrite (B2,SB2) ;
}
//Main:
int main (void)
{
setup () ;
for(;;){
motor_speed(50,10,50,10);
read_sensor ();
printf ("Data:%5hd %5hd %5hd %5hd %5hd %5hd %5hd %5hd %5hd\n",ax,ay,az,gx,gy,gz,cx,cy,cz);
}
}
<|endoftext|> |
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2017-2019 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <inviwo/core/properties/propertypresetmanager.h>
#include <inviwo/core/properties/property.h>
#include <inviwo/core/properties/compositeproperty.h>
#include <inviwo/core/metadata/containermetadata.h>
#include <inviwo/core/util/stdextensions.h>
#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/network/networklock.h>
#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/properties/propertyfactory.h>
#include <inviwo/core/metadata/metadatafactory.h>
namespace inviwo {
PropertyPresetManager::PropertyPresetManager(InviwoApplication* app) : app_{app} {
loadApplicationPresets();
}
bool PropertyPresetManager::loadPreset(const std::string& name, Property* property,
PropertyPresetType type) const {
auto apply = [this](Property* p, const std::string& data) {
NetworkLock lock(p);
std::stringstream ss;
ss << data;
auto d = app_->getWorkspaceManager()->createWorkspaceDeserializer(ss, "");
// We deserialize into a clone here and link it to the original to only set value not
// identifiers and such.
auto temp = std::unique_ptr<Property>(p->clone());
auto reset = scopedSerializationModeAll(temp);
temp->deserialize(d);
p->set(temp.get());
};
switch (type) {
case PropertyPresetType::Property: {
auto pmap = getPropertyPresets(property);
auto it = std::find_if(pmap.begin(), pmap.end(),
[&](const auto& pair) { return pair.first == name; });
if (it != pmap.end()) {
apply(property, it->second);
return true;
}
break;
}
case PropertyPresetType::Workspace: {
auto it = std::find_if(workspacePresets_.begin(), workspacePresets_.end(),
[&](const auto& item) { return item.name == name; });
if (it != workspacePresets_.end() &&
it->classIdentifier == property->getClassIdentifier()) {
apply(property, it->data);
return true;
}
break;
}
case PropertyPresetType::Application: {
auto it = std::find_if(appPresets_.begin(), appPresets_.end(),
[&](const auto& item) { return item.name == name; });
if (it != appPresets_.end() && it->classIdentifier == property->getClassIdentifier()) {
apply(property, it->data);
return true;
}
break;
}
default:
break;
}
return false;
}
void PropertyPresetManager::savePreset(const std::string& name, Property* property,
PropertyPresetType type) {
if (!property) return;
Serializer serializer("");
{
auto reset = scopedSerializationModeAll(property);
property->serialize(serializer);
}
std::stringstream ss;
serializer.writeFile(ss);
switch (type) {
case PropertyPresetType::Property: {
auto& pmap = getPropertyPresets(property);
pmap[name] = ss.str();
break;
}
case PropertyPresetType::Workspace: {
auto it = std::find_if(workspacePresets_.begin(), workspacePresets_.end(),
[&](const auto& item) { return item.name == name; });
if (it != workspacePresets_.end()) {
it->classIdentifier = property->getClassIdentifier();
it->data = ss.str();
} else {
workspacePresets_.emplace_back(property->getClassIdentifier(), name, ss.str());
}
break;
}
case PropertyPresetType::Application: {
auto it = std::find_if(appPresets_.begin(), appPresets_.end(),
[&](const auto& item) { return item.name == name; });
if (it != appPresets_.end()) {
it->classIdentifier = property->getClassIdentifier();
it->data = ss.str();
} else {
appPresets_.emplace_back(property->getClassIdentifier(), name, ss.str());
}
saveApplicationPresets();
break;
}
default:
break;
}
}
bool PropertyPresetManager::removePreset(const std::string& name, PropertyPresetType type,
Property* property) {
switch (type) {
case PropertyPresetType::Property: {
if (!property) return false;
auto& pmap = getPropertyPresets(property);
return pmap.erase(name) > 0;
}
case PropertyPresetType::Workspace: {
return util::erase_remove_if(workspacePresets_,
[&](const auto& item) { return item.name == name; }) > 0;
}
case PropertyPresetType::Application: {
auto removed = util::erase_remove_if(
appPresets_, [&](const auto& item) { return item.name == name; });
saveApplicationPresets();
return removed > 0;
}
default:
return false;
}
}
void PropertyPresetManager::appendPropertyPresets(Property* target, Property* source) {
auto& pmap = getPropertyPresets(target);
for (auto item : getPropertyPresets(source)) {
pmap[item.first] = item.second;
}
}
inviwo::util::OnScopeExit PropertyPresetManager::scopedSerializationModeAll(Property* property) {
std::vector<std::pair<Property*, PropertySerializationMode>> toReset;
std::function<void(Property*)> setPSM = [&](Property* p) {
if (p->getSerializationMode() != PropertySerializationMode::All) {
toReset.emplace_back(p, p->getSerializationMode());
p->setSerializationMode(PropertySerializationMode::All);
}
if (auto comp = dynamic_cast<CompositeProperty*>(p)) {
for (auto child : comp->getProperties()) {
setPSM(child);
}
}
};
setPSM(property);
return util::OnScopeExit{[toReset]() {
for (auto item : toReset) {
item.first->setSerializationMode(item.second);
}
}};
}
std::vector<std::string> PropertyPresetManager::getAvailablePresets(
Property* property, PropertyPresetTypes types) const {
std::vector<std::string> result;
if (types & PropertyPresetType::Property) {
auto pmap = getPropertyPresets(property);
std::transform(pmap.begin(), pmap.end(), std::back_inserter(result),
[&](const auto& pair) { return pair.first; });
}
if (types & PropertyPresetType::Workspace) {
for (auto& item : workspacePresets_) {
if (item.classIdentifier == property->getClassIdentifier()) {
result.push_back(item.name);
}
}
}
if (types & PropertyPresetType::Application) {
for (auto& item : appPresets_) {
if (item.classIdentifier == property->getClassIdentifier()) {
result.push_back(item.name);
}
}
}
return result;
}
void PropertyPresetManager::loadApplicationPresets() {
std::string filename = filesystem::getPath(PathType::Settings, "/PropertyPresets.ivs");
if (filesystem::fileExists(filename)) {
try {
Deserializer d(filename);
d.deserialize("PropertyPresets", appPresets_, "Preset");
} catch (AbortException& e) {
LogError(e.getMessage());
} catch (std::exception& e) {
LogError(e.what());
}
}
}
void PropertyPresetManager::saveApplicationPresets() {
try {
Serializer s(filesystem::getPath(PathType::Settings, "/PropertyPresets.ivs", true));
s.serialize("PropertyPresets", appPresets_, "Preset");
s.writeFile();
} catch (const std::exception& e) {
LogWarn("Could not write application presets: " << e.what());
}
}
void PropertyPresetManager::clearPropertyPresets(Property* property) {
if (!property) return;
auto& pmap = getPropertyPresets(property);
pmap.clear();
}
void PropertyPresetManager::clearWorkspacePresets() { workspacePresets_.clear(); }
void PropertyPresetManager::loadWorkspacePresets(Deserializer& d) {
workspacePresets_.clear();
d.deserialize("PropertyPresets", workspacePresets_, "Preset");
}
void PropertyPresetManager::saveWorkspacePresets(Serializer& s) {
s.serialize("PropertyPresets", workspacePresets_, "Preset");
}
PropertyPresetManager::Preset::Preset() = default;
PropertyPresetManager::Preset::Preset(std::string id, std::string n, std::string d)
: classIdentifier(id), name(n), data(d) {}
PropertyPresetManager::Preset::~Preset() = default;
void PropertyPresetManager::Preset::serialize(Serializer& s) const {
s.serialize("classIdentifier", classIdentifier);
s.serialize("name", name);
s.serialize("data", data);
}
void PropertyPresetManager::Preset::deserialize(Deserializer& d) {
d.deserialize("classIdentifier", classIdentifier);
d.deserialize("name", name);
d.deserialize("data", data);
}
std::map<std::string, std::string>& PropertyPresetManager::getPropertyPresets(Property* property) {
using MT = StdUnorderedMapMetaData<std::string, std::string>;
return property->createMetaData<MT>("SavedState")->getMap();
}
} // namespace inviwo
<commit_msg>Core: PropertyPresetType: Compile fix<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2017-2019 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <inviwo/core/properties/propertypresetmanager.h>
#include <inviwo/core/properties/property.h>
#include <inviwo/core/properties/compositeproperty.h>
#include <inviwo/core/metadata/containermetadata.h>
#include <inviwo/core/util/stdextensions.h>
#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/network/networklock.h>
#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/properties/propertyfactory.h>
#include <inviwo/core/metadata/metadatafactory.h>
namespace inviwo {
PropertyPresetManager::PropertyPresetManager(InviwoApplication* app) : app_{app} {
loadApplicationPresets();
}
bool PropertyPresetManager::loadPreset(const std::string& name, Property* property,
PropertyPresetType type) const {
auto apply = [this](Property* p, const std::string& data) {
NetworkLock lock(p);
std::stringstream ss;
ss << data;
auto d = app_->getWorkspaceManager()->createWorkspaceDeserializer(ss, "");
// We deserialize into a clone here and link it to the original to only set value not
// identifiers and such.
auto temp = std::unique_ptr<Property>(p->clone());
auto reset = scopedSerializationModeAll(temp.get());
temp->deserialize(d);
p->set(temp.get());
};
switch (type) {
case PropertyPresetType::Property: {
auto pmap = getPropertyPresets(property);
auto it = std::find_if(pmap.begin(), pmap.end(),
[&](const auto& pair) { return pair.first == name; });
if (it != pmap.end()) {
apply(property, it->second);
return true;
}
break;
}
case PropertyPresetType::Workspace: {
auto it = std::find_if(workspacePresets_.begin(), workspacePresets_.end(),
[&](const auto& item) { return item.name == name; });
if (it != workspacePresets_.end() &&
it->classIdentifier == property->getClassIdentifier()) {
apply(property, it->data);
return true;
}
break;
}
case PropertyPresetType::Application: {
auto it = std::find_if(appPresets_.begin(), appPresets_.end(),
[&](const auto& item) { return item.name == name; });
if (it != appPresets_.end() && it->classIdentifier == property->getClassIdentifier()) {
apply(property, it->data);
return true;
}
break;
}
default:
break;
}
return false;
}
void PropertyPresetManager::savePreset(const std::string& name, Property* property,
PropertyPresetType type) {
if (!property) return;
Serializer serializer("");
{
auto reset = scopedSerializationModeAll(property);
property->serialize(serializer);
}
std::stringstream ss;
serializer.writeFile(ss);
switch (type) {
case PropertyPresetType::Property: {
auto& pmap = getPropertyPresets(property);
pmap[name] = ss.str();
break;
}
case PropertyPresetType::Workspace: {
auto it = std::find_if(workspacePresets_.begin(), workspacePresets_.end(),
[&](const auto& item) { return item.name == name; });
if (it != workspacePresets_.end()) {
it->classIdentifier = property->getClassIdentifier();
it->data = ss.str();
} else {
workspacePresets_.emplace_back(property->getClassIdentifier(), name, ss.str());
}
break;
}
case PropertyPresetType::Application: {
auto it = std::find_if(appPresets_.begin(), appPresets_.end(),
[&](const auto& item) { return item.name == name; });
if (it != appPresets_.end()) {
it->classIdentifier = property->getClassIdentifier();
it->data = ss.str();
} else {
appPresets_.emplace_back(property->getClassIdentifier(), name, ss.str());
}
saveApplicationPresets();
break;
}
default:
break;
}
}
bool PropertyPresetManager::removePreset(const std::string& name, PropertyPresetType type,
Property* property) {
switch (type) {
case PropertyPresetType::Property: {
if (!property) return false;
auto& pmap = getPropertyPresets(property);
return pmap.erase(name) > 0;
}
case PropertyPresetType::Workspace: {
return util::erase_remove_if(workspacePresets_,
[&](const auto& item) { return item.name == name; }) > 0;
}
case PropertyPresetType::Application: {
auto removed = util::erase_remove_if(
appPresets_, [&](const auto& item) { return item.name == name; });
saveApplicationPresets();
return removed > 0;
}
default:
return false;
}
}
void PropertyPresetManager::appendPropertyPresets(Property* target, Property* source) {
auto& pmap = getPropertyPresets(target);
for (auto item : getPropertyPresets(source)) {
pmap[item.first] = item.second;
}
}
inviwo::util::OnScopeExit PropertyPresetManager::scopedSerializationModeAll(Property* property) {
std::vector<std::pair<Property*, PropertySerializationMode>> toReset;
std::function<void(Property*)> setPSM = [&](Property* p) {
if (p->getSerializationMode() != PropertySerializationMode::All) {
toReset.emplace_back(p, p->getSerializationMode());
p->setSerializationMode(PropertySerializationMode::All);
}
if (auto comp = dynamic_cast<CompositeProperty*>(p)) {
for (auto child : comp->getProperties()) {
setPSM(child);
}
}
};
setPSM(property);
return util::OnScopeExit{[toReset]() {
for (auto item : toReset) {
item.first->setSerializationMode(item.second);
}
}};
}
std::vector<std::string> PropertyPresetManager::getAvailablePresets(
Property* property, PropertyPresetTypes types) const {
std::vector<std::string> result;
if (types & PropertyPresetType::Property) {
auto pmap = getPropertyPresets(property);
std::transform(pmap.begin(), pmap.end(), std::back_inserter(result),
[&](const auto& pair) { return pair.first; });
}
if (types & PropertyPresetType::Workspace) {
for (auto& item : workspacePresets_) {
if (item.classIdentifier == property->getClassIdentifier()) {
result.push_back(item.name);
}
}
}
if (types & PropertyPresetType::Application) {
for (auto& item : appPresets_) {
if (item.classIdentifier == property->getClassIdentifier()) {
result.push_back(item.name);
}
}
}
return result;
}
void PropertyPresetManager::loadApplicationPresets() {
std::string filename = filesystem::getPath(PathType::Settings, "/PropertyPresets.ivs");
if (filesystem::fileExists(filename)) {
try {
Deserializer d(filename);
d.deserialize("PropertyPresets", appPresets_, "Preset");
} catch (AbortException& e) {
LogError(e.getMessage());
} catch (std::exception& e) {
LogError(e.what());
}
}
}
void PropertyPresetManager::saveApplicationPresets() {
try {
Serializer s(filesystem::getPath(PathType::Settings, "/PropertyPresets.ivs", true));
s.serialize("PropertyPresets", appPresets_, "Preset");
s.writeFile();
} catch (const std::exception& e) {
LogWarn("Could not write application presets: " << e.what());
}
}
void PropertyPresetManager::clearPropertyPresets(Property* property) {
if (!property) return;
auto& pmap = getPropertyPresets(property);
pmap.clear();
}
void PropertyPresetManager::clearWorkspacePresets() { workspacePresets_.clear(); }
void PropertyPresetManager::loadWorkspacePresets(Deserializer& d) {
workspacePresets_.clear();
d.deserialize("PropertyPresets", workspacePresets_, "Preset");
}
void PropertyPresetManager::saveWorkspacePresets(Serializer& s) {
s.serialize("PropertyPresets", workspacePresets_, "Preset");
}
PropertyPresetManager::Preset::Preset() = default;
PropertyPresetManager::Preset::Preset(std::string id, std::string n, std::string d)
: classIdentifier(id), name(n), data(d) {}
PropertyPresetManager::Preset::~Preset() = default;
void PropertyPresetManager::Preset::serialize(Serializer& s) const {
s.serialize("classIdentifier", classIdentifier);
s.serialize("name", name);
s.serialize("data", data);
}
void PropertyPresetManager::Preset::deserialize(Deserializer& d) {
d.deserialize("classIdentifier", classIdentifier);
d.deserialize("name", name);
d.deserialize("data", data);
}
std::map<std::string, std::string>& PropertyPresetManager::getPropertyPresets(Property* property) {
using MT = StdUnorderedMapMetaData<std::string, std::string>;
return property->createMetaData<MT>("SavedState")->getMap();
}
} // namespace inviwo
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebStorageNamespaceImpl.h"
#if ENABLE(DOM_STORAGE)
#include "SecurityOrigin.h"
#include "WebStorageAreaImpl.h"
#include "WebString.h"
namespace WebKit {
WebStorageNamespace* WebStorageNamespace::createLocalStorageNamespace(const WebString& path, unsigned quota)
{
return new WebStorageNamespaceImpl(WebCore::StorageNamespaceImpl::localStorageNamespace(path, quota));
}
WebStorageNamespace* WebStorageNamespace::createSessionStorageNamespace()
{
return new WebStorageNamespaceImpl(WebCore::StorageNamespaceImpl::sessionStorageNamespace());
}
WebStorageNamespaceImpl::WebStorageNamespaceImpl(PassRefPtr<WebCore::StorageNamespace> storageNamespace)
: m_storageNamespace(storageNamespace)
{
}
WebStorageNamespaceImpl::~WebStorageNamespaceImpl()
{
}
WebStorageArea* WebStorageNamespaceImpl::createStorageArea(const WebString& originString)
{
RefPtr<WebCore::SecurityOrigin> origin = WebCore::SecurityOrigin::createFromString(originString);
return new WebStorageAreaImpl(m_storageNamespace->storageArea(origin.get()));
}
WebStorageNamespace* WebStorageNamespaceImpl::copy()
{
return new WebStorageNamespaceImpl(m_storageNamespace->copy());
}
void WebStorageNamespaceImpl::close()
{
m_storageNamespace->close();
}
} // namespace WebKit
#endif // ENABLE(DOM_STORAGE)
<commit_msg>m_storageNamespace->storageArea takes a PassRefPtr not a pointer.<commit_after>/*
* Copyright (C) 2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebStorageNamespaceImpl.h"
#if ENABLE(DOM_STORAGE)
#include "SecurityOrigin.h"
#include "WebStorageAreaImpl.h"
#include "WebString.h"
namespace WebKit {
WebStorageNamespace* WebStorageNamespace::createLocalStorageNamespace(const WebString& path, unsigned quota)
{
return new WebStorageNamespaceImpl(WebCore::StorageNamespaceImpl::localStorageNamespace(path, quota));
}
WebStorageNamespace* WebStorageNamespace::createSessionStorageNamespace()
{
return new WebStorageNamespaceImpl(WebCore::StorageNamespaceImpl::sessionStorageNamespace());
}
WebStorageNamespaceImpl::WebStorageNamespaceImpl(PassRefPtr<WebCore::StorageNamespace> storageNamespace)
: m_storageNamespace(storageNamespace)
{
}
WebStorageNamespaceImpl::~WebStorageNamespaceImpl()
{
}
WebStorageArea* WebStorageNamespaceImpl::createStorageArea(const WebString& originString)
{
RefPtr<WebCore::SecurityOrigin> origin = WebCore::SecurityOrigin::createFromString(originString);
return new WebStorageAreaImpl(m_storageNamespace->storageArea(origin.release()));
}
WebStorageNamespace* WebStorageNamespaceImpl::copy()
{
return new WebStorageNamespaceImpl(m_storageNamespace->copy());
}
void WebStorageNamespaceImpl::close()
{
m_storageNamespace->close();
}
} // namespace WebKit
#endif // ENABLE(DOM_STORAGE)
<|endoftext|> |
<commit_before>#include "../utils/utils.hpp"
#include <cstdio>
#include <vector>
#include <string>
#include <cerrno>
#include <cstring>
#include <cmath>
#include <dirent.h>
#include <sys/utsname.h>
struct Domain {
std::string name, fmt;
};
const Domain doms[] = {
{ "tiles", "./tiles/15md_solver %s < %s" },
{ "pancake", "./pancake/50pancake_solver %s < %s" },
{ "gridnav", "./gridnav/gridnav_solver %s < %s" },
{ "plat2d", "./plat2d/plat2d_solver %s -lvl %s" },
};
struct Algorithm {
std::string name, cmd;
};
const Algorithm algs[] = {
{ "astar", "astar" },
{ "greedy", "greedy" },
{ "wastar", "wastar -wt 1" },
};
// Separate since it doesn't work well on all domains.
const Algorithm idastar = { "idastar", "idastar" };
enum {
Ndoms = sizeof(doms) / sizeof(doms[0]),
Nalgs = sizeof(algs) / sizeof(algs[0]),
};
// Result holds results from a run.
struct Result {
Result(void) : time(-1), len(0), nruns(0), stdev(-1) { }
double time; // time or mean time
unsigned int len; // solution length
unsigned int nruns; // only for saved benchmarks
double stdev; // only for saved benchmarks
};
char mname[256];
static bool bench(const Domain&, const Algorithm&);
static std::string instpath(const Domain&, const std::string&);
static std::string benchpath(const Domain&, const Algorithm&,const std::string&);
static bool chkbench(const Domain&, const Algorithm&, const std::string&);
static void mkbench(const Domain&, const Algorithm&, const std::string&);
static Result readresult(FILE*);
static void dfline(std::vector<const char *>&, void*);
static Result run(const Domain&, const Algorithm&, const std::string&);
int main() {
if (gethostname(mname, sizeof(mname)) == -1)
fatalx(errno, "failed to get the machine name");
printf("machine: %s\n", mname);
for (unsigned int i = 0; i < Ndoms; i++) {
printf("domain: %s\n", doms[i].name.c_str());
for (unsigned int j = 0; j < Nalgs; j++) {
printf("algorithm: %s\n", algs[j].name.c_str());
if (!bench(doms[i], algs[j]))
return 1;
}
if (doms[i].name == "tiles" || doms[i].name == "pancake") {
printf("algorithm: %s\n", idastar.name.c_str());
if (!bench(doms[i], idastar))
return 1;
}
}
return 0;
}
// bench benchmarks the given domain and algorithm,
// returning true if the benchmark matched previous
// results.
static bool bench(const Domain &dom, const Algorithm &alg) {
const std::string dir = "bench/insts/" + dom.name;
std::vector<std::string> insts = readdir(dir, false);
for (unsigned int i = 0; i < insts.size(); i++) {
std::string inst = insts[i];
printf("instance: %s (%s)\n", inst.c_str(),
benchpath(dom, alg, inst).c_str());
if (fileexists(benchpath(dom, alg, inst))) {
if (!chkbench(dom, alg, inst)) {
printf("failed\n");
return false;
}
} else {
mkbench(dom, alg, inst);
}
}
return true;
}
static std::string instpath(const Domain &dom, const std::string &inst) {
return "bench/insts/" + dom.name + "/" + inst;
}
static std::string benchpath(const Domain &dom, const Algorithm &alg,
const std::string &inst) {
return "bench/data/" + std::string(mname) + "_" +
dom.name + "_" + alg.name + "_" + inst;
}
// chkbench returns true if the current behavior is
// consistent with the benchmark.
static bool chkbench(const Domain &dom, const Algorithm &alg,
const std::string &inst) {
const std::string ipath = benchpath(dom, alg, inst);
FILE *f = fopen(ipath.c_str(), "r");
if (!f)
fatalx(errno, "failed to open %s for reading", ipath.c_str());
Result bench = readresult(f);
fclose(f);
// Must pass 1 of 3 runs within the limit
double lim = bench.time + bench.stdev * 2;
unsigned int ok = 0;
for (unsigned int i = 0; i < 3 && ok < 1; i++) {
Result r = run(dom, alg, inst);
if (r.len != bench.len) {
printf(" expected %u solution length\n", bench.len);
continue;
}
if (r.time > lim) {
printf(" expected ≤ %g seconds (mean: %gs)\n", lim, bench.time);
continue;
}
ok++;
}
return ok >= 1;
}
// mkbench makes a new benchmark file.
static void mkbench(const Domain &dom, const Algorithm &alg,
const std::string &inst) {
static const unsigned int N = 5;
const std::string opath = benchpath(dom, alg, inst);
printf(" making %s\n", opath.c_str());
printf(" warmup run: ");
run(dom, alg, inst);
Result r[N];
double meantime = 0;
for (unsigned int i = 0; i < N; i++) {
r[i] = run(dom, alg, inst);
meantime += r[i].time;
}
meantime /= N;
double vartime = 0;
for (unsigned int i = 1; i < N; i++) {
if (r[i].len != r[0].len)
fatal("different lengths when solving %s %s %s",
dom.name.c_str(), alg.name.c_str(), inst.c_str());
double diff = r[i].time - meantime;
vartime += diff * diff;
}
vartime /= N;
double stdev = sqrt(vartime);
printf(" %g avg. seconds, %g stdev\n", meantime, stdev);
ensuredir(opath);
FILE *o = fopen(opath.c_str(), "w");
if (!o)
fatalx(errno, "failed to open %s for writing", opath.c_str());
dfpair(o, "machine name", "%s", mname);
dfpair(o, "domain", "%s", dom.name.c_str());
dfpair(o, "algorithm", "%s", alg.name.c_str());
dfpair(o, "instance", "%s", inst.c_str());
dfpair(o, "num runs", "%u", (unsigned int) N);
dfpair(o, "mean wall time", "%g", meantime);
dfpair(o, "stdev wall time", "%g", stdev);
dfpair(o, "final sol length", "%u", (unsigned int) r[0].len);
fclose(o);
}
// readresult reads the datafile from the stream
// and returns the result data.
static Result readresult(FILE *f) {
Result res;
dfread(f, dfline, &res);
return res;
}
static void dfline(std::vector<const char *> &toks, void *_res) {
Result *res = static_cast<Result*>(_res);
if (strcmp(toks[1], "total wall time") == 0) {
res->time = strtod(toks[2], NULL);
} else if (strcmp(toks[1], "final sol length") == 0) {
res->len = strtol(toks[2], NULL, 10);
} else if (strcmp(toks[1], "mean wall time") == 0) {
res->time = strtod(toks[2], NULL);
} else if (strcmp(toks[1], "stdev wall time") == 0) {
res->stdev = strtod(toks[2], NULL);
} else if (strcmp(toks[1], "num runs") == 0) {
res->nruns = strtol(toks[2], NULL, 10);
}
}
// run runs the solver on the given instance using the
// given algorithm, returning the Result.
static Result run(const Domain &dom, const Algorithm &alg,
const std::string &inst) {
char cmd[1024];
const std::string ipath = instpath(dom, inst);
unsigned int res = snprintf(cmd, sizeof(cmd), dom.fmt.c_str(),
alg.cmd.c_str(), ipath.c_str());
if (res >= sizeof(cmd))
fatal("mark.cc run(): buffer is too small");
FILE *f = popen(cmd, "r");
if (!f)
fatal("failed to execute [%s]", cmd);
Result r = readresult(f);
pclose(f);
printf(" %u sol length, %g seconds\n", r.len, r.time);
return r;
}<commit_msg>bench: allow 1% over the mean. This seems to be less prone to false negatives than 2σ and less prone to false positives than 10%.<commit_after>#include "../utils/utils.hpp"
#include <cstdio>
#include <vector>
#include <string>
#include <cerrno>
#include <cstring>
#include <cmath>
#include <dirent.h>
#include <sys/utsname.h>
struct Domain {
std::string name, fmt;
};
const Domain doms[] = {
{ "tiles", "./tiles/15md_solver %s < %s" },
{ "pancake", "./pancake/50pancake_solver %s < %s" },
{ "gridnav", "./gridnav/gridnav_solver %s < %s" },
{ "plat2d", "./plat2d/plat2d_solver %s -lvl %s" },
};
struct Algorithm {
std::string name, cmd;
};
const Algorithm algs[] = {
{ "astar", "astar" },
{ "greedy", "greedy" },
{ "wastar", "wastar -wt 1" },
};
// Separate since it doesn't work well on all domains.
const Algorithm idastar = { "idastar", "idastar" };
enum {
Ndoms = sizeof(doms) / sizeof(doms[0]),
Nalgs = sizeof(algs) / sizeof(algs[0]),
};
// Result holds results from a run.
struct Result {
Result(void) : time(-1), len(0), nruns(0), stdev(-1) { }
double time; // time or mean time
unsigned int len; // solution length
unsigned int nruns; // only for saved benchmarks
double stdev; // only for saved benchmarks
};
char mname[256];
static bool bench(const Domain&, const Algorithm&);
static std::string instpath(const Domain&, const std::string&);
static std::string benchpath(const Domain&, const Algorithm&,const std::string&);
static bool chkbench(const Domain&, const Algorithm&, const std::string&);
static void mkbench(const Domain&, const Algorithm&, const std::string&);
static Result readresult(FILE*);
static void dfline(std::vector<const char *>&, void*);
static Result run(const Domain&, const Algorithm&, const std::string&);
int main() {
if (gethostname(mname, sizeof(mname)) == -1)
fatalx(errno, "failed to get the machine name");
printf("machine: %s\n", mname);
for (unsigned int i = 0; i < Ndoms; i++) {
printf("domain: %s\n", doms[i].name.c_str());
for (unsigned int j = 0; j < Nalgs; j++) {
printf("algorithm: %s\n", algs[j].name.c_str());
if (!bench(doms[i], algs[j]))
return 1;
}
if (doms[i].name == "tiles" || doms[i].name == "pancake") {
printf("algorithm: %s\n", idastar.name.c_str());
if (!bench(doms[i], idastar))
return 1;
}
}
return 0;
}
// bench benchmarks the given domain and algorithm,
// returning true if the benchmark matched previous
// results.
static bool bench(const Domain &dom, const Algorithm &alg) {
const std::string dir = "bench/insts/" + dom.name;
std::vector<std::string> insts = readdir(dir, false);
for (unsigned int i = 0; i < insts.size(); i++) {
std::string inst = insts[i];
printf("instance: %s (%s)\n", inst.c_str(),
benchpath(dom, alg, inst).c_str());
if (fileexists(benchpath(dom, alg, inst))) {
if (!chkbench(dom, alg, inst)) {
printf("failed\n");
return false;
}
} else {
mkbench(dom, alg, inst);
}
}
return true;
}
static std::string instpath(const Domain &dom, const std::string &inst) {
return "bench/insts/" + dom.name + "/" + inst;
}
static std::string benchpath(const Domain &dom, const Algorithm &alg,
const std::string &inst) {
return "bench/data/" + std::string(mname) + "_" +
dom.name + "_" + alg.name + "_" + inst;
}
// chkbench returns true if the current behavior is
// consistent with the benchmark.
static bool chkbench(const Domain &dom, const Algorithm &alg,
const std::string &inst) {
const std::string ipath = benchpath(dom, alg, inst);
FILE *f = fopen(ipath.c_str(), "r");
if (!f)
fatalx(errno, "failed to open %s for reading", ipath.c_str());
Result bench = readresult(f);
fclose(f);
// Must pass 1 of 3 runs within the limit
double lim = bench.time + bench.time * 1.01;
unsigned int ok = 0;
for (unsigned int i = 0; i < 3 && ok < 1; i++) {
Result r = run(dom, alg, inst);
if (r.len != bench.len) {
printf(" expected %u solution length\n", bench.len);
continue;
}
if (r.time > lim) {
printf(" expected ≤ %g seconds (mean: %gs)\n", lim, bench.time);
continue;
}
ok++;
}
return ok >= 1;
}
// mkbench makes a new benchmark file.
static void mkbench(const Domain &dom, const Algorithm &alg,
const std::string &inst) {
static const unsigned int N = 5;
const std::string opath = benchpath(dom, alg, inst);
printf(" making %s\n", opath.c_str());
printf(" warmup run: ");
run(dom, alg, inst);
Result r[N];
double meantime = 0;
for (unsigned int i = 0; i < N; i++) {
r[i] = run(dom, alg, inst);
meantime += r[i].time;
}
meantime /= N;
double vartime = 0;
for (unsigned int i = 1; i < N; i++) {
if (r[i].len != r[0].len)
fatal("different lengths when solving %s %s %s",
dom.name.c_str(), alg.name.c_str(), inst.c_str());
double diff = r[i].time - meantime;
vartime += diff * diff;
}
vartime /= N;
double stdev = sqrt(vartime);
printf(" %g avg. seconds, %g stdev\n", meantime, stdev);
ensuredir(opath);
FILE *o = fopen(opath.c_str(), "w");
if (!o)
fatalx(errno, "failed to open %s for writing", opath.c_str());
dfpair(o, "machine name", "%s", mname);
dfpair(o, "domain", "%s", dom.name.c_str());
dfpair(o, "algorithm", "%s", alg.name.c_str());
dfpair(o, "instance", "%s", inst.c_str());
dfpair(o, "num runs", "%u", (unsigned int) N);
dfpair(o, "mean wall time", "%g", meantime);
dfpair(o, "stdev wall time", "%g", stdev);
dfpair(o, "final sol length", "%u", (unsigned int) r[0].len);
fclose(o);
}
// readresult reads the datafile from the stream
// and returns the result data.
static Result readresult(FILE *f) {
Result res;
dfread(f, dfline, &res);
return res;
}
static void dfline(std::vector<const char *> &toks, void *_res) {
Result *res = static_cast<Result*>(_res);
if (strcmp(toks[1], "total wall time") == 0) {
res->time = strtod(toks[2], NULL);
} else if (strcmp(toks[1], "final sol length") == 0) {
res->len = strtol(toks[2], NULL, 10);
} else if (strcmp(toks[1], "mean wall time") == 0) {
res->time = strtod(toks[2], NULL);
} else if (strcmp(toks[1], "stdev wall time") == 0) {
res->stdev = strtod(toks[2], NULL);
} else if (strcmp(toks[1], "num runs") == 0) {
res->nruns = strtol(toks[2], NULL, 10);
}
}
// run runs the solver on the given instance using the
// given algorithm, returning the Result.
static Result run(const Domain &dom, const Algorithm &alg,
const std::string &inst) {
char cmd[1024];
const std::string ipath = instpath(dom, inst);
unsigned int res = snprintf(cmd, sizeof(cmd), dom.fmt.c_str(),
alg.cmd.c_str(), ipath.c_str());
if (res >= sizeof(cmd))
fatal("mark.cc run(): buffer is too small");
FILE *f = popen(cmd, "r");
if (!f)
fatal("failed to execute [%s]", cmd);
Result r = readresult(f);
pclose(f);
printf(" %u sol length, %g seconds\n", r.len, r.time);
return r;
}<|endoftext|> |
<commit_before>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <functional>
#include <random>
#include <string>
#include <vector>
#include "benchmark/benchmark.h"
#include "farmhash.h"
#include "farmhash-direct.h"
#include "n3980.h"
#include "n3980-farmhash.h"
#include "std.h"
template <class H>
static void BM_HashStrings(benchmark::State& state) {
static const int kTotalStringBytes = 1000 * 1000;
const int string_size = state.range_x();
const int num_strings = kTotalStringBytes / string_size;
std::vector<std::string> strings;
strings.reserve(num_strings);
std::default_random_engine rng;
std::uniform_int_distribution<char> dist;
for (int i = 0; i < num_strings; ++i) {
strings.push_back({});
strings.back().reserve(string_size);
for (int j = 0; j < string_size; ++j) {
strings.back().push_back(dist(rng));
}
}
int i = 0;
H h;
while (state.KeepRunning()) {
benchmark::DoNotOptimize(h(strings[i++ % strings.size()]));
}
state.SetBytesProcessed(static_cast<int64_t>(state.iterations()) *
string_size);
}
BENCHMARK_TEMPLATE(BM_HashStrings, std::hash<std::string>)
->Range(1, 1000 * 1000);
struct farmhash_string_direct {
size_t operator()(const std::string& s) {
return hashing::direct::farmhash::Hash64(s.data(), s.size());
}
};
BENCHMARK_TEMPLATE(BM_HashStrings, farmhash_string_direct)
->Range(1, 1000 * 1000);
BENCHMARK_TEMPLATE(BM_HashStrings, std::hasher<std::string, hashing::farmhash>)
->Range(1, 1000 * 1000);
BENCHMARK_TEMPLATE(BM_HashStrings, std::uhash<hashing::n3980::farmhash>)
->Range(1, 1000 * 1000);
BENCHMARK_MAIN();
<commit_msg>Generate random data once, rather than on each benchmark run.<commit_after>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <algorithm>
#include <array>
#include <functional>
#include <random>
#include <string>
#include <vector>
#include "benchmark/benchmark.h"
#include "farmhash.h"
#include "farmhash-direct.h"
#include "n3980.h"
#include "n3980-farmhash.h"
#include "std.h"
static const int kNumBytes = 10'000'000;
static const std::array<unsigned char, kNumBytes>& Bytes() {
static const std::array<unsigned char, kNumBytes> kBytes = [](){
std::array<unsigned char, kNumBytes> bytes;
std::independent_bits_engine<
std::default_random_engine, 8, unsigned char> engine;
std::generate(bytes.begin(), bytes.end(), engine);
return bytes;
}();
return kBytes;
}
struct string_piece {
string_piece(const unsigned char* begin, const unsigned char* end)
: begin(reinterpret_cast<const char*>(begin)),
end(reinterpret_cast<const char*>(end)) {}
const char* begin;
const char* end;
};
template <typename HashCode>
HashCode hash_decompose(HashCode code, string_piece str) {
return hash_combine(
hash_combine_range(std::move(code), str.begin, str.end),
str.end - str.begin);
}
template <typename HashAlgorithm>
void hash_append(HashAlgorithm& h, string_piece str) {
using std::hash_append;
h(str.begin, str.end - str.begin);
hash_append(h, str.end - str.begin);
}
struct farmhash_string_direct {
size_t operator()(string_piece s) {
return hashing::direct::farmhash::Hash64(s.begin, s.end - s.begin);
}
};
template <class H>
static void BM_HashStrings(benchmark::State& state) {
const std::array<unsigned char, kNumBytes>& bytes = Bytes();
const int string_size = state.range_x();
assert(string_size <= kNumBytes/10);
int i = 0;
H h;
while (state.KeepRunning()) {
benchmark::DoNotOptimize(h(string_piece{&bytes[i], &bytes[i+string_size]}));
i = (i + 1) % (kNumBytes - string_size);
}
state.SetBytesProcessed(static_cast<int64_t>(state.iterations()) *
string_size);
}
BENCHMARK_TEMPLATE(BM_HashStrings, farmhash_string_direct)
->Range(1, 1000 * 1000);
BENCHMARK_TEMPLATE(BM_HashStrings, std::hasher<string_piece, hashing::farmhash>)
->Range(1, 1000 * 1000);
BENCHMARK_TEMPLATE(BM_HashStrings, std::uhash<hashing::n3980::farmhash>)
->Range(1, 1000 * 1000);
BENCHMARK_MAIN();
<|endoftext|> |
<commit_before>// tileentry.cxx -- routines to handle a scenery tile
//
// Written by Curtis Olson, started May 1998.
//
// Copyright (C) 1998 - 2001 Curtis L. Olson - http://www.flightgear.org/~curt
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#ifdef HAVE_CONFIG_H
# include <simgear_config.h>
#endif
#include <simgear/compiler.h>
#include <string>
#include <sstream>
#include <istream>
#include <osg/LOD>
#include <osg/MatrixTransform>
#include <osg/Math>
#include <osg/NodeCallback>
#include <osgDB/FileNameUtils>
#include <osgDB/ReaderWriter>
#include <osgDB/ReadFile>
#include <osgDB/Registry>
#include <simgear/bucket/newbucket.hxx>
#include <simgear/debug/logstream.hxx>
#include <simgear/math/sg_geodesy.hxx>
#include <simgear/math/sg_random.h>
#include <simgear/misc/sgstream.hxx>
#include <simgear/scene/material/mat.hxx>
#include <simgear/scene/material/matlib.hxx>
#include <simgear/scene/model/ModelRegistry.hxx>
#include <simgear/scene/tgdb/apt_signs.hxx>
#include <simgear/scene/tgdb/obj.hxx>
#include <simgear/scene/util/OsgMath.hxx>
#include <simgear/scene/util/SGReaderWriterOptions.hxx>
#include "ReaderWriterSPT.hxx"
#include "ReaderWriterSTG.hxx"
#include "SGOceanTile.hxx"
#include "TileEntry.hxx"
using std::string;
using namespace simgear;
ModelLoadHelper *TileEntry::_modelLoader=0;
namespace {
osgDB::RegisterReaderWriterProxy<ReaderWriterSTG> g_readerWriterSTGProxy;
ModelRegistryCallbackProxy<LoadOnlyCallback> g_stgCallbackProxy("stg");
osgDB::RegisterReaderWriterProxy<ReaderWriterSPT> g_readerWriterSPTProxy;
ModelRegistryCallbackProxy<LoadOnlyCallback> g_sptCallbackProxy("spt");
}
// Constructor
TileEntry::TileEntry ( const SGBucket& b )
: tile_bucket( b ),
tileFileName(b.gen_index_str()),
_node( new osg::LOD ),
_priority(-FLT_MAX),
_current_view(false),
_time_expired(-1.0)
{
tileFileName += ".stg";
_node->setName(tileFileName);
// Give a default LOD range so that traversals that traverse
// active children (like the groundcache lookup) will work before
// tile manager has had a chance to update this node.
_node->setRange(0, 0.0, 10000.0);
}
TileEntry::TileEntry( const TileEntry& t )
: tile_bucket( t.tile_bucket ),
tileFileName(t.tileFileName),
_node( new osg::LOD ),
_priority(t._priority),
_current_view(t._current_view),
_time_expired(t._time_expired)
{
_node->setName(tileFileName);
// Give a default LOD range so that traversals that traverse
// active children (like the groundcache lookup) will work before
// tile manager has had a chance to update this node.
_node->setRange(0, 0.0, 10000.0);
}
// Destructor
TileEntry::~TileEntry ()
{
}
static void WorldCoordinate(osg::Matrix& obj_pos, double lat,
double lon, double elev, double hdg)
{
SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
obj_pos = makeZUpFrame(geod);
// hdg is not a compass heading, but a counter-clockwise rotation
// around the Z axis
obj_pos.preMult(osg::Matrix::rotate(hdg * SGD_DEGREES_TO_RADIANS,
0.0, 0.0, 1.0));
}
// Update the ssg transform node for this tile so it can be
// properly drawn relative to our (0,0,0) point
void TileEntry::prep_ssg_node(float vis) {
if (!is_loaded())
return;
// visibility can change from frame to frame so we update the
// range selector cutoff's each time.
float bounding_radius = _node->getChild(0)->getBound().radius();
_node->setRange( 0, 0, vis + bounding_radius );
}
bool TileEntry::obj_load(const string& path, osg::Group *geometry, bool is_base,
const osgDB::Options* options)
{
osg::Node* node = osgDB::readNodeFile(path, options);
if (node)
geometry->addChild(node);
return node != 0;
}
typedef enum {
OBJECT,
OBJECT_SHARED,
OBJECT_STATIC,
OBJECT_SIGN,
OBJECT_RUNWAY_SIGN
} object_type;
// storage class for deferred object processing in TileEntry::load()
struct Object {
Object(object_type t, const string& token, const SGPath& p,
std::istream& in)
: type(t), path(p)
{
in >> name;
if (type != OBJECT)
in >> lon >> lat >> elev >> hdg;
in >> ::skipeol;
if (type == OBJECT)
SG_LOG(SG_TERRAIN, SG_BULK, " " << token << " " << name);
else
SG_LOG(SG_TERRAIN, SG_BULK, " " << token << " " << name << " lon=" <<
lon << " lat=" << lat << " elev=" << elev << " hdg=" << hdg);
}
object_type type;
string name;
SGPath path;
double lon, lat, elev, hdg;
};
// Work in progress... load the tile based entirely by name cuz that's
// what we'll want to do with the database pager.
osg::Node*
TileEntry::loadTileByFileName(const string& fileName,
const osgDB::Options* options)
{
std::string index_str = osgDB::getNameLessExtension(fileName);
index_str = osgDB::getSimpleFileName(index_str);
long tileIndex;
{
std::istringstream idxStream(index_str);
idxStream >> tileIndex;
}
SGBucket tile_bucket(tileIndex);
const string basePath = tile_bucket.gen_base_path();
bool found_tile_base = false;
SGPath object_base;
vector<const Object*> objects;
SG_LOG( SG_TERRAIN, SG_INFO, "Loading tile " << index_str );
osgDB::FilePathList path_list=options->getDatabasePathList();
// Make sure we find the original filename here...
std::string filePath = osgDB::getFilePath(fileName);
if (!filePath.empty()) {
SGPath p(filePath);
p.append("..");
p.append("..");
path_list.push_front(p.str());
}
// scan and parse all files and store information
for (unsigned int i = 0; i < path_list.size(); i++) {
// If we found a terrain tile in Terrain/, we have to process the
// Objects/ dir in the same group, too, before we can stop scanning.
// FGGlobals::set_fg_scenery() inserts an empty string to path_list
// as marker.
if (path_list[i].empty()) {
if (found_tile_base)
break;
else
continue;
}
bool has_base = false;
SGPath tile_path = path_list[i];
tile_path.append(basePath);
SGPath basename = tile_path;
basename.append( index_str );
SG_LOG( SG_TERRAIN, SG_DEBUG, " Trying " << basename.str() );
// Check for master .stg (scene terra gear) file
SGPath stg_name = basename;
stg_name.concat( ".stg" );
sg_gzifstream in( stg_name.str() );
if ( !in.is_open() )
continue;
while ( ! in.eof() ) {
string token;
in >> token;
if ( token.empty() || token[0] == '#' ) {
in >> ::skipeol;
continue;
}
// Load only once (first found)
if ( token == "OBJECT_BASE" ) {
string name;
in >> name >> ::skipws;
SG_LOG( SG_TERRAIN, SG_BULK, " " << token << " " << name );
if (!found_tile_base) {
found_tile_base = true;
has_base = true;
object_base = tile_path;
object_base.append(name);
} else
SG_LOG(SG_TERRAIN, SG_BULK, " (skipped)");
// Load only if base is not in another file
} else if ( token == "OBJECT" ) {
if (!found_tile_base || has_base)
objects.push_back(new Object(OBJECT, token, tile_path, in));
else {
string name;
in >> name >> ::skipeol;
SG_LOG(SG_TERRAIN, SG_BULK, " " << token << " "
<< name << " (skipped)");
}
// Always OK to load
} else if ( token == "OBJECT_STATIC" ) {
objects.push_back(new Object(OBJECT_STATIC, token, tile_path, in));
} else if ( token == "OBJECT_SHARED" ) {
objects.push_back(new Object(OBJECT_SHARED, token, tile_path, in));
} else if ( token == "OBJECT_SIGN" ) {
objects.push_back(new Object(OBJECT_SIGN, token, tile_path, in));
} else if ( token == "OBJECT_RUNWAY_SIGN" ) {
objects.push_back(new Object(OBJECT_RUNWAY_SIGN, token, tile_path, in));
} else {
SG_LOG( SG_TERRAIN, SG_DEBUG,
"Unknown token '" << token << "' in " << stg_name.str() );
in >> ::skipws;
}
}
}
const SGReaderWriterOptions* btgOpt;
btgOpt = dynamic_cast<const SGReaderWriterOptions*>(options);
osg::ref_ptr<SGReaderWriterOptions> opt;
if (btgOpt)
opt = new SGReaderWriterOptions(*btgOpt);
else
opt = new SGReaderWriterOptions;
// obj_load() will generate ground lighting for us ...
osg::Group* new_tile = new osg::Group;
if (found_tile_base) {
// load tile if found ...
obj_load( object_base.str(), new_tile, true, opt.get());
} else {
// ... or generate an ocean tile on the fly
SG_LOG(SG_TERRAIN, SG_INFO, " Generating ocean tile");
osg::Node* node = SGOceanTile(tile_bucket, opt->getMaterialLib());
if ( node ) {
new_tile->addChild(node);
} else {
SG_LOG( SG_TERRAIN, SG_ALERT,
"Warning: failed to generate ocean tile!" );
}
}
// now that we have a valid center, process all the objects
for (unsigned int j = 0; j < objects.size(); j++) {
const Object *obj = objects[j];
if (obj->type == OBJECT) {
SGPath custom_path = obj->path;
custom_path.append( obj->name );
obj_load( custom_path.str(), new_tile, false, opt.get());
} else if (obj->type == OBJECT_SHARED || obj->type == OBJECT_STATIC) {
// object loading is deferred to main render thread,
// but lets figure out the paths right now.
SGPath custom_path;
if ( obj->type == OBJECT_STATIC ) {
custom_path = obj->path;
} else {
// custom_path = globals->get_fg_root();
}
custom_path.append( obj->name );
osg::Matrix obj_pos;
WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
obj_trans->setDataVariance(osg::Object::STATIC);
obj_trans->setMatrix( obj_pos );
// wire as much of the scene graph together as we can
new_tile->addChild( obj_trans );
osg::Node* model = 0;
if(_modelLoader)
model = _modelLoader->loadTileModel(custom_path.str(),
obj->type == OBJECT_SHARED);
if (model)
obj_trans->addChild(model);
} else if (obj->type == OBJECT_SIGN || obj->type == OBJECT_RUNWAY_SIGN) {
// load the object itself
SGPath custom_path = obj->path;
custom_path.append( obj->name );
osg::Matrix obj_pos;
WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
obj_trans->setDataVariance(osg::Object::STATIC);
obj_trans->setMatrix( obj_pos );
osg::Node *custom_obj = 0;
if (obj->type == OBJECT_SIGN)
custom_obj = SGMakeSign(opt->getMaterialLib(), custom_path.str(), obj->name);
else
custom_obj = SGMakeRunwaySign(opt->getMaterialLib(), custom_path.str(), obj->name);
// wire the pieces together
if ( custom_obj != NULL ) {
obj_trans -> addChild( custom_obj );
}
new_tile->addChild( obj_trans );
}
delete obj;
}
return new_tile;
}
void
TileEntry::addToSceneGraph(osg::Group *terrain_branch)
{
terrain_branch->addChild( _node.get() );
SG_LOG( SG_TERRAIN, SG_DEBUG,
"connected a tile into scene graph. _node = "
<< _node.get() );
SG_LOG( SG_TERRAIN, SG_DEBUG, "num parents now = "
<< _node->getNumParents() );
}
void
TileEntry::removeFromSceneGraph()
{
SG_LOG( SG_TERRAIN, SG_DEBUG, "disconnecting TileEntry nodes" );
if (! is_loaded()) {
SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a not-fully loaded tile!" );
} else {
SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a fully loaded tile! _node = " << _node.get() );
}
// find the nodes branch parent
if ( _node->getNumParents() > 0 ) {
// find the first parent (should only be one)
osg::Group *parent = _node->getParent( 0 ) ;
if( parent ) {
parent->removeChild( _node.get() );
}
}
}
void
TileEntry::refresh()
{
osg::Group *parent = NULL;
// find the nodes branch parent
if ( _node->getNumParents() > 0 ) {
// find the first parent (should only be one)
parent = _node->getParent( 0 ) ;
if( parent ) {
parent->removeChild( _node.get() );
}
}
_node = new osg::LOD;
if (parent)
parent->addChild(_node.get());
}
<commit_msg>Make use of SGReaderWriterOptions::copyOrCreate in ReaderWriterSTG.<commit_after>// tileentry.cxx -- routines to handle a scenery tile
//
// Written by Curtis Olson, started May 1998.
//
// Copyright (C) 1998 - 2001 Curtis L. Olson - http://www.flightgear.org/~curt
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#ifdef HAVE_CONFIG_H
# include <simgear_config.h>
#endif
#include <simgear/compiler.h>
#include <string>
#include <sstream>
#include <istream>
#include <osg/LOD>
#include <osg/MatrixTransform>
#include <osg/Math>
#include <osg/NodeCallback>
#include <osgDB/FileNameUtils>
#include <osgDB/ReaderWriter>
#include <osgDB/ReadFile>
#include <osgDB/Registry>
#include <simgear/bucket/newbucket.hxx>
#include <simgear/debug/logstream.hxx>
#include <simgear/math/sg_geodesy.hxx>
#include <simgear/math/sg_random.h>
#include <simgear/misc/sgstream.hxx>
#include <simgear/scene/material/mat.hxx>
#include <simgear/scene/material/matlib.hxx>
#include <simgear/scene/model/ModelRegistry.hxx>
#include <simgear/scene/tgdb/apt_signs.hxx>
#include <simgear/scene/tgdb/obj.hxx>
#include <simgear/scene/util/OsgMath.hxx>
#include <simgear/scene/util/SGReaderWriterOptions.hxx>
#include "ReaderWriterSPT.hxx"
#include "ReaderWriterSTG.hxx"
#include "SGOceanTile.hxx"
#include "TileEntry.hxx"
using std::string;
using namespace simgear;
ModelLoadHelper *TileEntry::_modelLoader=0;
namespace {
osgDB::RegisterReaderWriterProxy<ReaderWriterSTG> g_readerWriterSTGProxy;
ModelRegistryCallbackProxy<LoadOnlyCallback> g_stgCallbackProxy("stg");
osgDB::RegisterReaderWriterProxy<ReaderWriterSPT> g_readerWriterSPTProxy;
ModelRegistryCallbackProxy<LoadOnlyCallback> g_sptCallbackProxy("spt");
}
// Constructor
TileEntry::TileEntry ( const SGBucket& b )
: tile_bucket( b ),
tileFileName(b.gen_index_str()),
_node( new osg::LOD ),
_priority(-FLT_MAX),
_current_view(false),
_time_expired(-1.0)
{
tileFileName += ".stg";
_node->setName(tileFileName);
// Give a default LOD range so that traversals that traverse
// active children (like the groundcache lookup) will work before
// tile manager has had a chance to update this node.
_node->setRange(0, 0.0, 10000.0);
}
TileEntry::TileEntry( const TileEntry& t )
: tile_bucket( t.tile_bucket ),
tileFileName(t.tileFileName),
_node( new osg::LOD ),
_priority(t._priority),
_current_view(t._current_view),
_time_expired(t._time_expired)
{
_node->setName(tileFileName);
// Give a default LOD range so that traversals that traverse
// active children (like the groundcache lookup) will work before
// tile manager has had a chance to update this node.
_node->setRange(0, 0.0, 10000.0);
}
// Destructor
TileEntry::~TileEntry ()
{
}
static void WorldCoordinate(osg::Matrix& obj_pos, double lat,
double lon, double elev, double hdg)
{
SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
obj_pos = makeZUpFrame(geod);
// hdg is not a compass heading, but a counter-clockwise rotation
// around the Z axis
obj_pos.preMult(osg::Matrix::rotate(hdg * SGD_DEGREES_TO_RADIANS,
0.0, 0.0, 1.0));
}
// Update the ssg transform node for this tile so it can be
// properly drawn relative to our (0,0,0) point
void TileEntry::prep_ssg_node(float vis) {
if (!is_loaded())
return;
// visibility can change from frame to frame so we update the
// range selector cutoff's each time.
float bounding_radius = _node->getChild(0)->getBound().radius();
_node->setRange( 0, 0, vis + bounding_radius );
}
bool TileEntry::obj_load(const string& path, osg::Group *geometry, bool is_base,
const osgDB::Options* options)
{
osg::Node* node = osgDB::readNodeFile(path, options);
if (node)
geometry->addChild(node);
return node != 0;
}
typedef enum {
OBJECT,
OBJECT_SHARED,
OBJECT_STATIC,
OBJECT_SIGN,
OBJECT_RUNWAY_SIGN
} object_type;
// storage class for deferred object processing in TileEntry::load()
struct Object {
Object(object_type t, const string& token, const SGPath& p,
std::istream& in)
: type(t), path(p)
{
in >> name;
if (type != OBJECT)
in >> lon >> lat >> elev >> hdg;
in >> ::skipeol;
if (type == OBJECT)
SG_LOG(SG_TERRAIN, SG_BULK, " " << token << " " << name);
else
SG_LOG(SG_TERRAIN, SG_BULK, " " << token << " " << name << " lon=" <<
lon << " lat=" << lat << " elev=" << elev << " hdg=" << hdg);
}
object_type type;
string name;
SGPath path;
double lon, lat, elev, hdg;
};
// Work in progress... load the tile based entirely by name cuz that's
// what we'll want to do with the database pager.
osg::Node*
TileEntry::loadTileByFileName(const string& fileName,
const osgDB::Options* options)
{
std::string index_str = osgDB::getNameLessExtension(fileName);
index_str = osgDB::getSimpleFileName(index_str);
long tileIndex;
{
std::istringstream idxStream(index_str);
idxStream >> tileIndex;
}
SGBucket tile_bucket(tileIndex);
const string basePath = tile_bucket.gen_base_path();
bool found_tile_base = false;
SGPath object_base;
vector<const Object*> objects;
SG_LOG( SG_TERRAIN, SG_INFO, "Loading tile " << index_str );
osgDB::FilePathList path_list=options->getDatabasePathList();
// Make sure we find the original filename here...
std::string filePath = osgDB::getFilePath(fileName);
if (!filePath.empty()) {
SGPath p(filePath);
p.append("..");
p.append("..");
path_list.push_front(p.str());
}
// scan and parse all files and store information
for (unsigned int i = 0; i < path_list.size(); i++) {
// If we found a terrain tile in Terrain/, we have to process the
// Objects/ dir in the same group, too, before we can stop scanning.
// FGGlobals::set_fg_scenery() inserts an empty string to path_list
// as marker.
if (path_list[i].empty()) {
if (found_tile_base)
break;
else
continue;
}
bool has_base = false;
SGPath tile_path = path_list[i];
tile_path.append(basePath);
SGPath basename = tile_path;
basename.append( index_str );
SG_LOG( SG_TERRAIN, SG_DEBUG, " Trying " << basename.str() );
// Check for master .stg (scene terra gear) file
SGPath stg_name = basename;
stg_name.concat( ".stg" );
sg_gzifstream in( stg_name.str() );
if ( !in.is_open() )
continue;
while ( ! in.eof() ) {
string token;
in >> token;
if ( token.empty() || token[0] == '#' ) {
in >> ::skipeol;
continue;
}
// Load only once (first found)
if ( token == "OBJECT_BASE" ) {
string name;
in >> name >> ::skipws;
SG_LOG( SG_TERRAIN, SG_BULK, " " << token << " " << name );
if (!found_tile_base) {
found_tile_base = true;
has_base = true;
object_base = tile_path;
object_base.append(name);
} else
SG_LOG(SG_TERRAIN, SG_BULK, " (skipped)");
// Load only if base is not in another file
} else if ( token == "OBJECT" ) {
if (!found_tile_base || has_base)
objects.push_back(new Object(OBJECT, token, tile_path, in));
else {
string name;
in >> name >> ::skipeol;
SG_LOG(SG_TERRAIN, SG_BULK, " " << token << " "
<< name << " (skipped)");
}
// Always OK to load
} else if ( token == "OBJECT_STATIC" ) {
objects.push_back(new Object(OBJECT_STATIC, token, tile_path, in));
} else if ( token == "OBJECT_SHARED" ) {
objects.push_back(new Object(OBJECT_SHARED, token, tile_path, in));
} else if ( token == "OBJECT_SIGN" ) {
objects.push_back(new Object(OBJECT_SIGN, token, tile_path, in));
} else if ( token == "OBJECT_RUNWAY_SIGN" ) {
objects.push_back(new Object(OBJECT_RUNWAY_SIGN, token, tile_path, in));
} else {
SG_LOG( SG_TERRAIN, SG_DEBUG,
"Unknown token '" << token << "' in " << stg_name.str() );
in >> ::skipws;
}
}
}
osg::ref_ptr<SGReaderWriterOptions> opt;
opt = SGReaderWriterOptions::copyOrCreate(options);
// obj_load() will generate ground lighting for us ...
osg::Group* new_tile = new osg::Group;
if (found_tile_base) {
// load tile if found ...
obj_load( object_base.str(), new_tile, true, opt.get());
} else {
// ... or generate an ocean tile on the fly
SG_LOG(SG_TERRAIN, SG_INFO, " Generating ocean tile");
osg::Node* node = SGOceanTile(tile_bucket, opt->getMaterialLib());
if ( node ) {
new_tile->addChild(node);
} else {
SG_LOG( SG_TERRAIN, SG_ALERT,
"Warning: failed to generate ocean tile!" );
}
}
// now that we have a valid center, process all the objects
for (unsigned int j = 0; j < objects.size(); j++) {
const Object *obj = objects[j];
if (obj->type == OBJECT) {
SGPath custom_path = obj->path;
custom_path.append( obj->name );
obj_load( custom_path.str(), new_tile, false, opt.get());
} else if (obj->type == OBJECT_SHARED || obj->type == OBJECT_STATIC) {
// object loading is deferred to main render thread,
// but lets figure out the paths right now.
SGPath custom_path;
if ( obj->type == OBJECT_STATIC ) {
custom_path = obj->path;
} else {
// custom_path = globals->get_fg_root();
}
custom_path.append( obj->name );
osg::Matrix obj_pos;
WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
obj_trans->setDataVariance(osg::Object::STATIC);
obj_trans->setMatrix( obj_pos );
// wire as much of the scene graph together as we can
new_tile->addChild( obj_trans );
osg::Node* model = 0;
if(_modelLoader)
model = _modelLoader->loadTileModel(custom_path.str(),
obj->type == OBJECT_SHARED);
if (model)
obj_trans->addChild(model);
} else if (obj->type == OBJECT_SIGN || obj->type == OBJECT_RUNWAY_SIGN) {
// load the object itself
SGPath custom_path = obj->path;
custom_path.append( obj->name );
osg::Matrix obj_pos;
WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
obj_trans->setDataVariance(osg::Object::STATIC);
obj_trans->setMatrix( obj_pos );
osg::Node *custom_obj = 0;
if (obj->type == OBJECT_SIGN)
custom_obj = SGMakeSign(opt->getMaterialLib(), custom_path.str(), obj->name);
else
custom_obj = SGMakeRunwaySign(opt->getMaterialLib(), custom_path.str(), obj->name);
// wire the pieces together
if ( custom_obj != NULL ) {
obj_trans -> addChild( custom_obj );
}
new_tile->addChild( obj_trans );
}
delete obj;
}
return new_tile;
}
void
TileEntry::addToSceneGraph(osg::Group *terrain_branch)
{
terrain_branch->addChild( _node.get() );
SG_LOG( SG_TERRAIN, SG_DEBUG,
"connected a tile into scene graph. _node = "
<< _node.get() );
SG_LOG( SG_TERRAIN, SG_DEBUG, "num parents now = "
<< _node->getNumParents() );
}
void
TileEntry::removeFromSceneGraph()
{
SG_LOG( SG_TERRAIN, SG_DEBUG, "disconnecting TileEntry nodes" );
if (! is_loaded()) {
SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a not-fully loaded tile!" );
} else {
SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a fully loaded tile! _node = " << _node.get() );
}
// find the nodes branch parent
if ( _node->getNumParents() > 0 ) {
// find the first parent (should only be one)
osg::Group *parent = _node->getParent( 0 ) ;
if( parent ) {
parent->removeChild( _node.get() );
}
}
}
void
TileEntry::refresh()
{
osg::Group *parent = NULL;
// find the nodes branch parent
if ( _node->getNumParents() > 0 ) {
// find the first parent (should only be one)
parent = _node->getParent( 0 ) ;
if( parent ) {
parent->removeChild( _node.get() );
}
}
_node = new osg::LOD;
if (parent)
parent->addChild(_node.get());
}
<|endoftext|> |
<commit_before><commit_msg>Fix crash if null object supplied to PushWeakObject().<commit_after><|endoftext|> |
<commit_before>
#include "FunctionDeclHandler.h"
#include <regex>
namespace typegrind {
FunctionDeclHandler::FunctionDeclHandler(clang::Rewriter*& rewriter,
SpecializationHandler& specializationHandler,
MethodMatcher const& matchers)
: BaseExprHandler(rewriter, specializationHandler), mMatchers(matchers) {}
void FunctionDeclHandler::run(const clang::ast_matchers::MatchFinder::MatchResult& result) {
const clang::FunctionDecl* decl = result.Nodes.getNodeAs<clang::FunctionDecl>("decl");
if (!decl) return;
if (!decl->hasBody()) return;
if (decl->getTemplateSpecializationKind() == clang::TSK_ImplicitInstantiation) return;
std::string prettyName;
{
llvm::raw_string_ostream prettyNameStream(prettyName);
decl->getCanonicalDecl()->getNameForDiagnostic(
prettyNameStream, clang::PrintingPolicy(result.Context->getPrintingPolicy()), true);
prettyNameStream.flush();
}
auto match = mMatchers.matches(prettyName);
if (!match) {
// TODO: extract this to a policy class.
if (decl->isInlined() || decl->isInlineSpecified() ||
decl->hasTrivialBody()) return;
}
clang::Stmt* funcBody = decl->getBody();
auto insertPosition = funcBody->getSourceRange().getBegin();
if (!processingLocation(insertPosition)) return;
MacroAdder functionEnterMacro(
match ? "TYPEGRIND_LOG_FUNCTION_ENTER" : "TYPEGRIND_LOG_FUNCTION_AUTO_ENTER", insertPosition,
insertPosition, mRewriter);
functionEnterMacro.addParameterAsString(prettyName);
if (match) {
functionEnterMacro.addParameterAsString(match->custom_name);
functionEnterMacro.addParameter(std::to_string(match->flags));
}
functionEnterMacro.commitAfterStartLocation();
}
}
<commit_msg>formatting<commit_after>
#include "FunctionDeclHandler.h"
#include <regex>
namespace typegrind {
FunctionDeclHandler::FunctionDeclHandler(clang::Rewriter*& rewriter,
SpecializationHandler& specializationHandler,
MethodMatcher const& matchers)
: BaseExprHandler(rewriter, specializationHandler), mMatchers(matchers) {}
void FunctionDeclHandler::run(const clang::ast_matchers::MatchFinder::MatchResult& result) {
const clang::FunctionDecl* decl = result.Nodes.getNodeAs<clang::FunctionDecl>("decl");
if (!decl) return;
if (!decl->hasBody()) return;
if (decl->getTemplateSpecializationKind() == clang::TSK_ImplicitInstantiation) return;
std::string prettyName;
{
llvm::raw_string_ostream prettyNameStream(prettyName);
decl->getCanonicalDecl()->getNameForDiagnostic(
prettyNameStream, clang::PrintingPolicy(result.Context->getPrintingPolicy()), true);
prettyNameStream.flush();
}
auto match = mMatchers.matches(prettyName);
if (!match) {
// TODO: extract this to a policy class.
if (decl->isInlined() || decl->isInlineSpecified() || decl->hasTrivialBody()) return;
}
clang::Stmt* funcBody = decl->getBody();
auto insertPosition = funcBody->getSourceRange().getBegin();
if (!processingLocation(insertPosition)) return;
MacroAdder functionEnterMacro(
match ? "TYPEGRIND_LOG_FUNCTION_ENTER" : "TYPEGRIND_LOG_FUNCTION_AUTO_ENTER", insertPosition,
insertPosition, mRewriter);
functionEnterMacro.addParameterAsString(prettyName);
if (match) {
functionEnterMacro.addParameterAsString(match->custom_name);
functionEnterMacro.addParameter(std::to_string(match->flags));
}
functionEnterMacro.commitAfterStartLocation();
}
}
<|endoftext|> |
<commit_before>#ifndef INCLUDED_SROOK_ALGORITHM_FOREACH_HPP
#define INCLUDED_SROOK_ALGORITHM_FOREACH_HPP
#include<srook/config/require.hpp>
#include<srook/type_traits/has_iterator.hpp>
#include<srook/type_traits/is_callable.hpp>
#include<srook/iterator/range_iterator.hpp>
#include<type_traits>
#include<algorithm>
#include<tuple>
#include<initializer_list>
#include<iostream>
#define remove_ref_cv(x)\
std::remove_reference_t<std::remove_cv_t<x>>
namespace srook{
inline namespace v1{
template<
class Iterator,
class Functor,
REQUIRES(
!has_iterator_v<remove_ref_cv(Iterator)> and
is_callable_v<remove_ref_cv(Functor)>
)
>
auto for_each(Iterator&& first,Iterator&& last,Functor&& functor) -> decltype(std::forward<Iterator>(first))
{
std::for_each(std::forward<Iterator>(first),std::forward<Iterator>(last),std::forward<Functor>(functor));
return std::forward<Iterator>(first);
}
template<
class Range,
class Functor,
REQUIRES(
(has_iterator_v<remove_ref_cv(Range)> or is_range_iterator_v<remove_ref_cv(Range)>) and
is_callable_v<remove_ref_cv(Functor)>
)
>
auto for_each(Range&& r,Functor&& functor) -> decltype(std::forward<Range>(r))
{
std::for_each(std::begin(r),std::end(r),std::forward<Functor>(functor));
return std::forward<Range>(r);
}
namespace{
template<class Functor>
void tuple_for_eacher(Functor&&){}
template<class Functor,class Head,class... Tail,REQUIRES(is_callable_v<remove_ref_cv(Functor)>)>
void tuple_for_eacher(Functor&& functor,Head&& head,Tail&&... tail)
{
functor(std::forward<Head>(head));
tuple_for_eacher(std::forward<Functor>(functor),std::forward<Tail>(tail)...);
}
template<class... Ts,class Functor,std::size_t... I,REQUIRES(is_callable_v<remove_ref_cv(Functor)>)>
std::tuple<Ts...>& tuple_for_eacher(std::tuple<Ts...>& t,Functor&& functor,const std::index_sequence<I...>&&)
{
tuple_for_eacher(std::forward<Functor>(functor),std::get<I>(t)...);
return t;
}
template<class... Ts,class Functor,std::size_t... I,REQUIRES(is_callable_v<remove_ref_cv(Functor)>)>
const std::tuple<Ts...>& tuple_for_eacher(const std::tuple<Ts...>& t,Functor&& functor,const std::index_sequence<I...>&&)
{
tuple_for_eacher(std::forward<Functor>(functor),std::get<I>(t)...);
return t;
}
} // anonymouse namespace
template<
class Tuple,
class Functor,
REQUIRES(
is_callable_v<remove_ref_cv(Functor)>
and
!std::is_const<Tuple>::value
and
(std::tuple_size<std::remove_reference_t<Tuple>>::value or !std::tuple_size<std::remove_reference_t<Tuple>>::value)
)
>
auto for_each(Tuple&& t,Functor&& functor)
noexcept(noexcept(tuple_for_eacher(std::declval<decltype(static_cast<Tuple&&>(t))>(),std::declval<decltype(static_cast<Functor&&>(functor))>(),std::declval<std::make_index_sequence<std::tuple_size<std::decay_t<Tuple>>::value>>())))
-> decltype(tuple_for_eacher(std::forward<Tuple>(t),std::forward<Functor>(functor),std::make_index_sequence<std::tuple_size<std::decay_t<Tuple>>::value>()))
{
return tuple_for_eacher(std::forward<Tuple>(t),std::forward<Functor>(functor),std::make_index_sequence<std::tuple_size<std::decay_t<Tuple>>::value>());
}
template<
class... Ts,
class Functor,
REQUIRES(is_callable_v<remove_ref_cv(Functor)>)
>
auto for_each(const std::tuple<Ts...>& t,Functor&& functor)
noexcept(noexcept(tuple_for_eacher(t,std::declval<decltype(std::forward<Functor>(functor))>(),std::declval<std::make_index_sequence<std::tuple_size<std::tuple<Ts...>>::value>>())))
-> const std::tuple<Ts...>&
{
return tuple_for_eacher(t,std::forward<Functor>(functor),std::make_index_sequence<std::tuple_size<std::tuple<Ts...>>::value>());
}
namespace{
template<class Range>
struct lvalue_counter{
explicit constexpr lvalue_counter(Range& r,std::size_t value)
:r_(r),value_(std::move(value)){}
using reference_type=Range&;
protected:
reference_type r_;
std::size_t value_;
};
template<class Range>
struct rvalue_counter{
explicit constexpr rvalue_counter(Range&& r,std::size_t value)
:r_(std::move(r)),value_(std::move(value)){}
using reference_type=Range&&;
protected:
reference_type r_;
std::size_t value_;
};
template<class Range>
using select_ref=typename std::conditional<std::is_lvalue_reference<Range>::value,lvalue_counter<remove_ref_cv(Range)>,rvalue_counter<remove_ref_cv(Range)>>::type;
template<class Range>
struct counter:select_ref<Range>{
using select_ref<Range>::select_ref;
using iterator=typename remove_ref_cv(Range)::iterator;
using const_iterator=typename remove_ref_cv(Range)::const_iterator;
auto begin()const{return std::begin(this->r_);}
auto end()const{return std::end(this->r_);}
auto begin(){return std::begin(this->r_);}
auto end(){return std::end(this->r_);}
const_iterator cbegin()const{return this->r_.cbegin();}
const_iterator cend()const{return this->r_.cend();}
std::size_t& get_counter(){return this->value_;}
typename select_ref<Range>::reference_type operator*(){return static_cast<typename select_ref<Range>::reference_type>(this->r_);}
};
template<bool,class Tuple>
struct counter_tuple{
explicit constexpr counter_tuple(Tuple&& t,std::size_t value)
:t_(std::move(t)),value_(std::move(value)){}
Tuple&& operator*(){return std::move(t_);}
std::size_t& get_counter(){return value_;}
using reference_type=Tuple&&;
private:
reference_type t_;
std::size_t value_;
};
template<class Tuple>
struct counter_tuple<true,Tuple>{
explicit constexpr counter_tuple(Tuple& t,std::size_t value)
:t_(t),value_(std::move(value)){}
Tuple& operator*(){return t_;}
std::size_t& get_counter(){return value_;}
using reference_type=Tuple&;
private:
reference_type t_;
std::size_t value_;
};
template<class Iterator>
struct counter_iters{
explicit constexpr counter_iters(Iterator first,Iterator last,std::size_t value)
:first_(std::move(first)),last_(std::move(last)),value_(std::move(value)){}
using iterator=remove_ref_cv(Iterator);
using const_iterator=const iterator;
iterator begin()const{return first_;}
iterator end()const{return last_;}
iterator begin(){return first_;}
iterator end(){return last_;}
const_iterator cbegin()const{return first_;}
const_iterator cend()const{return last_;}
std::size_t& get_counter(){return value_;}
private:
Iterator first_,last_;
std::size_t value_;
};
template<class Functor>
void counting_for_eacher(std::size_t&,Functor&&){}
template<class Functor,class Head,class... Tail,REQUIRES(is_callable_v<remove_ref_cv(Functor)>)>
void counting_for_eacher(std::size_t& counter,Functor&& functor_,Head&& head,Tail&&... tail)
{
functor_(std::forward<Head>(head),counter);
counting_for_eacher(++counter,std::forward<Functor>(functor_),std::forward<Tail>(tail)...);
}
template<class Tuple,class Functor,std::size_t... I,REQUIRES(is_callable_v<remove_ref_cv(Functor)>)>
auto counting_for_eacher(Tuple&& t,std::size_t& counter,Functor&& functor,const std::index_sequence<I...>&&) -> decltype(std::forward<Tuple>(t))
{
counting_for_eacher(counter,std::forward<Functor>(functor),std::get<I>(t)...);
return std::forward<Tuple>(t);
}
} // anonymouse namespace
template<class Tuple,REQUIRES(std::conditional_t<std::get<0>(remove_ref_cv(Tuple)()),std::true_type,std::true_type>::value)>
constexpr auto make_counter(Tuple&& t,std::size_t value=0)
-> decltype(
counter_tuple<std::is_lvalue_reference<Tuple>::value,Tuple>(std::forward<Tuple>(t),std::move(value))
)
{
return counter_tuple<std::is_lvalue_reference<Tuple>::value,Tuple>(std::forward<Tuple>(t),std::move(value));
}
template<class Range,REQUIRES(has_iterator_v<remove_ref_cv(Range)> or is_range_iterator_v<remove_ref_cv(Range)>)>
constexpr auto make_counter(Range&& r,std::size_t value=0) -> counter<decltype(std::forward<Range>(r))>
{
return counter<decltype(std::forward<Range>(r))>(std::forward<Range>(r),std::move(value));
}
template<class T>
constexpr auto make_counter(const std::initializer_list<T>& init_list,std::size_t value=0) -> counter<const std::initializer_list<T>&>
{
return counter<const std::initializer_list<T>&>(init_list,std::move(value));
}
template<class Iterator,REQUIRES(not has_iterator_v<remove_ref_cv(Iterator)>)>
constexpr auto make_counter(Iterator&& first,Iterator&& last,std::size_t value=0) -> counter_iters<remove_ref_cv(Iterator)>
{
return counter_iters<Iterator>(std::forward<Iterator>(first),std::forward<Iterator>(last),std::move(value));
}
template<
bool b,
class Tuple,
class Functor,
REQUIRES(is_callable_v<remove_ref_cv(Functor)>)
>
constexpr auto for_each(counter_tuple<b,Tuple> t,Functor&& functor) -> typename counter_tuple<b,Tuple>::reference_type
{
return counting_for_eacher(std::forward<Tuple>(*t),t.get_counter(),std::forward<Functor>(functor),std::make_index_sequence<std::tuple_size<remove_ref_cv(Tuple)>::value>());
}
template<
class Range,
class Functor,
REQUIRES(
(has_iterator_v<remove_ref_cv(Range)> or is_range_iterator_v<remove_ref_cv(Range)>) and
is_callable_v<remove_ref_cv(Functor)>
)
>
auto for_each(counter<Range> cr,Functor&& functor) -> typename counter<Range>::reference_type
{
for(decltype(std::begin(cr)) iter=std::begin(cr); iter!=std::end(cr); ++iter){
functor(*iter,cr.get_counter());
++cr.get_counter();
}
return *cr;
}
template<
class Iterator,
class Functor,
REQUIRES(!has_iterator_v<remove_ref_cv(Iterator)> and is_callable_v<remove_ref_cv(Functor)>)
>
auto for_each(counter_iters<Iterator> cr,Functor&& functor) -> decltype(std::begin(cr))
{
for(typename counter_iters<Iterator>::iterator iter=std::begin(cr); iter!=std::end(cr); ++iter){
functor(*iter,cr.get_counter());
++cr.get_counter();
}
return std::begin(cr);
}
template<
class T,
class Functor,
REQUIRES(is_callable_v<remove_ref_cv(Functor)>)
>
auto for_each(std::initializer_list<T> init_list,Functor&& functor) -> decltype(std::begin(init_list))
{
return for_each(std::begin(init_list),std::end(init_list),std::forward<Functor>(functor));
}
} // inline namespace v1
} // namespace srook
#undef remove_cv_t
#endif
<commit_msg>配列への曖昧さを解決<commit_after>#ifndef INCLUDED_SROOK_ALGORITHM_FOREACH_HPP
#define INCLUDED_SROOK_ALGORITHM_FOREACH_HPP
#include<srook/config/require.hpp>
#include<srook/type_traits/has_iterator.hpp>
#include<srook/type_traits/is_callable.hpp>
#include<srook/iterator/range_iterator.hpp>
#include<type_traits>
#include<algorithm>
#include<tuple>
#include<initializer_list>
#include<iostream>
#define remove_ref_cv(x)\
std::remove_reference_t<std::remove_cv_t<x>>
namespace srook{
inline namespace v1{
template<
class Iterator,
class Functor,
REQUIRES(
!has_iterator_v<remove_ref_cv(Iterator)> and
is_callable_v<remove_ref_cv(Functor)>
)
>
auto for_each(Iterator&& first,Iterator&& last,Functor&& functor) -> decltype(std::forward<Iterator>(first))
{
std::for_each(std::forward<Iterator>(first),std::forward<Iterator>(last),std::forward<Functor>(functor));
return std::forward<Iterator>(first);
}
template<
class Range,
class Functor,
REQUIRES(
(has_iterator_v<remove_ref_cv(Range)> or is_range_iterator_v<remove_ref_cv(Range)>) and
is_callable_v<remove_ref_cv(Functor)>
)
>
auto for_each(Range&& r,Functor&& functor) -> decltype(std::forward<Range>(r))
{
std::for_each(std::begin(r),std::end(r),std::forward<Functor>(functor));
return std::forward<Range>(r);
}
namespace{
template<class Functor>
void tuple_for_eacher(Functor&&){}
template<class Functor,class Head,class... Tail,REQUIRES(is_callable_v<remove_ref_cv(Functor)>)>
void tuple_for_eacher(Functor&& functor,Head&& head,Tail&&... tail)
{
functor(std::forward<Head>(head));
tuple_for_eacher(std::forward<Functor>(functor),std::forward<Tail>(tail)...);
}
template<class... Ts,class Functor,std::size_t... I,REQUIRES(is_callable_v<remove_ref_cv(Functor)>)>
std::tuple<Ts...>& tuple_for_eacher(std::tuple<Ts...>& t,Functor&& functor,const std::index_sequence<I...>&&)
{
tuple_for_eacher(std::forward<Functor>(functor),std::get<I>(t)...);
return t;
}
template<class... Ts,class Functor,std::size_t... I,REQUIRES(is_callable_v<remove_ref_cv(Functor)>)>
const std::tuple<Ts...>& tuple_for_eacher(const std::tuple<Ts...>& t,Functor&& functor,const std::index_sequence<I...>&&)
{
tuple_for_eacher(std::forward<Functor>(functor),std::get<I>(t)...);
return t;
}
} // anonymouse namespace
template<
class Tuple,
class Functor,
REQUIRES(
is_callable_v<remove_ref_cv(Functor)>
and
!std::is_const<Tuple>::value
and
(std::tuple_size<std::remove_reference_t<Tuple>>::value or !std::tuple_size<std::remove_reference_t<Tuple>>::value)
)
>
auto for_each(Tuple&& t,Functor&& functor)
noexcept(noexcept(tuple_for_eacher(std::declval<decltype(static_cast<Tuple&&>(t))>(),std::declval<decltype(static_cast<Functor&&>(functor))>(),std::declval<std::make_index_sequence<std::tuple_size<std::decay_t<Tuple>>::value>>())))
-> decltype(tuple_for_eacher(std::forward<Tuple>(t),std::forward<Functor>(functor),std::make_index_sequence<std::tuple_size<std::decay_t<Tuple>>::value>()))
{
return tuple_for_eacher(std::forward<Tuple>(t),std::forward<Functor>(functor),std::make_index_sequence<std::tuple_size<std::decay_t<Tuple>>::value>());
}
template<
class... Ts,
class Functor,
REQUIRES(is_callable_v<remove_ref_cv(Functor)>)
>
auto for_each(const std::tuple<Ts...>& t,Functor&& functor)
noexcept(noexcept(tuple_for_eacher(t,std::declval<decltype(std::forward<Functor>(functor))>(),std::declval<std::make_index_sequence<std::tuple_size<std::tuple<Ts...>>::value>>())))
-> const std::tuple<Ts...>&
{
return tuple_for_eacher(t,std::forward<Functor>(functor),std::make_index_sequence<std::tuple_size<std::tuple<Ts...>>::value>());
}
namespace{
template<class Range>
struct lvalue_counter{
explicit constexpr lvalue_counter(Range& r,std::size_t value)
:r_(r),value_(std::move(value)){}
using reference_type=Range&;
protected:
reference_type r_;
std::size_t value_;
};
template<class Range>
struct rvalue_counter{
explicit constexpr rvalue_counter(Range&& r,std::size_t value)
:r_(std::move(r)),value_(std::move(value)){}
using reference_type=Range&&;
protected:
reference_type r_;
std::size_t value_;
};
template<class Range>
using select_ref=typename std::conditional<std::is_lvalue_reference<Range>::value,lvalue_counter<remove_ref_cv(Range)>,rvalue_counter<remove_ref_cv(Range)>>::type;
template<class Range>
struct counter:select_ref<Range>{
using select_ref<Range>::select_ref;
using iterator=typename remove_ref_cv(Range)::iterator;
using const_iterator=typename remove_ref_cv(Range)::const_iterator;
auto begin()const{return std::begin(this->r_);}
auto end()const{return std::end(this->r_);}
auto begin(){return std::begin(this->r_);}
auto end(){return std::end(this->r_);}
const_iterator cbegin()const{return this->r_.cbegin();}
const_iterator cend()const{return this->r_.cend();}
std::size_t& get_counter(){return this->value_;}
typename select_ref<Range>::reference_type operator*(){return static_cast<typename select_ref<Range>::reference_type>(this->r_);}
};
template<bool,class Tuple>
struct counter_tuple{
explicit constexpr counter_tuple(Tuple&& t,std::size_t value)
:t_(std::move(t)),value_(std::move(value)){}
Tuple&& operator*(){return std::move(t_);}
std::size_t& get_counter(){return value_;}
using reference_type=Tuple&&;
private:
reference_type t_;
std::size_t value_;
};
template<class Tuple>
struct counter_tuple<true,Tuple>{
explicit constexpr counter_tuple(Tuple& t,std::size_t value)
:t_(t),value_(std::move(value)){}
Tuple& operator*(){return t_;}
std::size_t& get_counter(){return value_;}
using reference_type=Tuple&;
private:
reference_type t_;
std::size_t value_;
};
template<class Iterator>
struct counter_iters{
explicit constexpr counter_iters(Iterator first,Iterator last,std::size_t value)
:first_(std::move(first)),last_(std::move(last)),value_(std::move(value)){}
using iterator=remove_ref_cv(Iterator);
using const_iterator=const iterator;
iterator begin()const{return first_;}
iterator end()const{return last_;}
iterator begin(){return first_;}
iterator end(){return last_;}
const_iterator cbegin()const{return first_;}
const_iterator cend()const{return last_;}
std::size_t& get_counter(){return value_;}
private:
Iterator first_,last_;
std::size_t value_;
};
template<class Functor>
void counting_for_eacher(std::size_t&,Functor&&){}
template<class Functor,class Head,class... Tail,REQUIRES(is_callable_v<remove_ref_cv(Functor)>)>
void counting_for_eacher(std::size_t& counter,Functor&& functor_,Head&& head,Tail&&... tail)
{
functor_(std::forward<Head>(head),counter);
counting_for_eacher(++counter,std::forward<Functor>(functor_),std::forward<Tail>(tail)...);
}
template<class Tuple,class Functor,std::size_t... I,REQUIRES(is_callable_v<remove_ref_cv(Functor)>)>
auto counting_for_eacher(Tuple&& t,std::size_t& counter,Functor&& functor,const std::index_sequence<I...>&&) -> decltype(std::forward<Tuple>(t))
{
counting_for_eacher(counter,std::forward<Functor>(functor),std::get<I>(t)...);
return std::forward<Tuple>(t);
}
} // anonymouse namespace
template<class T,std::size_t s>
constexpr auto make_counter(const std::array<T,s>& ar,std::size_t value=0)
-> counter<decltype(ar)>
{
return counter<decltype(ar)>(ar,std::move(value));
}
template<class T,std::size_t s>
constexpr auto make_counter(std::array<T,s>& ar,std::size_t value=0)
-> counter<decltype(ar)>
{
return counter<decltype(ar)>(ar,std::move(value));
}
template<class Tuple>
constexpr auto make_counter(Tuple&& t,std::size_t value=0)
-> std::enable_if_t<!has_iterator_v<remove_ref_cv(Tuple)> or !is_range_iterator_v<remove_ref_cv(Tuple)>,counter_tuple<std::is_lvalue_reference<Tuple>::value,Tuple>>
{
return counter_tuple<std::is_lvalue_reference<Tuple>::value,Tuple>(std::forward<Tuple>(t),std::move(value));
}
template<class Range,REQUIRES(has_iterator_v<remove_ref_cv(Range)> or is_range_iterator_v<remove_ref_cv(Range)>)>
constexpr auto make_counter(Range&& r,std::size_t value=0) -> counter<decltype(std::forward<Range>(r))>
{
return counter<decltype(std::forward<Range>(r))>(std::forward<Range>(r),std::move(value));
}
template<class T>
constexpr auto make_counter(const std::initializer_list<T>& init_list,std::size_t value=0) -> counter<const std::initializer_list<T>&>
{
return counter<const std::initializer_list<T>&>(init_list,std::move(value));
}
template<class Iterator,REQUIRES(not has_iterator_v<remove_ref_cv(Iterator)>)>
constexpr auto make_counter(Iterator&& first,Iterator&& last,std::size_t value=0) -> counter_iters<remove_ref_cv(Iterator)>
{
return counter_iters<Iterator>(std::forward<Iterator>(first),std::forward<Iterator>(last),std::move(value));
}
template<
bool b,
class Tuple,
class Functor,
REQUIRES(is_callable_v<remove_ref_cv(Functor)>)
>
constexpr auto for_each(counter_tuple<b,Tuple> t,Functor&& functor) -> typename counter_tuple<b,Tuple>::reference_type
{
return counting_for_eacher(std::forward<Tuple>(*t),t.get_counter(),std::forward<Functor>(functor),std::make_index_sequence<std::tuple_size<remove_ref_cv(Tuple)>::value>());
}
template<
class Range,
class Functor,
REQUIRES(
(has_iterator_v<remove_ref_cv(Range)> or is_range_iterator_v<remove_ref_cv(Range)>) and
is_callable_v<remove_ref_cv(Functor)>
)
>
auto for_each(counter<Range> cr,Functor&& functor) -> typename counter<Range>::reference_type
{
for(decltype(std::begin(cr)) iter=std::begin(cr); iter!=std::end(cr); ++iter){
functor(*iter,cr.get_counter());
++cr.get_counter();
}
return *cr;
}
template<
class Iterator,
class Functor,
REQUIRES(!has_iterator_v<remove_ref_cv(Iterator)> and is_callable_v<remove_ref_cv(Functor)>)
>
auto for_each(counter_iters<Iterator> cr,Functor&& functor) -> decltype(std::begin(cr))
{
for(typename counter_iters<Iterator>::iterator iter=std::begin(cr); iter!=std::end(cr); ++iter){
functor(*iter,cr.get_counter());
++cr.get_counter();
}
return std::begin(cr);
}
template<
class T,
class Functor,
REQUIRES(is_callable_v<remove_ref_cv(Functor)>)
>
auto for_each(std::initializer_list<T> init_list,Functor&& functor) -> decltype(std::begin(init_list))
{
return for_each(std::begin(init_list),std::end(init_list),std::forward<Functor>(functor));
}
} // inline namespace v1
} // namespace srook
#undef remove_cv_t
#endif
<|endoftext|> |
<commit_before>/*
* HTTP server implementation.
*
* istream implementation for the request body.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "http_server_internal.hxx"
#include "http_upgrade.hxx"
#include "http_util.hxx"
#include "pool.hxx"
#include "strmap.hxx"
#include "header_parser.hxx"
#include "istream-internal.h"
#include "istream_null.hxx"
#include "util/CharUtil.hxx"
#include <inline/poison.h>
#include <daemon/log.h>
#include <limits.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/socket.h>
/**
* @return false if the connection has been closed
*/
static bool
http_server_parse_request_line(struct http_server_connection *connection,
const char *line, size_t length)
{
assert(connection != nullptr);
assert(connection->request.read_state == http_server_connection::Request::START);
assert(connection->request.request == nullptr);
assert(!connection->response.pending_drained);
if (unlikely(length < 5)) {
connection->Error("malformed request line");
return false;
}
const char *eol = line + length;
http_method_t method = HTTP_METHOD_NULL;
switch (line[0]) {
case 'D':
if (likely(line[1] == 'E' && line[2] == 'L' && line[3] == 'E' &&
line[4] == 'T' && line[5] == 'E' && line[6] == ' ')) {
method = HTTP_METHOD_DELETE;
line += 7;
}
break;
case 'G':
if (likely(line[1] == 'E' && line[2] == 'T' && line[3] == ' ')) {
method = HTTP_METHOD_GET;
line += 4;
}
break;
case 'P':
if (likely(line[1] == 'O' && line[2] == 'S' && line[3] == 'T' &&
line[4] == ' ')) {
method = HTTP_METHOD_POST;
line += 5;
} else if (line[1] == 'U' && line[2] == 'T' && line[3] == ' ') {
method = HTTP_METHOD_PUT;
line += 4;
} else if (memcmp(line + 1, "ROPFIND ", 8) == 0) {
method = HTTP_METHOD_PROPFIND;
line += 9;
} else if (memcmp(line + 1, "ROPPATCH ", 9) == 0) {
method = HTTP_METHOD_PROPPATCH;
line += 10;
}
break;
case 'H':
if (likely(line[1] == 'E' && line[2] == 'A' && line[3] == 'D' &&
line[4] == ' ')) {
method = HTTP_METHOD_HEAD;
line += 5;
}
break;
case 'O':
if (memcmp(line + 1, "PTIONS ", 7) == 0) {
method = HTTP_METHOD_OPTIONS;
line += 8;
}
break;
case 'T':
if (memcmp(line + 1, "RACE ", 5) == 0) {
method = HTTP_METHOD_TRACE;
line += 6;
}
break;
case 'M':
if (memcmp(line + 1, "KCOL ", 5) == 0) {
method = HTTP_METHOD_MKCOL;
line += 6;
} else if (memcmp(line + 1, "OVE ", 4) == 0) {
method = HTTP_METHOD_MOVE;
line += 5;
}
break;
case 'C':
if (memcmp(line + 1, "OPY ", 4) == 0) {
method = HTTP_METHOD_COPY;
line += 5;
}
break;
case 'L':
if (memcmp(line + 1, "OCK ", 4) == 0) {
method = HTTP_METHOD_LOCK;
line += 5;
}
break;
case 'U':
if (memcmp(line + 1, "NLOCK ", 6) == 0) {
method = HTTP_METHOD_UNLOCK;
line += 7;
}
break;
}
if (method == HTTP_METHOD_NULL) {
/* invalid request method */
connection->Error("unrecognized request method");
return false;
}
const char *space = (const char *)memchr(line, ' ', eol - line);
if (unlikely(space == nullptr || space + 6 > line + length ||
memcmp(space + 1, "HTTP/", 5) != 0)) {
/* refuse HTTP 0.9 requests */
static const char msg[] =
"This server requires HTTP 1.1.";
ssize_t nbytes = connection->socket.Write(msg, sizeof(msg) - 1);
if (nbytes != WRITE_DESTROYED)
connection->Done();
return false;
}
connection->request.request = http_server_request_new(connection);
connection->request.request->method = method;
connection->request.request->uri = p_strndup(connection->request.request->pool, line, space - line);
connection->request.read_state = http_server_connection::Request::HEADERS;
connection->request.http_1_0 = space + 9 <= line + length &&
space[8] == '0' && space[7] == '.' && space[6] == '1';
return true;
}
/**
* @return false if the connection has been closed
*/
static bool
http_server_headers_finished(struct http_server_connection *connection)
{
struct http_server_request *request = connection->request.request;
/* disable the idle+headers timeout; the request body timeout will
be tracked by filtered_socket (auto-refreshing) */
evtimer_del(&connection->idle_timeout);
const char *value = request->headers->Get("expect");
connection->request.expect_100_continue = value != nullptr &&
strcmp(value, "100-continue") == 0;
connection->request.expect_failed = value != nullptr &&
strcmp(value, "100-continue") != 0;
value = request->headers->Get("connection");
/* we disable keep-alive support on ancient HTTP 1.0, because that
feature was not well-defined and led to problems with some
clients */
connection->keep_alive = !connection->request.http_1_0 &&
(value == nullptr || !http_list_contains_i(value, "close"));
const bool upgrade = !connection->request.http_1_0 && value != nullptr &&
http_is_upgrade(value);
value = request->headers->Get("transfer-encoding");
const struct timeval *read_timeout = &http_server_read_timeout;
off_t content_length = -1;
const bool chunked = value != nullptr && strcasecmp(value, "chunked") == 0;
if (!chunked) {
value = request->headers->Get("content-length");
if (upgrade) {
if (value != nullptr) {
connection->Error("cannot upgrade with Content-Length request header");
return false;
}
/* disable timeout */
read_timeout = nullptr;
/* forward incoming data as-is */
connection->keep_alive = false;
} else if (value == nullptr) {
/* no body at all */
request->body = nullptr;
connection->request.read_state = http_server_connection::Request::END;
return true;
} else {
char *endptr;
content_length = strtoul(value, &endptr, 10);
if (unlikely(*endptr != 0 || content_length < 0)) {
connection->Error("invalid Content-Length header in HTTP request");
return false;
}
if (content_length == 0) {
/* empty body */
request->body = istream_null_new(request->pool);
connection->request.read_state = http_server_connection::Request::END;
return true;
}
}
} else if (upgrade) {
connection->Error("cannot upgrade chunked request");
return false;
}
/* istream_deinit() used poison_noaccess() - make it writable now
for re-use */
poison_undefined(&connection->request_body_reader,
sizeof(connection->request_body_reader));
request->body =
&connection->request_body_reader.Init(http_server_request_stream,
*connection->pool,
*request->pool,
content_length, chunked);
connection->request.read_state = http_server_connection::Request::BODY;
/* for the response body, the filtered_socket class tracks
inactivity timeout */
connection->socket.ScheduleReadTimeout(false, read_timeout);
return true;
}
/**
* @return false if the connection has been closed
*/
static bool
http_server_handle_line(struct http_server_connection *connection,
const char *line, size_t length)
{
assert(connection->request.read_state == http_server_connection::Request::START ||
connection->request.read_state == http_server_connection::Request::HEADERS);
if (unlikely(connection->request.read_state == http_server_connection::Request::START)) {
assert(connection->request.request == nullptr);
return http_server_parse_request_line(connection, line, length);
} else if (likely(length > 0)) {
assert(connection->request.read_state == http_server_connection::Request::HEADERS);
assert(connection->request.request != nullptr);
header_parse_line(connection->request.request->pool,
connection->request.request->headers,
line, length);
return true;
} else {
assert(connection->request.read_state == http_server_connection::Request::HEADERS);
assert(connection->request.request != nullptr);
return http_server_headers_finished(connection);
}
}
static BufferedResult
http_server_feed_headers(struct http_server_connection *connection,
const void *_data, size_t length)
{
assert(connection->request.read_state == http_server_connection::Request::START ||
connection->request.read_state == http_server_connection::Request::HEADERS);
if (connection->request.bytes_received >= 64 * 1024) {
daemon_log(2, "http_server: too many request headers\n");
http_server_connection_close(connection);
return BufferedResult::CLOSED;
}
const char *const buffer = (const char *)_data;
const char *const buffer_end = buffer + length;
const char *start = buffer, *end, *next = nullptr;
while ((end = (const char *)memchr(start, '\n',
buffer_end - start)) != nullptr) {
next = end + 1;
--end;
while (end >= start && IsWhitespaceOrNull(*end))
--end;
if (!http_server_handle_line(connection, start, end - start + 1))
return BufferedResult::CLOSED;
if (connection->request.read_state != http_server_connection::Request::HEADERS)
break;
start = next;
}
size_t consumed = 0;
if (next != nullptr) {
consumed = next - buffer;
connection->request.bytes_received += consumed;
connection->socket.Consumed(consumed);
}
return connection->request.read_state == http_server_connection::Request::HEADERS
? BufferedResult::MORE
: (consumed == length ? BufferedResult::OK : BufferedResult::PARTIAL);
}
/**
* @return false if the connection has been closed
*/
static bool
http_server_submit_request(struct http_server_connection *connection)
{
if (connection->request.read_state == http_server_connection::Request::END)
/* re-enable the event, to detect client disconnect while
we're processing the request */
connection->socket.ScheduleReadNoTimeout(false);
const ScopePoolRef ref(*connection->pool TRACE_ARGS);
if (connection->request.expect_failed)
http_server_send_message(connection->request.request,
HTTP_STATUS_EXPECTATION_FAILED,
"Unrecognized expectation");
else {
connection->request.in_handler = true;
connection->handler->request(connection->request.request,
connection->handler_ctx,
&connection->request.async_ref);
connection->request.in_handler = false;
}
return connection->IsValid();
}
BufferedResult
http_server_connection::Feed(const void *data, size_t length)
{
assert(!response.pending_drained);
switch (request.read_state) {
BufferedResult result;
case Request::START:
case Request::HEADERS:
if (score == HTTP_SERVER_NEW)
score = HTTP_SERVER_FIRST;
result = http_server_feed_headers(this, data, length);
if ((result == BufferedResult::OK || result == BufferedResult::PARTIAL) &&
(request.read_state == Request::BODY ||
request.read_state == Request::END)) {
if (request.read_state == Request::BODY)
result = request_body_reader.RequireMore()
? BufferedResult::AGAIN_EXPECT
: BufferedResult::AGAIN_OPTIONAL;
if (!http_server_submit_request(this))
result = BufferedResult::CLOSED;
}
return result;
case Request::BODY:
return FeedRequestBody(data, length);
case Request::END:
/* check if the connection was closed by the client while we
were processing the request */
if (socket.IsFull())
/* the buffer is full, the peer has been pipelining too
much - that would disallow us to detect a disconnect;
let's disable keep-alive now and discard all data */
keep_alive = false;
if (!keep_alive) {
/* discard all pipelined input when keep-alive has been
disabled */
socket.Consumed(length);
return BufferedResult::OK;
}
return BufferedResult::MORE;
}
assert(false);
gcc_unreachable();
}
DirectResult
http_server_connection::TryRequestBodyDirect(int fd,
enum istream_direct fd_type)
{
assert(IsValid());
assert(request.read_state == Request::BODY);
assert(!response.pending_drained);
if (!MaybeSend100Continue())
return DirectResult::CLOSED;
ssize_t nbytes = request_body_reader.TryDirect(fd, fd_type);
if (nbytes == ISTREAM_RESULT_BLOCKING)
/* the destination fd blocks */
return DirectResult::BLOCKING;
if (nbytes == ISTREAM_RESULT_CLOSED)
/* the stream (and the whole connection) has been closed
during the direct() callback (-3); no further checks */
return DirectResult::CLOSED;
if (nbytes < 0) {
if (errno == EAGAIN)
return DirectResult::EMPTY;
return DirectResult::ERRNO;
}
if (nbytes == ISTREAM_RESULT_EOF)
return DirectResult::END;
request.bytes_received += nbytes;
if (request_body_reader.IsEOF()) {
request.read_state = Request::END;
request_body_reader.DeinitEOF();
return IsValid()
? DirectResult::OK
: DirectResult::CLOSED;
} else {
return DirectResult::OK;
}
}
<commit_msg>http_server: adjust score from NEW to FIRST only in read_state==START<commit_after>/*
* HTTP server implementation.
*
* istream implementation for the request body.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "http_server_internal.hxx"
#include "http_upgrade.hxx"
#include "http_util.hxx"
#include "pool.hxx"
#include "strmap.hxx"
#include "header_parser.hxx"
#include "istream-internal.h"
#include "istream_null.hxx"
#include "util/CharUtil.hxx"
#include <inline/poison.h>
#include <daemon/log.h>
#include <limits.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/socket.h>
/**
* @return false if the connection has been closed
*/
static bool
http_server_parse_request_line(struct http_server_connection *connection,
const char *line, size_t length)
{
assert(connection != nullptr);
assert(connection->request.read_state == http_server_connection::Request::START);
assert(connection->request.request == nullptr);
assert(!connection->response.pending_drained);
if (unlikely(length < 5)) {
connection->Error("malformed request line");
return false;
}
const char *eol = line + length;
http_method_t method = HTTP_METHOD_NULL;
switch (line[0]) {
case 'D':
if (likely(line[1] == 'E' && line[2] == 'L' && line[3] == 'E' &&
line[4] == 'T' && line[5] == 'E' && line[6] == ' ')) {
method = HTTP_METHOD_DELETE;
line += 7;
}
break;
case 'G':
if (likely(line[1] == 'E' && line[2] == 'T' && line[3] == ' ')) {
method = HTTP_METHOD_GET;
line += 4;
}
break;
case 'P':
if (likely(line[1] == 'O' && line[2] == 'S' && line[3] == 'T' &&
line[4] == ' ')) {
method = HTTP_METHOD_POST;
line += 5;
} else if (line[1] == 'U' && line[2] == 'T' && line[3] == ' ') {
method = HTTP_METHOD_PUT;
line += 4;
} else if (memcmp(line + 1, "ROPFIND ", 8) == 0) {
method = HTTP_METHOD_PROPFIND;
line += 9;
} else if (memcmp(line + 1, "ROPPATCH ", 9) == 0) {
method = HTTP_METHOD_PROPPATCH;
line += 10;
}
break;
case 'H':
if (likely(line[1] == 'E' && line[2] == 'A' && line[3] == 'D' &&
line[4] == ' ')) {
method = HTTP_METHOD_HEAD;
line += 5;
}
break;
case 'O':
if (memcmp(line + 1, "PTIONS ", 7) == 0) {
method = HTTP_METHOD_OPTIONS;
line += 8;
}
break;
case 'T':
if (memcmp(line + 1, "RACE ", 5) == 0) {
method = HTTP_METHOD_TRACE;
line += 6;
}
break;
case 'M':
if (memcmp(line + 1, "KCOL ", 5) == 0) {
method = HTTP_METHOD_MKCOL;
line += 6;
} else if (memcmp(line + 1, "OVE ", 4) == 0) {
method = HTTP_METHOD_MOVE;
line += 5;
}
break;
case 'C':
if (memcmp(line + 1, "OPY ", 4) == 0) {
method = HTTP_METHOD_COPY;
line += 5;
}
break;
case 'L':
if (memcmp(line + 1, "OCK ", 4) == 0) {
method = HTTP_METHOD_LOCK;
line += 5;
}
break;
case 'U':
if (memcmp(line + 1, "NLOCK ", 6) == 0) {
method = HTTP_METHOD_UNLOCK;
line += 7;
}
break;
}
if (method == HTTP_METHOD_NULL) {
/* invalid request method */
connection->Error("unrecognized request method");
return false;
}
const char *space = (const char *)memchr(line, ' ', eol - line);
if (unlikely(space == nullptr || space + 6 > line + length ||
memcmp(space + 1, "HTTP/", 5) != 0)) {
/* refuse HTTP 0.9 requests */
static const char msg[] =
"This server requires HTTP 1.1.";
ssize_t nbytes = connection->socket.Write(msg, sizeof(msg) - 1);
if (nbytes != WRITE_DESTROYED)
connection->Done();
return false;
}
connection->request.request = http_server_request_new(connection);
connection->request.request->method = method;
connection->request.request->uri = p_strndup(connection->request.request->pool, line, space - line);
connection->request.read_state = http_server_connection::Request::HEADERS;
connection->request.http_1_0 = space + 9 <= line + length &&
space[8] == '0' && space[7] == '.' && space[6] == '1';
return true;
}
/**
* @return false if the connection has been closed
*/
static bool
http_server_headers_finished(struct http_server_connection *connection)
{
struct http_server_request *request = connection->request.request;
/* disable the idle+headers timeout; the request body timeout will
be tracked by filtered_socket (auto-refreshing) */
evtimer_del(&connection->idle_timeout);
const char *value = request->headers->Get("expect");
connection->request.expect_100_continue = value != nullptr &&
strcmp(value, "100-continue") == 0;
connection->request.expect_failed = value != nullptr &&
strcmp(value, "100-continue") != 0;
value = request->headers->Get("connection");
/* we disable keep-alive support on ancient HTTP 1.0, because that
feature was not well-defined and led to problems with some
clients */
connection->keep_alive = !connection->request.http_1_0 &&
(value == nullptr || !http_list_contains_i(value, "close"));
const bool upgrade = !connection->request.http_1_0 && value != nullptr &&
http_is_upgrade(value);
value = request->headers->Get("transfer-encoding");
const struct timeval *read_timeout = &http_server_read_timeout;
off_t content_length = -1;
const bool chunked = value != nullptr && strcasecmp(value, "chunked") == 0;
if (!chunked) {
value = request->headers->Get("content-length");
if (upgrade) {
if (value != nullptr) {
connection->Error("cannot upgrade with Content-Length request header");
return false;
}
/* disable timeout */
read_timeout = nullptr;
/* forward incoming data as-is */
connection->keep_alive = false;
} else if (value == nullptr) {
/* no body at all */
request->body = nullptr;
connection->request.read_state = http_server_connection::Request::END;
return true;
} else {
char *endptr;
content_length = strtoul(value, &endptr, 10);
if (unlikely(*endptr != 0 || content_length < 0)) {
connection->Error("invalid Content-Length header in HTTP request");
return false;
}
if (content_length == 0) {
/* empty body */
request->body = istream_null_new(request->pool);
connection->request.read_state = http_server_connection::Request::END;
return true;
}
}
} else if (upgrade) {
connection->Error("cannot upgrade chunked request");
return false;
}
/* istream_deinit() used poison_noaccess() - make it writable now
for re-use */
poison_undefined(&connection->request_body_reader,
sizeof(connection->request_body_reader));
request->body =
&connection->request_body_reader.Init(http_server_request_stream,
*connection->pool,
*request->pool,
content_length, chunked);
connection->request.read_state = http_server_connection::Request::BODY;
/* for the response body, the filtered_socket class tracks
inactivity timeout */
connection->socket.ScheduleReadTimeout(false, read_timeout);
return true;
}
/**
* @return false if the connection has been closed
*/
static bool
http_server_handle_line(struct http_server_connection *connection,
const char *line, size_t length)
{
assert(connection->request.read_state == http_server_connection::Request::START ||
connection->request.read_state == http_server_connection::Request::HEADERS);
if (unlikely(connection->request.read_state == http_server_connection::Request::START)) {
assert(connection->request.request == nullptr);
return http_server_parse_request_line(connection, line, length);
} else if (likely(length > 0)) {
assert(connection->request.read_state == http_server_connection::Request::HEADERS);
assert(connection->request.request != nullptr);
header_parse_line(connection->request.request->pool,
connection->request.request->headers,
line, length);
return true;
} else {
assert(connection->request.read_state == http_server_connection::Request::HEADERS);
assert(connection->request.request != nullptr);
return http_server_headers_finished(connection);
}
}
static BufferedResult
http_server_feed_headers(struct http_server_connection *connection,
const void *_data, size_t length)
{
assert(connection->request.read_state == http_server_connection::Request::START ||
connection->request.read_state == http_server_connection::Request::HEADERS);
if (connection->request.bytes_received >= 64 * 1024) {
daemon_log(2, "http_server: too many request headers\n");
http_server_connection_close(connection);
return BufferedResult::CLOSED;
}
const char *const buffer = (const char *)_data;
const char *const buffer_end = buffer + length;
const char *start = buffer, *end, *next = nullptr;
while ((end = (const char *)memchr(start, '\n',
buffer_end - start)) != nullptr) {
next = end + 1;
--end;
while (end >= start && IsWhitespaceOrNull(*end))
--end;
if (!http_server_handle_line(connection, start, end - start + 1))
return BufferedResult::CLOSED;
if (connection->request.read_state != http_server_connection::Request::HEADERS)
break;
start = next;
}
size_t consumed = 0;
if (next != nullptr) {
consumed = next - buffer;
connection->request.bytes_received += consumed;
connection->socket.Consumed(consumed);
}
return connection->request.read_state == http_server_connection::Request::HEADERS
? BufferedResult::MORE
: (consumed == length ? BufferedResult::OK : BufferedResult::PARTIAL);
}
/**
* @return false if the connection has been closed
*/
static bool
http_server_submit_request(struct http_server_connection *connection)
{
if (connection->request.read_state == http_server_connection::Request::END)
/* re-enable the event, to detect client disconnect while
we're processing the request */
connection->socket.ScheduleReadNoTimeout(false);
const ScopePoolRef ref(*connection->pool TRACE_ARGS);
if (connection->request.expect_failed)
http_server_send_message(connection->request.request,
HTTP_STATUS_EXPECTATION_FAILED,
"Unrecognized expectation");
else {
connection->request.in_handler = true;
connection->handler->request(connection->request.request,
connection->handler_ctx,
&connection->request.async_ref);
connection->request.in_handler = false;
}
return connection->IsValid();
}
BufferedResult
http_server_connection::Feed(const void *data, size_t length)
{
assert(!response.pending_drained);
switch (request.read_state) {
BufferedResult result;
case Request::START:
if (score == HTTP_SERVER_NEW)
score = HTTP_SERVER_FIRST;
case Request::HEADERS:
result = http_server_feed_headers(this, data, length);
if ((result == BufferedResult::OK || result == BufferedResult::PARTIAL) &&
(request.read_state == Request::BODY ||
request.read_state == Request::END)) {
if (request.read_state == Request::BODY)
result = request_body_reader.RequireMore()
? BufferedResult::AGAIN_EXPECT
: BufferedResult::AGAIN_OPTIONAL;
if (!http_server_submit_request(this))
result = BufferedResult::CLOSED;
}
return result;
case Request::BODY:
return FeedRequestBody(data, length);
case Request::END:
/* check if the connection was closed by the client while we
were processing the request */
if (socket.IsFull())
/* the buffer is full, the peer has been pipelining too
much - that would disallow us to detect a disconnect;
let's disable keep-alive now and discard all data */
keep_alive = false;
if (!keep_alive) {
/* discard all pipelined input when keep-alive has been
disabled */
socket.Consumed(length);
return BufferedResult::OK;
}
return BufferedResult::MORE;
}
assert(false);
gcc_unreachable();
}
DirectResult
http_server_connection::TryRequestBodyDirect(int fd,
enum istream_direct fd_type)
{
assert(IsValid());
assert(request.read_state == Request::BODY);
assert(!response.pending_drained);
if (!MaybeSend100Continue())
return DirectResult::CLOSED;
ssize_t nbytes = request_body_reader.TryDirect(fd, fd_type);
if (nbytes == ISTREAM_RESULT_BLOCKING)
/* the destination fd blocks */
return DirectResult::BLOCKING;
if (nbytes == ISTREAM_RESULT_CLOSED)
/* the stream (and the whole connection) has been closed
during the direct() callback (-3); no further checks */
return DirectResult::CLOSED;
if (nbytes < 0) {
if (errno == EAGAIN)
return DirectResult::EMPTY;
return DirectResult::ERRNO;
}
if (nbytes == ISTREAM_RESULT_EOF)
return DirectResult::END;
request.bytes_received += nbytes;
if (request_body_reader.IsEOF()) {
request.read_state = Request::END;
request_body_reader.DeinitEOF();
return IsValid()
? DirectResult::OK
: DirectResult::CLOSED;
} else {
return DirectResult::OK;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright © 2012, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is 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 SpineFeedbackControl.cpp
* @brief A controller for the template class BaseSpineModelLearning
* @author Brian Mirletz
* @version 1.1.0
* $Id$
*/
#include "SpineFeedbackControl.h"
#include <string>
// Should include tgString, but compiler complains since its been
// included from BaseSpineModelLearning. Perhaps we should move things
// to a cpp over there
#include "core/tgSpringCableActuator.h"
#include "core/tgBasicActuator.h"
#include "controllers/tgImpedanceController.h"
#include "examples/learningSpines/tgCPGActuatorControl.h"
#include "tgCPGCableControl.h"
#include "helpers/FileHelpers.h"
#include "learning/AnnealEvolution/AnnealEvolution.h"
#include "learning/Configuration/configuration.h"
#include "CPGEquationsFB.h"
#include "CPGNodeFB.h"
//#define LOGGING
#define USE_KINEMATIC
using namespace std;
SpineFeedbackControl::Config::Config(int ss,
int tm,
int om,
int param,
int segnum,
double ct,
double la,
double ha,
double lp,
double hp,
double kt,
double kp,
double kv,
bool def,
double cl,
double lf,
double hf,
double ffMin,
double ffMax,
double afMin,
double afMax,
double pfMin,
double pfMax) :
BaseSpineCPGControl::Config::Config(ss, tm, om, param, segnum, ct, la, ha,
lp, hp, kt, kp, kv, def, cl, lf, hf),
freqFeedbackMin(ffMin),
freqFeedbackMax(ffMax),
ampFeedbackMin(afMin),
ampFeedbackMax(afMax),
phaseFeedbackMin(pfMin),
phaseFeedbackMax(pfMax)
{
}
/**
* Defining the adapters here assumes the controller is around and
* attached for the lifecycle of the learning runs. I.E. that the setup
* and teardown functions are used for tgModel
*/
SpineFeedbackControl::SpineFeedbackControl(SpineFeedbackControl::Config config,
std::string args,
std::string resourcePath,
std::string ec,
std::string nc,
std::string fc) :
BaseSpineCPGControl(config, args, resourcePath, ec, nc),
m_config(config),
feedbackConfigFilename(fc),
// Evolution assumes no pre-processing was done on these names
feedbackEvolution(args + "_fb", fc, resourcePath),
// Will be overwritten by configuration data
feedbackLearning(false)
{
std::string path;
if (resourcePath != "")
{
path = FileHelpers::getResourcePath(resourcePath);
}
else
{
path = "";
}
feedbackConfigData.readFile(path + feedbackConfigFilename);
feedbackLearning = feedbackConfigData.getintvalue("learning");
}
void SpineFeedbackControl::onSetup(BaseSpineModelLearning& subject)
{
m_pCPGSys = new CPGEquationsFB(100);
//Initialize the Learning Adapters
nodeAdapter.initialize(&nodeEvolution,
nodeLearning,
nodeConfigData);
edgeAdapter.initialize(&edgeEvolution,
edgeLearning,
edgeConfigData);
feedbackAdapter.initialize(&feedbackEvolution,
feedbackLearning,
feedbackConfigData);
/* Empty vector signifying no state information
* All parameters are stateless parameters, so we can get away with
* only doing this once
*/
std::vector<double> state;
double dt = 0;
array_4D edgeParams = scaleEdgeActions(edgeAdapter.step(dt, state));
array_2D nodeParams = scaleNodeActions(nodeAdapter.step(dt, state));
setupCPGs(subject, nodeParams, edgeParams);
initConditions = subject.getSegmentCOM(m_config.segmentNumber);
#ifdef LOGGING // Conditional compile for data logging
m_dataObserver.onSetup(subject);
#endif
#if (0) // Conditional Compile for debug info
std::cout << *m_pCPGSys << std::endl;
#endif
m_updateTime = 0.0;
bogus = false;
}
void SpineFeedbackControl::onStep(BaseSpineModelLearning& subject, double dt)
{
m_updateTime += dt;
if (m_updateTime >= m_config.controlTime)
{
#if (1)
std::vector<double> desComs = getFeedback(subject);
#else
std::size_t numControllers = subject.getNumberofMuslces() * 3;
double descendingCommand = 0.0;
std::vector<double> desComs (numControllers, descendingCommand);
#endif
try
{
m_pCPGSys->update(desComs, m_updateTime);
}
catch (std::runtime_error& e)
{
// Stops the trial immediately, lets teardown know it broke
bogus = true;
throw (e);
}
#ifdef LOGGING // Conditional compile for data logging
m_dataObserver.onStep(subject, m_updateTime);
#endif
notifyStep(m_updateTime);
m_updateTime = 0;
}
double currentHeight = subject.getSegmentCOM(m_config.segmentNumber)[1];
/// @todo add to config
if (currentHeight > 25 || currentHeight < 1.0)
{
/// @todo if bogus, stop trial (reset simulation)
bogus = true;
throw std::runtime_error("Height out of range");
}
}
void SpineFeedbackControl::onTeardown(BaseSpineModelLearning& subject)
{
scores.clear();
// @todo - check to make sure we ran for the right amount of time
std::vector<double> finalConditions = subject.getSegmentCOM(m_config.segmentNumber);
const double newX = finalConditions[0];
const double newZ = finalConditions[2];
const double oldX = initConditions[0];
const double oldZ = initConditions[2];
const double distanceMoved = sqrt((newX-oldX) * (newX-oldX) +
(newZ-oldZ) * (newZ-oldZ));
if (bogus)
{
scores.push_back(-1.0);
}
else
{
scores.push_back(distanceMoved);
}
/// @todo - consolidate with other controller classes.
/// @todo - return length scale as a parameter
double totalEnergySpent=0;
std::vector<tgSpringCableActuator* > tmpStrings = subject.getAllMuscles();
for(int i=0; i<tmpStrings.size(); i++)
{
tgSpringCableActuator::SpringCableActuatorHistory stringHist = tmpStrings[i]->getHistory();
for(int j=1; j<stringHist.tensionHistory.size(); j++)
{
const double previousTension = stringHist.tensionHistory[j-1];
const double previousLength = stringHist.restLengths[j-1];
const double currentLength = stringHist.restLengths[j];
//TODO: examine this assumption - free spinning motor may require more power
double motorSpeed = (currentLength-previousLength);
if(motorSpeed > 0) // Vestigial code
motorSpeed = 0;
const double workDone = previousTension * motorSpeed;
totalEnergySpent += workDone;
}
}
scores.push_back(totalEnergySpent);
edgeAdapter.endEpisode(scores);
nodeAdapter.endEpisode(scores);
feedbackAdapter.endEpisode(scores);
delete m_pCPGSys;
m_pCPGSys = NULL;
for(size_t i = 0; i < m_allControllers.size(); i++)
{
delete m_allControllers[i];
}
m_allControllers.clear();
}
void SpineFeedbackControl::setupCPGs(BaseSpineModelLearning& subject, array_2D nodeActions, array_4D edgeActions)
{
std::vector <tgSpringCableActuator*> allMuscles = subject.getAllMuscles();
CPGEquationsFB& m_CPGFBSys = *(tgCast::cast<CPGEquations, CPGEquationsFB>(m_pCPGSys));
for (std::size_t i = 0; i < allMuscles.size(); i++)
{
tgPIDController::Config config(20000.0, 0.0, 5.0, true); // Non backdrivable
tgCPGCableControl* pStringControl = new tgCPGCableControl(config);
allMuscles[i]->attach(pStringControl);
// First assign node numbers
pStringControl->assignNodeNumberFB(m_CPGFBSys, nodeActions);
m_allControllers.push_back(pStringControl);
}
// Then determine connectivity and setup string
for (std::size_t i = 0; i < m_allControllers.size(); i++)
{
tgCPGActuatorControl * const pStringInfo = m_allControllers[i];
assert(pStringInfo != NULL);
pStringInfo->setConnectivity(m_allControllers, edgeActions);
//String will own this pointer
tgImpedanceController* p_ipc = new tgImpedanceController( m_config.tension,
m_config.kPosition,
m_config.kVelocity);
if (m_config.useDefault)
{
pStringInfo->setupControl(*p_ipc);
}
else
{
pStringInfo->setupControl(*p_ipc, m_config.controlLength);
}
}
}
array_2D SpineFeedbackControl::scaleNodeActions
(vector< vector <double> > actions)
{
std::size_t numControllers = nodeConfigData.getintvalue("numberOfControllers");
std::size_t numActions = nodeConfigData.getintvalue("numberOfActions");
assert( actions.size() == numControllers);
assert( actions[0].size() == numActions);
array_2D nodeActions(boost::extents[numControllers][numActions]);
array_2D limits(boost::extents[2][numActions]);
// Check if we need to update limits
assert(numActions == 5);
limits[0][0] = m_config.lowFreq;
limits[1][0] = m_config.highFreq;
limits[0][1] = m_config.lowAmp;
limits[1][1] = m_config.highAmp;
limits[0][2] = m_config.freqFeedbackMin;
limits[1][2] = m_config.freqFeedbackMax;
limits[0][3] = m_config.ampFeedbackMin;
limits[1][3] = m_config.ampFeedbackMax;
limits[0][4] = m_config.phaseFeedbackMin;
limits[1][4] = m_config.phaseFeedbackMax;
// This one is square
for( std::size_t i = 0; i < numControllers; i++)
{
for( std::size_t j = 0; j < numActions; j++)
{
nodeActions[i][j] = ( actions[i][j] *
(limits[1][j] - limits[0][j])) + limits[0][j];
}
}
return nodeActions;
}
std::vector<double> SpineFeedbackControl::getFeedback(BaseSpineModelLearning& subject)
{
// Placeholder
std:vector<double> feedback;
// Adapter doesn't use this anyway, so just do zero here for now (will trigger errors if it starts to use it =) )
const double dt = 0;
const std::vector<tgSpringCableActuator*>& allCables = subject.getAllMuscles();
std::size_t n = allCables.size();
for(std::size_t i = 0; i != n; i++)
{
const tgSpringCableActuator& cable = *(allCables[i]);
std::vector<double > state = getCableState(cable);
std::vector< std::vector<double> > actions = feedbackAdapter.step(m_updateTime, state);
std::vector<double> cableFeedback = transformFeedbackActions(actions);
feedback.insert(feedback.end(), cableFeedback.begin(), cableFeedback.end());
}
return feedback;
}
std::vector<double> SpineFeedbackControl::getCableState(const tgSpringCableActuator& cable)
{
// For each string, scale value from -1 to 1 based on initial length or max tension of motor
std::vector<double> state;
// Scale length by starting length
const double startLength = cable.getStartLength();
state.push_back((cable.getCurrentLength() - startLength) / startLength);
const double maxTension = cable.getConfig().maxTens;
state.push_back((cable.getTension() - maxTension / 2.0) / maxTension);
return state;
}
std::vector<double> SpineFeedbackControl::transformFeedbackActions(std::vector< std::vector<double> >& actions)
{
// Placeholder
std:vector<double> feedback;
std::size_t numControllers = feedbackConfigData.getintvalue("numberOfControllers");
std::size_t numActions = feedbackConfigData.getintvalue("numberOfActions");
assert( actions.size() == numControllers);
assert( actions[0].size() == numActions);
// Scale values back to -1 to +1
for( std::size_t i = 0; i < numControllers; i++)
{
for( std::size_t j = 0; j < numActions; j++)
{
feedback.push_back(actions[i][j] * 2.0 - 1.0);
}
}
return feedback;
}
<commit_msg>Turn feedback off<commit_after>/*
* Copyright © 2012, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is 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 SpineFeedbackControl.cpp
* @brief A controller for the template class BaseSpineModelLearning
* @author Brian Mirletz
* @version 1.1.0
* $Id$
*/
#include "SpineFeedbackControl.h"
#include <string>
// Should include tgString, but compiler complains since its been
// included from BaseSpineModelLearning. Perhaps we should move things
// to a cpp over there
#include "core/tgSpringCableActuator.h"
#include "core/tgBasicActuator.h"
#include "controllers/tgImpedanceController.h"
#include "examples/learningSpines/tgCPGActuatorControl.h"
#include "tgCPGCableControl.h"
#include "helpers/FileHelpers.h"
#include "learning/AnnealEvolution/AnnealEvolution.h"
#include "learning/Configuration/configuration.h"
#include "CPGEquationsFB.h"
#include "CPGNodeFB.h"
//#define LOGGING
#define USE_KINEMATIC
using namespace std;
SpineFeedbackControl::Config::Config(int ss,
int tm,
int om,
int param,
int segnum,
double ct,
double la,
double ha,
double lp,
double hp,
double kt,
double kp,
double kv,
bool def,
double cl,
double lf,
double hf,
double ffMin,
double ffMax,
double afMin,
double afMax,
double pfMin,
double pfMax) :
BaseSpineCPGControl::Config::Config(ss, tm, om, param, segnum, ct, la, ha,
lp, hp, kt, kp, kv, def, cl, lf, hf),
freqFeedbackMin(ffMin),
freqFeedbackMax(ffMax),
ampFeedbackMin(afMin),
ampFeedbackMax(afMax),
phaseFeedbackMin(pfMin),
phaseFeedbackMax(pfMax)
{
}
/**
* Defining the adapters here assumes the controller is around and
* attached for the lifecycle of the learning runs. I.E. that the setup
* and teardown functions are used for tgModel
*/
SpineFeedbackControl::SpineFeedbackControl(SpineFeedbackControl::Config config,
std::string args,
std::string resourcePath,
std::string ec,
std::string nc,
std::string fc) :
BaseSpineCPGControl(config, args, resourcePath, ec, nc),
m_config(config),
feedbackConfigFilename(fc),
// Evolution assumes no pre-processing was done on these names
feedbackEvolution(args + "_fb", fc, resourcePath),
// Will be overwritten by configuration data
feedbackLearning(false)
{
std::string path;
if (resourcePath != "")
{
path = FileHelpers::getResourcePath(resourcePath);
}
else
{
path = "";
}
feedbackConfigData.readFile(path + feedbackConfigFilename);
feedbackLearning = feedbackConfigData.getintvalue("learning");
}
void SpineFeedbackControl::onSetup(BaseSpineModelLearning& subject)
{
m_pCPGSys = new CPGEquationsFB(100);
//Initialize the Learning Adapters
nodeAdapter.initialize(&nodeEvolution,
nodeLearning,
nodeConfigData);
edgeAdapter.initialize(&edgeEvolution,
edgeLearning,
edgeConfigData);
feedbackAdapter.initialize(&feedbackEvolution,
feedbackLearning,
feedbackConfigData);
/* Empty vector signifying no state information
* All parameters are stateless parameters, so we can get away with
* only doing this once
*/
std::vector<double> state;
double dt = 0;
array_4D edgeParams = scaleEdgeActions(edgeAdapter.step(dt, state));
array_2D nodeParams = scaleNodeActions(nodeAdapter.step(dt, state));
setupCPGs(subject, nodeParams, edgeParams);
initConditions = subject.getSegmentCOM(m_config.segmentNumber);
#ifdef LOGGING // Conditional compile for data logging
m_dataObserver.onSetup(subject);
#endif
#if (0) // Conditional Compile for debug info
std::cout << *m_pCPGSys << std::endl;
#endif
m_updateTime = 0.0;
bogus = false;
}
void SpineFeedbackControl::onStep(BaseSpineModelLearning& subject, double dt)
{
m_updateTime += dt;
if (m_updateTime >= m_config.controlTime)
{
#if (0)
std::vector<double> desComs = getFeedback(subject);
#else
std::size_t numControllers = subject.getNumberofMuslces() * 3;
double descendingCommand = 0.0;
std::vector<double> desComs (numControllers, descendingCommand);
#endif
try
{
m_pCPGSys->update(desComs, m_updateTime);
}
catch (std::runtime_error& e)
{
// Stops the trial immediately, lets teardown know it broke
bogus = true;
throw (e);
}
#ifdef LOGGING // Conditional compile for data logging
m_dataObserver.onStep(subject, m_updateTime);
#endif
notifyStep(m_updateTime);
m_updateTime = 0;
}
double currentHeight = subject.getSegmentCOM(m_config.segmentNumber)[1];
/// @todo add to config
if (currentHeight > 25 || currentHeight < 1.0)
{
/// @todo if bogus, stop trial (reset simulation)
bogus = true;
throw std::runtime_error("Height out of range");
}
}
void SpineFeedbackControl::onTeardown(BaseSpineModelLearning& subject)
{
scores.clear();
// @todo - check to make sure we ran for the right amount of time
std::vector<double> finalConditions = subject.getSegmentCOM(m_config.segmentNumber);
const double newX = finalConditions[0];
const double newZ = finalConditions[2];
const double oldX = initConditions[0];
const double oldZ = initConditions[2];
const double distanceMoved = sqrt((newX-oldX) * (newX-oldX) +
(newZ-oldZ) * (newZ-oldZ));
if (bogus)
{
scores.push_back(-1.0);
}
else
{
scores.push_back(distanceMoved);
}
/// @todo - consolidate with other controller classes.
/// @todo - return length scale as a parameter
double totalEnergySpent=0;
std::vector<tgSpringCableActuator* > tmpStrings = subject.getAllMuscles();
for(int i=0; i<tmpStrings.size(); i++)
{
tgSpringCableActuator::SpringCableActuatorHistory stringHist = tmpStrings[i]->getHistory();
for(int j=1; j<stringHist.tensionHistory.size(); j++)
{
const double previousTension = stringHist.tensionHistory[j-1];
const double previousLength = stringHist.restLengths[j-1];
const double currentLength = stringHist.restLengths[j];
//TODO: examine this assumption - free spinning motor may require more power
double motorSpeed = (currentLength-previousLength);
if(motorSpeed > 0) // Vestigial code
motorSpeed = 0;
const double workDone = previousTension * motorSpeed;
totalEnergySpent += workDone;
}
}
scores.push_back(totalEnergySpent);
edgeAdapter.endEpisode(scores);
nodeAdapter.endEpisode(scores);
feedbackAdapter.endEpisode(scores);
delete m_pCPGSys;
m_pCPGSys = NULL;
for(size_t i = 0; i < m_allControllers.size(); i++)
{
delete m_allControllers[i];
}
m_allControllers.clear();
}
void SpineFeedbackControl::setupCPGs(BaseSpineModelLearning& subject, array_2D nodeActions, array_4D edgeActions)
{
std::vector <tgSpringCableActuator*> allMuscles = subject.getAllMuscles();
CPGEquationsFB& m_CPGFBSys = *(tgCast::cast<CPGEquations, CPGEquationsFB>(m_pCPGSys));
for (std::size_t i = 0; i < allMuscles.size(); i++)
{
tgPIDController::Config config(20000.0, 0.0, 5.0, true); // Non backdrivable
tgCPGCableControl* pStringControl = new tgCPGCableControl(config);
allMuscles[i]->attach(pStringControl);
// First assign node numbers
pStringControl->assignNodeNumberFB(m_CPGFBSys, nodeActions);
m_allControllers.push_back(pStringControl);
}
// Then determine connectivity and setup string
for (std::size_t i = 0; i < m_allControllers.size(); i++)
{
tgCPGActuatorControl * const pStringInfo = m_allControllers[i];
assert(pStringInfo != NULL);
pStringInfo->setConnectivity(m_allControllers, edgeActions);
//String will own this pointer
tgImpedanceController* p_ipc = new tgImpedanceController( m_config.tension,
m_config.kPosition,
m_config.kVelocity);
if (m_config.useDefault)
{
pStringInfo->setupControl(*p_ipc);
}
else
{
pStringInfo->setupControl(*p_ipc, m_config.controlLength);
}
}
}
array_2D SpineFeedbackControl::scaleNodeActions
(vector< vector <double> > actions)
{
std::size_t numControllers = nodeConfigData.getintvalue("numberOfControllers");
std::size_t numActions = nodeConfigData.getintvalue("numberOfActions");
assert( actions.size() == numControllers);
assert( actions[0].size() == numActions);
array_2D nodeActions(boost::extents[numControllers][numActions]);
array_2D limits(boost::extents[2][numActions]);
// Check if we need to update limits
assert(numActions == 5);
limits[0][0] = m_config.lowFreq;
limits[1][0] = m_config.highFreq;
limits[0][1] = m_config.lowAmp;
limits[1][1] = m_config.highAmp;
limits[0][2] = m_config.freqFeedbackMin;
limits[1][2] = m_config.freqFeedbackMax;
limits[0][3] = m_config.ampFeedbackMin;
limits[1][3] = m_config.ampFeedbackMax;
limits[0][4] = m_config.phaseFeedbackMin;
limits[1][4] = m_config.phaseFeedbackMax;
// This one is square
for( std::size_t i = 0; i < numControllers; i++)
{
for( std::size_t j = 0; j < numActions; j++)
{
nodeActions[i][j] = ( actions[i][j] *
(limits[1][j] - limits[0][j])) + limits[0][j];
}
}
return nodeActions;
}
std::vector<double> SpineFeedbackControl::getFeedback(BaseSpineModelLearning& subject)
{
// Placeholder
std:vector<double> feedback;
// Adapter doesn't use this anyway, so just do zero here for now (will trigger errors if it starts to use it =) )
const double dt = 0;
const std::vector<tgSpringCableActuator*>& allCables = subject.getAllMuscles();
std::size_t n = allCables.size();
for(std::size_t i = 0; i != n; i++)
{
const tgSpringCableActuator& cable = *(allCables[i]);
std::vector<double > state = getCableState(cable);
std::vector< std::vector<double> > actions = feedbackAdapter.step(m_updateTime, state);
std::vector<double> cableFeedback = transformFeedbackActions(actions);
feedback.insert(feedback.end(), cableFeedback.begin(), cableFeedback.end());
}
return feedback;
}
std::vector<double> SpineFeedbackControl::getCableState(const tgSpringCableActuator& cable)
{
// For each string, scale value from -1 to 1 based on initial length or max tension of motor
std::vector<double> state;
// Scale length by starting length
const double startLength = cable.getStartLength();
state.push_back((cable.getCurrentLength() - startLength) / startLength);
const double maxTension = cable.getConfig().maxTens;
state.push_back((cable.getTension() - maxTension / 2.0) / maxTension);
return state;
}
std::vector<double> SpineFeedbackControl::transformFeedbackActions(std::vector< std::vector<double> >& actions)
{
// Placeholder
std:vector<double> feedback;
std::size_t numControllers = feedbackConfigData.getintvalue("numberOfControllers");
std::size_t numActions = feedbackConfigData.getintvalue("numberOfActions");
assert( actions.size() == numControllers);
assert( actions[0].size() == numActions);
// Scale values back to -1 to +1
for( std::size_t i = 0; i < numControllers; i++)
{
for( std::size_t j = 0; j < numActions; j++)
{
feedback.push_back(actions[i][j] * 2.0 - 1.0);
}
}
return feedback;
}
<|endoftext|> |
<commit_before><commit_msg>Convert SV_DECL_PTRARR_DEL(SfxVerbSlotArr_Impl) to std::vector<commit_after><|endoftext|> |
<commit_before>#include "doofit/plotting/Plot/PlotSimultaneous.h"
// STL
#include <vector>
#include <string>
// boost
// ROOT
#include "TList.h"
#include "TIterator.h"
#include "TCanvas.h"
#include "TPaveText.h"
// from RooFit
#include "RooSimultaneous.h"
#include "RooAbsData.h"
#include "RooAbsRealLValue.h"
#include "RooAbsCategoryLValue.h"
#include "RooCatType.h"
#include "RooDataHist.h"
#include "RooSuperCategory.h"
// from DooCore
#include "doocore/io/MsgStream.h"
#include "doocore/lutils/lutils.h"
// from Project
using namespace ROOT;
using namespace RooFit;
using namespace doocore::io;
namespace doofit {
namespace plotting {
PlotSimultaneous::PlotSimultaneous(const PlotConfig& cfg_plot, const RooAbsRealLValue& dimension, const RooAbsData& dataset, const RooSimultaneous& pdf, const std::vector<std::string>& components, const std::string& plot_name)
: Plot(cfg_plot, dimension, dataset, pdf, components, plot_name),
components_regexps_(components)
{
}
void PlotSimultaneous::PlotHandler(ScaleType sc_y, std::string suffix) const {
const RooSimultaneous& pdf = *dynamic_cast<const RooSimultaneous*>(pdf_);
const RooAbsData& data = *datasets_.front();
const RooAbsCategoryLValue& sim_cat = pdf.indexCat();
TList* data_split = data.split(sim_cat);
std::string plot_name;
// TCanvas c1("c1","c1",900,900);
// TLatex label(0.5, 0.5, "Bla");
// label.Draw();
// c1.Print(std::string(config_plot_.plot_directory()+"/pdf/AllPlots.pdf").c_str());
RooCatType* sim_cat_type = NULL;
TIterator* sim_cat_type_iter = sim_cat.typeIterator();
int num_slices = 0;
while((sim_cat_type=dynamic_cast<RooCatType*>(sim_cat_type_iter->Next()))) {
RooAbsPdf& sub_pdf = *(pdf.getPdf(sim_cat_type->GetName()));
if (&sub_pdf != NULL) {
RooAbsData& sub_data = *dynamic_cast<RooAbsData*>(data_split->FindObject(sim_cat_type->GetName()));
if (&sub_data == NULL) {
serr << "PlotSimultaneous::PlotHandler(...): sub dataset for category " << sim_cat_type->GetName() << " empty. Will not plot. " << endmsg;
} else {
double min,max;
RooRealVar var(dynamic_cast<const RooRealVar&>(dimension_));
sub_data.getRange(var, min, max);
sdebug << "Range: " << min << "," << max << endmsg;
//plot_name = std::string(dimension_.GetName()) + "_" + sim_cat_type->GetName();
plot_name = plot_name_ + "_" + sim_cat_type->GetName();
Plot plot(config_plot_, dimension_, sub_data, sub_pdf, components_regexps_, plot_name);
plot.plot_args_ = this->plot_args_;
plot.plot_range_ = this->plot_range_;
// 20130905 FK: deactivated this manual setting of the plot range as it
// can dramatically increase plot time. Maybe need to
// rethink that later
//plot.AddPlotArg(Range(min,max));
// go through supplied cmd args and if necessary adapt ProjWData argument
for (std::vector<RooCmdArg>::iterator it = plot.plot_args_.begin();
it != plot.plot_args_.end(); ++it) {
if (std::string(it->GetName()) == "ProjData") {
sinfo << "Found ProjWData() argument. Will change projection dataset accordingly." << endmsg;
// create the new projection argument
*it = ProjWData(*dynamic_cast<const RooArgSet*>(it->getObject(0)),
sub_data,
it->getInt(0));
}
}
doocore::lutils::setStyle("LHCb");
config_plot_.OnDemandOpenPlotStack();
TCanvas c1("c1","c1",900,900);
std::string label_text1 = std::string("Next plots: dimension ") + dimension_.GetName() + ", category " + sim_cat_type->GetName();
std::string label_text2 = std::string(" (") + plot_name + ")";
TPaveText label(0.1, 0.25, 0.9, 0.75);
label.SetTextSize(0.03);
label.AddText(label_text1.c_str());
label.AddText(label_text2.c_str());
label.SetLineWidth(0.0);
label.SetTextAlign(13);
label.SetFillColor(0);
label.Draw();
c1.Print(std::string(config_plot_.plot_directory()+"/pdf/AllPlots.pdf").c_str());
plot.PlotHandler(sc_y, suffix);
++num_slices;
}
}
}
if (num_slices > 1) {
TCanvas c1("c1","c1",900,900);
std::string label_text1 = std::string("Next plots: dimension ") + dimension_.GetName() + ", summed all categories ";
std::string label_text2 = std::string(" (") + plot_name + ")";
TPaveText label(0.1, 0.25, 0.9, 0.75);
label.SetTextSize(0.03);
label.AddText(label_text1.c_str());
label.AddText(label_text2.c_str());
label.SetLineWidth(0.0);
label.SetTextAlign(13);
label.SetFillColor(0);
label.Draw();
c1.Print(std::string(config_plot_.plot_directory()+"/pdf/AllPlots.pdf").c_str());
// plot_name = std::string(dimension_.GetName()) + "_summed";
plot_name = plot_name_ + "_summed";
Plot plot(config_plot_, dimension_, data, *pdf_, components_regexps_, plot_name);
plot.plot_args_ = this->plot_args_;
plot.plot_range_ = this->plot_range_;
// go through supplied cmd args and if necessary merge ProjWData arguments
bool project_arg_found = false;
RooArgSet* set_project = NULL;
RooAbsData* data_reduced = NULL;
const RooAbsData* data_project = NULL;
bool binned_projection = false;
for (std::vector<RooCmdArg>::iterator it = plot.plot_args_.begin();
it != plot.plot_args_.end(); ++it) {
if (std::string(it->GetName()) == "ProjData") {
sinfo << "Found ProjWData() argument. Will join with " << sim_cat.GetName() << " on same dataset." << endmsg;
project_arg_found = true;
binned_projection = it->getInt(0);
// copy argset for projection and add simultaneous category variables
set_project = new RooArgSet(*dynamic_cast<const RooArgSet*>(it->getObject(0)));
const RooSuperCategory* super_sim_cat = &dynamic_cast<const RooSuperCategory&>(sim_cat);
if (super_sim_cat) {
// The simultaneous category is a super category and will not be in the
// supplied dataset. Add input categories instead.
set_project->add(super_sim_cat->inputCatList());
} else {
set_project->add(sim_cat);
}
// check for binned projection and if so generate binned dataset here to
// accelerate projection
if (binned_projection) {
sinfo << " Binned projection is requested. Will generate a binned dataset to accelerate projection." << endmsg;
RooAbsData* data_proj = const_cast<RooAbsData*>(dynamic_cast<const RooAbsData*>(it->getObject(1)));
std::string name_data_hist = std::string(data_proj->GetName()) + "_hist";
data_reduced = data_proj->reduce(*set_project);
data_project = new RooDataHist(name_data_hist.c_str(), "binned projection dataset", *data_reduced->get(), *data_reduced);
sinfo << " Created binned dataset with " << data_project->numEntries() << " bins." << endmsg;
} else {
data_project = dynamic_cast<const RooAbsData*>(it->getObject(1));
}
// create the new projection argument
*it = ProjWData(*set_project,
*data_project,
it->getInt(0));
}
}
if (!project_arg_found) plot.AddPlotArg(ProjWData(sim_cat,data));
plot.PlotHandler(sc_y, suffix);
if (set_project != NULL) delete set_project;
if (binned_projection) {
delete data_reduced;
delete data_project;
}
}
TIter next(data_split);
TObject *obj = NULL;
while ((obj = next())) {
delete obj;
}
}
} // namespace plotting
} // namespace doofit
<commit_msg>Plotting: binned dataset for projections also for slices of simultaneous categories<commit_after>#include "doofit/plotting/Plot/PlotSimultaneous.h"
// STL
#include <vector>
#include <string>
// boost
// ROOT
#include "TList.h"
#include "TIterator.h"
#include "TCanvas.h"
#include "TPaveText.h"
// from RooFit
#include "RooSimultaneous.h"
#include "RooAbsData.h"
#include "RooAbsRealLValue.h"
#include "RooAbsCategoryLValue.h"
#include "RooCatType.h"
#include "RooDataHist.h"
#include "RooSuperCategory.h"
// from DooCore
#include "doocore/io/MsgStream.h"
#include "doocore/lutils/lutils.h"
// from Project
using namespace ROOT;
using namespace RooFit;
using namespace doocore::io;
namespace doofit {
namespace plotting {
PlotSimultaneous::PlotSimultaneous(const PlotConfig& cfg_plot, const RooAbsRealLValue& dimension, const RooAbsData& dataset, const RooSimultaneous& pdf, const std::vector<std::string>& components, const std::string& plot_name)
: Plot(cfg_plot, dimension, dataset, pdf, components, plot_name),
components_regexps_(components)
{
}
void PlotSimultaneous::PlotHandler(ScaleType sc_y, std::string suffix) const {
const RooSimultaneous& pdf = *dynamic_cast<const RooSimultaneous*>(pdf_);
const RooAbsData& data = *datasets_.front();
const RooAbsCategoryLValue& sim_cat = pdf.indexCat();
TList* data_split = data.split(sim_cat);
std::string plot_name;
// TCanvas c1("c1","c1",900,900);
// TLatex label(0.5, 0.5, "Bla");
// label.Draw();
// c1.Print(std::string(config_plot_.plot_directory()+"/pdf/AllPlots.pdf").c_str());
RooCatType* sim_cat_type = NULL;
TIterator* sim_cat_type_iter = sim_cat.typeIterator();
int num_slices = 0;
while((sim_cat_type=dynamic_cast<RooCatType*>(sim_cat_type_iter->Next()))) {
RooAbsPdf& sub_pdf = *(pdf.getPdf(sim_cat_type->GetName()));
if (&sub_pdf != NULL) {
RooAbsData& sub_data = *dynamic_cast<RooAbsData*>(data_split->FindObject(sim_cat_type->GetName()));
if (&sub_data == NULL) {
serr << "PlotSimultaneous::PlotHandler(...): sub dataset for category " << sim_cat_type->GetName() << " empty. Will not plot. " << endmsg;
} else {
double min,max;
RooRealVar var(dynamic_cast<const RooRealVar&>(dimension_));
sub_data.getRange(var, min, max);
sdebug << "Range: " << min << "," << max << endmsg;
//plot_name = std::string(dimension_.GetName()) + "_" + sim_cat_type->GetName();
plot_name = plot_name_ + "_" + sim_cat_type->GetName();
Plot plot(config_plot_, dimension_, sub_data, sub_pdf, components_regexps_, plot_name);
plot.plot_args_ = this->plot_args_;
plot.plot_range_ = this->plot_range_;
// 20130905 FK: deactivated this manual setting of the plot range as it
// can dramatically increase plot time. Maybe need to
// rethink that later
//plot.AddPlotArg(Range(min,max));
// go through supplied cmd args and if necessary adapt ProjWData argument
bool project_arg_found = false;
const RooAbsData* data_project = NULL;
bool binned_projection = false;
for (std::vector<RooCmdArg>::iterator it = plot.plot_args_.begin();
it != plot.plot_args_.end(); ++it) {
if (std::string(it->GetName()) == "ProjData") {
sinfo << "Found ProjWData() argument. Will change projection dataset accordingly." << endmsg;
project_arg_found = true;
binned_projection = it->getInt(0);
// check for binned projection and if so generate binned dataset here to
// accelerate projection
if (binned_projection) {
sinfo << " Binned projection is requested. Will generate a binned dataset to accelerate projection." << endmsg;
std::string name_data_hist = std::string(sub_data.GetName()) + "_hist" + sim_cat_type->GetName();
data_project = new RooDataHist(name_data_hist.c_str(), "binned projection dataset", *sub_data.get(), sub_data);
sinfo << " Created binned dataset with " << data_project->numEntries() << " bins." << endmsg;
} else {
data_project = &sub_data;
}
// create the new projection argument
*it = ProjWData(*dynamic_cast<const RooArgSet*>(it->getObject(0)),
*data_project,
it->getInt(0));
}
}
doocore::lutils::setStyle("LHCb");
config_plot_.OnDemandOpenPlotStack();
TCanvas c1("c1","c1",900,900);
std::string label_text1 = std::string("Next plots: dimension ") + dimension_.GetName() + ", category " + sim_cat_type->GetName();
std::string label_text2 = std::string(" (") + plot_name + ")";
TPaveText label(0.1, 0.25, 0.9, 0.75);
label.SetTextSize(0.03);
label.AddText(label_text1.c_str());
label.AddText(label_text2.c_str());
label.SetLineWidth(0.0);
label.SetTextAlign(13);
label.SetFillColor(0);
label.Draw();
c1.Print(std::string(config_plot_.plot_directory()+"/pdf/AllPlots.pdf").c_str());
plot.PlotHandler(sc_y, suffix);
if (binned_projection) {
delete data_project;
}
++num_slices;
}
}
}
if (num_slices > 1) {
TCanvas c1("c1","c1",900,900);
std::string label_text1 = std::string("Next plots: dimension ") + dimension_.GetName() + ", summed all categories ";
std::string label_text2 = std::string(" (") + plot_name + ")";
TPaveText label(0.1, 0.25, 0.9, 0.75);
label.SetTextSize(0.03);
label.AddText(label_text1.c_str());
label.AddText(label_text2.c_str());
label.SetLineWidth(0.0);
label.SetTextAlign(13);
label.SetFillColor(0);
label.Draw();
c1.Print(std::string(config_plot_.plot_directory()+"/pdf/AllPlots.pdf").c_str());
// plot_name = std::string(dimension_.GetName()) + "_summed";
plot_name = plot_name_ + "_summed";
Plot plot(config_plot_, dimension_, data, *pdf_, components_regexps_, plot_name);
plot.plot_args_ = this->plot_args_;
plot.plot_range_ = this->plot_range_;
// go through supplied cmd args and if necessary merge ProjWData arguments
bool project_arg_found = false;
RooArgSet* set_project = NULL;
RooAbsData* data_reduced = NULL;
const RooAbsData* data_project = NULL;
bool binned_projection = false;
for (std::vector<RooCmdArg>::iterator it = plot.plot_args_.begin();
it != plot.plot_args_.end(); ++it) {
if (std::string(it->GetName()) == "ProjData") {
sinfo << "Found ProjWData() argument. Will join with " << sim_cat.GetName() << " on same dataset." << endmsg;
project_arg_found = true;
binned_projection = it->getInt(0);
// copy argset for projection and add simultaneous category variables
set_project = new RooArgSet(*dynamic_cast<const RooArgSet*>(it->getObject(0)));
const RooSuperCategory* super_sim_cat = &dynamic_cast<const RooSuperCategory&>(sim_cat);
if (super_sim_cat) {
// The simultaneous category is a super category and will not be in the
// supplied dataset. Add input categories instead.
set_project->add(super_sim_cat->inputCatList());
} else {
set_project->add(sim_cat);
}
// check for binned projection and if so generate binned dataset here to
// accelerate projection
if (binned_projection) {
sinfo << " Binned projection is requested. Will generate a binned dataset to accelerate projection." << endmsg;
RooAbsData* data_proj = const_cast<RooAbsData*>(dynamic_cast<const RooAbsData*>(it->getObject(1)));
std::string name_data_hist = std::string(data_proj->GetName()) + "_hist";
data_reduced = data_proj->reduce(*set_project);
data_project = new RooDataHist(name_data_hist.c_str(), "binned projection dataset", *data_reduced->get(), *data_reduced);
sinfo << " Created binned dataset with " << data_project->numEntries() << " bins." << endmsg;
} else {
data_project = dynamic_cast<const RooAbsData*>(it->getObject(1));
}
// create the new projection argument
*it = ProjWData(*set_project,
*data_project,
it->getInt(0));
}
}
if (!project_arg_found) plot.AddPlotArg(ProjWData(sim_cat,data));
plot.PlotHandler(sc_y, suffix);
if (set_project != NULL) delete set_project;
if (binned_projection) {
delete data_reduced;
delete data_project;
}
}
TIter next(data_split);
TObject *obj = NULL;
while ((obj = next())) {
delete obj;
}
}
} // namespace plotting
} // namespace doofit
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2014-2019 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file ll40ls.cpp
* @author Allyson Kreft
* @author Johan Jansen <jnsn.johan@gmail.com>
* @author Ban Siesta <bansiesta@gmail.com>
* @author James Goppert <james.goppert@gmail.com>
*
*/
#include <board_config.h>
#include <px4_platform_common/getopt.h>
#include <px4_platform_common/module.h>
#include "LidarLiteI2C.h"
void
LidarLiteI2C::print_usage()
{
PRINT_MODULE_DESCRIPTION(
R"DESCR_STR(
### Description
I2C bus driver for LidarLite rangefinders.
The sensor/driver must be enabled using the parameter SENS_EN_LL40LS.
Setup/usage information: https://docs.px4.io/master/en/sensor/lidar_lite.html
)DESCR_STR");
PRINT_MODULE_USAGE_NAME("ll40ls", "driver");
PRINT_MODULE_USAGE_SUBCATEGORY("distance_sensor");
PRINT_MODULE_USAGE_COMMAND("start");
PRINT_MODULE_USAGE_PARAMS_I2C_SPI_DRIVER(true, false);
PRINT_MODULE_USAGE_PARAM_INT('R', 0, 0, 35, "Rotation", true);
PRINT_MODULE_USAGE_COMMAND("regdump");
PRINT_MODULE_USAGE_DEFAULT_COMMANDS();
}
I2CSPIDriverBase *LidarLiteI2C::instantiate(const BusCLIArguments &cli, const BusInstanceIterator &iterator,
int runtime_instance)
{
LidarLiteI2C* instance = new LidarLiteI2C(iterator.configuredBusOption(), iterator.bus(), cli.rotation, cli.bus_frequency);
if (instance == nullptr) {
PX4_ERR("alloc failed");
return nullptr;
}
if (instance->init() != PX4_OK) {
delete instance;
return nullptr;
}
instance->start();
return instance;
}
void
LidarLiteI2C::custom_method(const BusCLIArguments &cli)
{
print_registers();
}
extern "C" __EXPORT int ll40ls_main(int argc, char *argv[])
{
int ch;
using ThisDriver = LidarLiteI2C;
BusCLIArguments cli{true, false};
cli.default_i2c_frequency = 100000;
while ((ch = cli.getopt(argc, argv, "R:")) != EOF) {
switch (ch) {
case 'R':
cli.rotation = (enum Rotation)atoi(cli.optarg());
break;
}
}
const char *verb = cli.optarg();
if (!verb) {
ThisDriver::print_usage();
return -1;
}
BusInstanceIterator iterator(MODULE_NAME, cli, DRV_DIST_DEVTYPE_LL40LS);
if (!strcmp(verb, "start")) {
return ThisDriver::module_start(cli, iterator);
}
if (!strcmp(verb, "stop")) {
return ThisDriver::module_stop(iterator);
}
if (!strcmp(verb, "status")) {
return ThisDriver::module_status(iterator);
}
if (!strcmp(verb, "regdump")) {
return ThisDriver::module_custom_method(cli, iterator);
}
ThisDriver::print_usage();
return -1;
}
<commit_msg>ll40ls: set default rotation to downwards facing<commit_after>/****************************************************************************
*
* Copyright (c) 2014-2019 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file ll40ls.cpp
* @author Allyson Kreft
* @author Johan Jansen <jnsn.johan@gmail.com>
* @author Ban Siesta <bansiesta@gmail.com>
* @author James Goppert <james.goppert@gmail.com>
*
*/
#include <board_config.h>
#include <px4_platform_common/getopt.h>
#include <px4_platform_common/module.h>
#include "LidarLiteI2C.h"
void
LidarLiteI2C::print_usage()
{
PRINT_MODULE_DESCRIPTION(
R"DESCR_STR(
### Description
I2C bus driver for LidarLite rangefinders.
The sensor/driver must be enabled using the parameter SENS_EN_LL40LS.
Setup/usage information: https://docs.px4.io/master/en/sensor/lidar_lite.html
)DESCR_STR");
PRINT_MODULE_USAGE_NAME("ll40ls", "driver");
PRINT_MODULE_USAGE_SUBCATEGORY("distance_sensor");
PRINT_MODULE_USAGE_COMMAND("start");
PRINT_MODULE_USAGE_PARAMS_I2C_SPI_DRIVER(true, false);
PRINT_MODULE_USAGE_PARAM_INT('R', 25, 0, 25, "Sensor rotation - downward facing by default", true);
PRINT_MODULE_USAGE_COMMAND("regdump");
PRINT_MODULE_USAGE_DEFAULT_COMMANDS();
}
I2CSPIDriverBase *LidarLiteI2C::instantiate(const BusCLIArguments &cli, const BusInstanceIterator &iterator,
int runtime_instance)
{
LidarLiteI2C* instance = new LidarLiteI2C(iterator.configuredBusOption(), iterator.bus(), cli.rotation, cli.bus_frequency);
if (instance == nullptr) {
PX4_ERR("alloc failed");
return nullptr;
}
if (instance->init() != PX4_OK) {
delete instance;
return nullptr;
}
instance->start();
return instance;
}
void
LidarLiteI2C::custom_method(const BusCLIArguments &cli)
{
print_registers();
}
extern "C" __EXPORT int ll40ls_main(int argc, char *argv[])
{
int ch;
using ThisDriver = LidarLiteI2C;
BusCLIArguments cli{true, false};
cli.orientation = distance_sensor_s::ROTATION_DOWNWARD_FACING;
cli.default_i2c_frequency = 100000;
while ((ch = cli.getopt(argc, argv, "R:")) != EOF) {
switch (ch) {
case 'R':
cli.rotation = (enum Rotation)atoi(cli.optarg());
break;
}
}
const char *verb = cli.optarg();
if (!verb) {
ThisDriver::print_usage();
return -1;
}
BusInstanceIterator iterator(MODULE_NAME, cli, DRV_DIST_DEVTYPE_LL40LS);
if (!strcmp(verb, "start")) {
return ThisDriver::module_start(cli, iterator);
}
if (!strcmp(verb, "stop")) {
return ThisDriver::module_stop(iterator);
}
if (!strcmp(verb, "status")) {
return ThisDriver::module_status(iterator);
}
if (!strcmp(verb, "regdump")) {
return ThisDriver::module_custom_method(cli, iterator);
}
ThisDriver::print_usage();
return -1;
}
<|endoftext|> |
<commit_before>/*
MIT License
Copyright (c) 2016-2017 Mark Allender
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 "SDL.h"
#include "apple2emu.h"
#include "apple2emu_defs.h"
#include "speaker.h"
#include "memory.h"
static SDL_AudioDeviceID Device_id = 0;
static SDL_AudioSpec Audio_spec;
const static int Sound_freq = 11025;
const static int Sound_num_channels = 1;
const static int Sound_buffer_size = (Sound_freq * Sound_num_channels) / 60;
const static int Speaker_sample_cycles = CYCLES_PER_FRAME / Sound_buffer_size;
static bool Speaker_on = false;
static int Speaker_cycles = 0;
static int8_t Sound_buffer[Sound_buffer_size];
static int Sound_buffer_index = 0;
uint8_t speaker_soft_switch_handler(uint16_t addr, uint8_t val, bool write)
{
Speaker_on = !Speaker_on;
UNREFERENCED(addr);
UNREFERENCED(val);
UNREFERENCED(write);
return 0xff;
}
// initialize the speaker system. For now, this is just setting up a handler
// for the memory location that will do nothing
void speaker_init()
{
// allow for re-entrancy
if (Device_id != 0) {
SDL_CloseAudioDevice(Device_id);
}
// open up sdl audio device to write wave data
SDL_AudioSpec want;
want.channels = Sound_num_channels;
want.format = AUDIO_S8;
want.freq = Sound_freq;
want.samples = Sound_buffer_size;
want.callback = nullptr;
want.userdata = nullptr;
Device_id = SDL_OpenAudioDevice(nullptr, 0, &want, &Audio_spec, SDL_AUDIO_ALLOW_ANY_CHANGE);
SDL_PauseAudioDevice(Device_id, 1);
// set up sound buffer
Speaker_cycles = 0;
Sound_buffer_index = 0;
for (auto i = 0; i < Sound_buffer_size; i++) {
Sound_buffer[i] = 0;
}
Speaker_on = false;
}
void speaker_shutdown()
{
if (Device_id != 0) {
SDL_CloseAudioDevice(Device_id);
}
}
// update internal speaker code, which will first entail
// writing out information on current speaker status to
// the buffer, and then, if full, copying the buffer to
// the SDL audio queue
void speaker_update(int cycles)
{
static bool last_value = false;
UNREFERENCED(cycles);
Speaker_cycles += cycles;
if (Speaker_cycles < Speaker_sample_cycles) {
return;
}
Speaker_cycles -= Speaker_sample_cycles;
last_value = Speaker_on;
// assume speaker on
int8_t val = 127;
if (Speaker_on == false) {
// ramp down value slightly
val = last_value ? 63 : 0;
}
Sound_buffer[Sound_buffer_index++] = val;
if (Sound_buffer_index == Sound_buffer_size) {
SDL_QueueAudio(Device_id, Sound_buffer, Sound_buffer_size);
Sound_buffer_index = 0;
}
}
void speaker_queue_audio()
{
}
void speaker_pause()
{
SDL_PauseAudioDevice(Device_id, 1);
}
void speaker_unpause()
{
SDL_PauseAudioDevice(Device_id, 0);
}
<commit_msg>Working sound<commit_after>/*
MIT License
Copyright (c) 2016-2017 Mark Allender
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 "SDL.h"
#include "apple2emu.h"
#include "apple2emu_defs.h"
#include "speaker.h"
#include "memory.h"
static SDL_AudioDeviceID Device_id = 0;
static SDL_AudioSpec Audio_spec;
const static int Sound_samples = 44100;
const static int Sound_num_channels = 1;
const static int Sound_buffer_size = (Sound_samples * Sound_num_channels) / 60;
const static int Speaker_sample_cycles = CYCLES_PER_FRAME / Sound_buffer_size;
static int8_t Sound_silence;
// ring bugger
const static int Sound_ring_buffer_size = Sound_buffer_size * 2;
static int8_t Sound_ring_buffer[Sound_ring_buffer_size];
uint32_t Tail_index, Head_index;
SDL_sem *Sound_sem;
static bool Speaker_on = false;
static int Speaker_cycles = 0;
static void speaker_callback(void *userdata, uint8_t *stream, int len)
{
SDL_semaphore *sem = (SDL_semaphore *)userdata;
//int total_shorts = len / 2;
//int tail_index = Tail_index % Sound_ring_buffer_size;
//int head_index = Head_index % Sound_ring_buffer_size;
// we have to memcpy since we have shorts, and we must be prepared to
// wrap the buffer to the beginning
//if (head_index + total_shorts > Sound_ring_buffer_size) {
// int num_samples = Sound_ring_buffer_size - head_index;
// memcpy(stream, &Sound_ring_buffer[head_index], num_samples);
// memcpy(&stream[num_samples], Sound_ring_buffer, total_shorts - num_samples);
//} else {
// memcpy(stream, &Sound_ring_buffer[head_index], total_shorts);
//}
//Head_index += total_shorts;
SDL_SemWait(sem);
int index = 0;
while (Head_index < Tail_index) {
stream[index] = Sound_ring_buffer[(Head_index++) % Sound_ring_buffer_size];
index++;
if (index == len) {
break;
}
}
SDL_SemPost(sem);
while (index < len) {
stream[index++] = Sound_silence;
}
SDL_assert(Tail_index >= Head_index);
}
uint8_t speaker_soft_switch_handler(uint16_t addr, uint8_t val, bool write)
{
Speaker_on = !Speaker_on;
UNREFERENCED(addr);
UNREFERENCED(val);
UNREFERENCED(write);
return 0xff;
}
// initialize the speaker system. For now, this is just setting up a handler
// for the memory location that will do nothing
void speaker_init()
{
// allow for re-entrancy
if (Device_id != 0) {
SDL_CloseAudioDevice(Device_id);
}
Sound_sem = SDL_CreateSemaphore(1);
if (Sound_sem == nullptr) {
// ummm... have to figure out what to do here
}
// open up sdl audio device to write wave data
SDL_AudioSpec want;
want.channels = Sound_num_channels;
want.format = AUDIO_S8;
want.freq = Sound_samples;
want.samples = Sound_buffer_size;
want.callback = speaker_callback;
want.userdata = Sound_sem;
Device_id = SDL_OpenAudioDevice(nullptr, 0, &want, &Audio_spec, SDL_AUDIO_ALLOW_ANY_CHANGE);
SDL_PauseAudioDevice(Device_id, 1);
// set up sound buffer
Speaker_cycles = 0;
Tail_index = Head_index = 0;
for (auto i = 0; i < Sound_ring_buffer_size; i++) {
Sound_ring_buffer[i] = 0;
}
Speaker_on = false;
Sound_silence = SCHAR_MIN;
}
void speaker_shutdown()
{
if (Device_id != 0) {
SDL_CloseAudioDevice(Device_id);
}
SDL_DestroySemaphore(Sound_sem);
}
// update internal speaker code, which will first entail
// writing out information on current speaker status to
// the buffer, and then, if full, copying the buffer to
// the SDL audio queue
void speaker_update(int cycles)
{
static bool last_value = false;
UNREFERENCED(cycles);
Speaker_cycles += cycles;
if (Speaker_cycles < Speaker_sample_cycles) {
return;
}
Speaker_cycles -= Speaker_sample_cycles;
// assume speaker on
int8_t val = Sound_silence;
if (Speaker_on) {
val = ~val;
}
// ring buffer
SDL_SemWait(Sound_sem);
Sound_ring_buffer[(Tail_index++) % Sound_ring_buffer_size] = val;
SDL_SemPost(Sound_sem);
SDL_assert(Head_index <= Tail_index);
last_value = Speaker_on;
}
void speaker_queue_audio()
{
}
void speaker_pause()
{
SDL_PauseAudioDevice(Device_id, 1);
}
void speaker_unpause()
{
SDL_PauseAudioDevice(Device_id, 0);
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <ranges>
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include <iterator>
std::vector<int> count_lines_in_files(std::vector<std::string> const& strs) {
auto const& tmp_vals = strs
| std::ranges::views::transform(
[](std::string const& str) { return std::istringstream{str}; })
| std::ranges::views::transform(
[](std::istringstream strstream) {
return std::count(
std::istreambuf_iterator<char>(strstream),
std::istreambuf_iterator<char>(),
'\n');
});
std::vector<int> cnts{};
std::copy(std::cbegin(tmp_vals), std::cend(tmp_vals), std::back_inserter(cnts));
return cnts;
}
int main() {
for (auto const line_count : count_lines_in_files( { "1\n2\n3" }))
std::cout << line_count << " line(s)\n";
return 0;
}
<commit_msg>[i_cukic-func_progr_in_cpp][ch 01] slightly rewrite a more elaborate example with ranges and lambdas<commit_after>#include <algorithm>
#include <iostream>
#include <iterator>
#include <ranges>
#include <sstream>
#include <string>
#include <vector>
namespace test {
std::vector<int> countLines(std::vector<std::string> const& strs) {
std::vector<int> ret{};
auto const& vals = strs
| std::ranges::views::transform(
[](auto const& str) { return std::istringstream{str}; })
| std::ranges::views::transform(
[](auto strstream) {
return std::count(
std::istreambuf_iterator<char>{strstream},
std::istreambuf_iterator<char>{},
'\n');
});
std::copy(std::cbegin(vals), std::cend(vals), std::back_inserter(ret));
return ret;
}
void run() {
for (auto const cnt: countLines( { "1\n2\n3", "1\n2\n3", "1\n2\n3" } ))
std::cout << "line count: " << cnt << std::endl;
}
} // test
int main() {
std::cout << "test => [ok]" << std::endl; test::run(); std::cout << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2004-2005 The Regents of The University of Michigan
* 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 copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Todo: Find all the stuff in ExecContext and ev5 that needs to be
// specifically designed for this CPU.
#ifndef __CPU_O3_CPU_ALPHA_FULL_CPU_HH__
#define __CPU_O3_CPU_ALPHA_FULL_CPU_HH__
#include "cpu/o3/cpu.hh"
#include "arch/isa_traits.hh"
#include "sim/byteswap.hh"
template <class Impl>
class AlphaFullCPU : public FullO3CPU<Impl>
{
protected:
typedef TheISA::IntReg IntReg;
public:
typedef typename Impl::Params Params;
public:
AlphaFullCPU(Params ¶ms);
#if FULL_SYSTEM
AlphaITB *itb;
AlphaDTB *dtb;
#endif
public:
void regStats();
#if FULL_SYSTEM
//Note that the interrupt stuff from the base CPU might be somewhat
//ISA specific (ie NumInterruptLevels). These functions might not
//be needed in FullCPU though.
// void post_interrupt(int int_num, int index);
// void clear_interrupt(int int_num, int index);
// void clear_interrupts();
Fault translateInstReq(MemReqPtr &req)
{
return itb->translate(req);
}
Fault translateDataReadReq(MemReqPtr &req)
{
return dtb->translate(req, false);
}
Fault translateDataWriteReq(MemReqPtr &req)
{
return dtb->translate(req, true);
}
#else
Fault dummyTranslation(MemReqPtr &req)
{
#if 0
assert((req->vaddr >> 48 & 0xffff) == 0);
#endif
// put the asid in the upper 16 bits of the paddr
req->paddr = req->vaddr & ~((Addr)0xffff << sizeof(Addr) * 8 - 16);
req->paddr = req->paddr | (Addr)req->asid << sizeof(Addr) * 8 - 16;
return NoFault;
}
Fault translateInstReq(MemReqPtr &req)
{
return dummyTranslation(req);
}
Fault translateDataReadReq(MemReqPtr &req)
{
return dummyTranslation(req);
}
Fault translateDataWriteReq(MemReqPtr &req)
{
return dummyTranslation(req);
}
#endif
// Later on may want to remove this misc stuff from the regfile and
// have it handled at this level. Might prove to be an issue when
// trying to rename source/destination registers...
uint64_t readUniq()
{
return this->regFile.readUniq();
}
void setUniq(uint64_t val)
{
this->regFile.setUniq(val);
}
uint64_t readFpcr()
{
return this->regFile.readFpcr();
}
void setFpcr(uint64_t val)
{
this->regFile.setFpcr(val);
}
// Most of the full system code and syscall emulation is not yet
// implemented. These functions do show what the final interface will
// look like.
#if FULL_SYSTEM
uint64_t *getIpr();
uint64_t readIpr(int idx, Fault &fault);
Fault setIpr(int idx, uint64_t val);
int readIntrFlag();
void setIntrFlag(int val);
Fault hwrei();
bool inPalMode() { return AlphaISA::PcPAL(this->regFile.readPC()); }
bool inPalMode(uint64_t PC)
{ return AlphaISA::PcPAL(PC); }
void trap(Fault fault);
bool simPalCheck(int palFunc);
void processInterrupts();
#endif
#if !FULL_SYSTEM
// Need to change these into regfile calls that directly set a certain
// register. Actually, these functions should handle most of this
// functionality by themselves; should look up the rename and then
// set the register.
IntReg getSyscallArg(int i)
{
return this->xc->regs.intRegFile[AlphaISA::ArgumentReg0 + i];
}
// used to shift args for indirect syscall
void setSyscallArg(int i, IntReg val)
{
this->xc->regs.intRegFile[AlphaISA::ArgumentReg0 + i] = val;
}
void setSyscallReturn(int64_t return_value)
{
// check for error condition. Alpha syscall convention is to
// indicate success/failure in reg a3 (r19) and put the
// return value itself in the standard return value reg (v0).
const int RegA3 = 19; // only place this is used
if (return_value >= 0) {
// no error
this->xc->regs.intRegFile[RegA3] = 0;
this->xc->regs.intRegFile[AlphaISA::ReturnValueReg] = return_value;
} else {
// got an error, return details
this->xc->regs.intRegFile[RegA3] = (IntReg) -1;
this->xc->regs.intRegFile[AlphaISA::ReturnValueReg] = -return_value;
}
}
void syscall(short thread_num);
void squashStages();
#endif
void copyToXC();
void copyFromXC();
public:
#if FULL_SYSTEM
bool palShadowEnabled;
// Not sure this is used anywhere.
void intr_post(RegFile *regs, Fault fault, Addr pc);
// Actually used within exec files. Implement properly.
void swapPALShadow(bool use_shadow);
// Called by CPU constructor. Can implement as I please.
void initCPU(RegFile *regs);
// Called by initCPU. Implement as I please.
void initIPRs(RegFile *regs);
void halt() { panic("Halt not implemented!\n"); }
#endif
template <class T>
Fault read(MemReqPtr &req, T &data)
{
#if FULL_SYSTEM && defined(TARGET_ALPHA)
if (req->flags & LOCKED) {
MiscRegFile *cregs = &req->xc->regs.miscRegs;
cregs->lock_addr = req->paddr;
cregs->lock_flag = true;
}
#endif
Fault error;
error = this->mem->read(req, data);
data = gtoh(data);
return error;
}
template <class T>
Fault read(MemReqPtr &req, T &data, int load_idx)
{
return this->iew.ldstQueue.read(req, data, load_idx);
}
template <class T>
Fault write(MemReqPtr &req, T &data)
{
#if FULL_SYSTEM && defined(TARGET_ALPHA)
MiscRegFile *cregs;
// If this is a store conditional, act appropriately
if (req->flags & LOCKED) {
cregs = &this->xc->regs.miscRegs;
if (req->flags & UNCACHEABLE) {
// Don't update result register (see stq_c in isa_desc)
req->result = 2;
req->xc->storeCondFailures = 0;//Needed? [RGD]
} else {
req->result = cregs->lock_flag;
if (!cregs->lock_flag ||
((cregs->lock_addr & ~0xf) != (req->paddr & ~0xf))) {
cregs->lock_flag = false;
if (((++req->xc->storeCondFailures) % 100000) == 0) {
std::cerr << "Warning: "
<< req->xc->storeCondFailures
<< " consecutive store conditional failures "
<< "on cpu " << this->cpu_id
<< std::endl;
}
return NoFault;
}
else req->xc->storeCondFailures = 0;
}
}
// Need to clear any locked flags on other proccessors for
// this address. Only do this for succsful Store Conditionals
// and all other stores (WH64?). Unsuccessful Store
// Conditionals would have returned above, and wouldn't fall
// through.
for (int i = 0; i < this->system->execContexts.size(); i++){
cregs = &this->system->execContexts[i]->regs.miscRegs;
if ((cregs->lock_addr & ~0xf) == (req->paddr & ~0xf)) {
cregs->lock_flag = false;
}
}
#endif
return this->mem->write(req, (T)::htog(data));
}
template <class T>
Fault write(MemReqPtr &req, T &data, int store_idx)
{
return this->iew.ldstQueue.write(req, data, store_idx);
}
};
#endif // __CPU_O3_CPU_ALPHA_FULL_CPU_HH__
<commit_msg>Removed a stray ::.<commit_after>/*
* Copyright (c) 2004-2005 The Regents of The University of Michigan
* 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 copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Todo: Find all the stuff in ExecContext and ev5 that needs to be
// specifically designed for this CPU.
#ifndef __CPU_O3_CPU_ALPHA_FULL_CPU_HH__
#define __CPU_O3_CPU_ALPHA_FULL_CPU_HH__
#include "cpu/o3/cpu.hh"
#include "arch/isa_traits.hh"
#include "sim/byteswap.hh"
template <class Impl>
class AlphaFullCPU : public FullO3CPU<Impl>
{
protected:
typedef TheISA::IntReg IntReg;
public:
typedef typename Impl::Params Params;
public:
AlphaFullCPU(Params ¶ms);
#if FULL_SYSTEM
AlphaITB *itb;
AlphaDTB *dtb;
#endif
public:
void regStats();
#if FULL_SYSTEM
//Note that the interrupt stuff from the base CPU might be somewhat
//ISA specific (ie NumInterruptLevels). These functions might not
//be needed in FullCPU though.
// void post_interrupt(int int_num, int index);
// void clear_interrupt(int int_num, int index);
// void clear_interrupts();
Fault translateInstReq(MemReqPtr &req)
{
return itb->translate(req);
}
Fault translateDataReadReq(MemReqPtr &req)
{
return dtb->translate(req, false);
}
Fault translateDataWriteReq(MemReqPtr &req)
{
return dtb->translate(req, true);
}
#else
Fault dummyTranslation(MemReqPtr &req)
{
#if 0
assert((req->vaddr >> 48 & 0xffff) == 0);
#endif
// put the asid in the upper 16 bits of the paddr
req->paddr = req->vaddr & ~((Addr)0xffff << sizeof(Addr) * 8 - 16);
req->paddr = req->paddr | (Addr)req->asid << sizeof(Addr) * 8 - 16;
return NoFault;
}
Fault translateInstReq(MemReqPtr &req)
{
return dummyTranslation(req);
}
Fault translateDataReadReq(MemReqPtr &req)
{
return dummyTranslation(req);
}
Fault translateDataWriteReq(MemReqPtr &req)
{
return dummyTranslation(req);
}
#endif
// Later on may want to remove this misc stuff from the regfile and
// have it handled at this level. Might prove to be an issue when
// trying to rename source/destination registers...
uint64_t readUniq()
{
return this->regFile.readUniq();
}
void setUniq(uint64_t val)
{
this->regFile.setUniq(val);
}
uint64_t readFpcr()
{
return this->regFile.readFpcr();
}
void setFpcr(uint64_t val)
{
this->regFile.setFpcr(val);
}
// Most of the full system code and syscall emulation is not yet
// implemented. These functions do show what the final interface will
// look like.
#if FULL_SYSTEM
uint64_t *getIpr();
uint64_t readIpr(int idx, Fault &fault);
Fault setIpr(int idx, uint64_t val);
int readIntrFlag();
void setIntrFlag(int val);
Fault hwrei();
bool inPalMode() { return AlphaISA::PcPAL(this->regFile.readPC()); }
bool inPalMode(uint64_t PC)
{ return AlphaISA::PcPAL(PC); }
void trap(Fault fault);
bool simPalCheck(int palFunc);
void processInterrupts();
#endif
#if !FULL_SYSTEM
// Need to change these into regfile calls that directly set a certain
// register. Actually, these functions should handle most of this
// functionality by themselves; should look up the rename and then
// set the register.
IntReg getSyscallArg(int i)
{
return this->xc->regs.intRegFile[AlphaISA::ArgumentReg0 + i];
}
// used to shift args for indirect syscall
void setSyscallArg(int i, IntReg val)
{
this->xc->regs.intRegFile[AlphaISA::ArgumentReg0 + i] = val;
}
void setSyscallReturn(int64_t return_value)
{
// check for error condition. Alpha syscall convention is to
// indicate success/failure in reg a3 (r19) and put the
// return value itself in the standard return value reg (v0).
const int RegA3 = 19; // only place this is used
if (return_value >= 0) {
// no error
this->xc->regs.intRegFile[RegA3] = 0;
this->xc->regs.intRegFile[AlphaISA::ReturnValueReg] = return_value;
} else {
// got an error, return details
this->xc->regs.intRegFile[RegA3] = (IntReg) -1;
this->xc->regs.intRegFile[AlphaISA::ReturnValueReg] = -return_value;
}
}
void syscall(short thread_num);
void squashStages();
#endif
void copyToXC();
void copyFromXC();
public:
#if FULL_SYSTEM
bool palShadowEnabled;
// Not sure this is used anywhere.
void intr_post(RegFile *regs, Fault fault, Addr pc);
// Actually used within exec files. Implement properly.
void swapPALShadow(bool use_shadow);
// Called by CPU constructor. Can implement as I please.
void initCPU(RegFile *regs);
// Called by initCPU. Implement as I please.
void initIPRs(RegFile *regs);
void halt() { panic("Halt not implemented!\n"); }
#endif
template <class T>
Fault read(MemReqPtr &req, T &data)
{
#if FULL_SYSTEM && defined(TARGET_ALPHA)
if (req->flags & LOCKED) {
MiscRegFile *cregs = &req->xc->regs.miscRegs;
cregs->lock_addr = req->paddr;
cregs->lock_flag = true;
}
#endif
Fault error;
error = this->mem->read(req, data);
data = gtoh(data);
return error;
}
template <class T>
Fault read(MemReqPtr &req, T &data, int load_idx)
{
return this->iew.ldstQueue.read(req, data, load_idx);
}
template <class T>
Fault write(MemReqPtr &req, T &data)
{
#if FULL_SYSTEM && defined(TARGET_ALPHA)
MiscRegFile *cregs;
// If this is a store conditional, act appropriately
if (req->flags & LOCKED) {
cregs = &this->xc->regs.miscRegs;
if (req->flags & UNCACHEABLE) {
// Don't update result register (see stq_c in isa_desc)
req->result = 2;
req->xc->storeCondFailures = 0;//Needed? [RGD]
} else {
req->result = cregs->lock_flag;
if (!cregs->lock_flag ||
((cregs->lock_addr & ~0xf) != (req->paddr & ~0xf))) {
cregs->lock_flag = false;
if (((++req->xc->storeCondFailures) % 100000) == 0) {
std::cerr << "Warning: "
<< req->xc->storeCondFailures
<< " consecutive store conditional failures "
<< "on cpu " << this->cpu_id
<< std::endl;
}
return NoFault;
}
else req->xc->storeCondFailures = 0;
}
}
// Need to clear any locked flags on other proccessors for
// this address. Only do this for succsful Store Conditionals
// and all other stores (WH64?). Unsuccessful Store
// Conditionals would have returned above, and wouldn't fall
// through.
for (int i = 0; i < this->system->execContexts.size(); i++){
cregs = &this->system->execContexts[i]->regs.miscRegs;
if ((cregs->lock_addr & ~0xf) == (req->paddr & ~0xf)) {
cregs->lock_flag = false;
}
}
#endif
return this->mem->write(req, (T)htog(data));
}
template <class T>
Fault write(MemReqPtr &req, T &data, int store_idx)
{
return this->iew.ldstQueue.write(req, data, store_idx);
}
};
#endif // __CPU_O3_CPU_ALPHA_FULL_CPU_HH__
<|endoftext|> |
<commit_before>// Copyright (c) 2014 bushido
// Copyright (c) 2014 The Vertcoin developers
// Copyright (c) 2014 https://github.com/spesmilo/sx
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "stealth.h"
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/random/uniform_int_distribution.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/random_device.hpp>
hash_digest bitcoin_hash(const data_chunk& chunk)
{
hash_digest first_hash;
SHA256(chunk.data(), chunk.size(), first_hash.data());
hash_digest second_hash;
SHA256(first_hash.data(), first_hash.size(), second_hash.data());
// The hash is in the reverse of the expected order.
std::reverse(second_hash.begin(), second_hash.end());
return second_hash;
}
uint32_t bitcoin_checksum(const data_chunk& chunk)
{
hash_digest hash = bitcoin_hash(chunk);
return from_little_endian<uint32_t>(hash.rbegin());
}
void append_checksum(data_chunk& data)
{
uint32_t checksum = bitcoin_checksum(data);
extend_data(data, to_little_endian(checksum));
}
std::string stealth_address::encoded() const
{
data_chunk raw_addr;
raw_addr.push_back(stealth_version_byte);
raw_addr.push_back(options);
extend_data(raw_addr, scan_pubkey);
uint8_t number_spend_pubkeys = static_cast<uint8_t>(spend_pubkeys.size());
raw_addr.push_back(number_spend_pubkeys);
for (const ec_point& pubkey: spend_pubkeys)
extend_data(raw_addr, pubkey);
raw_addr.push_back(number_signatures);
//assert_msg(prefix.number_bits == 0, "Not yet implemented!");
raw_addr.push_back(0);
append_checksum(raw_addr);
return EncodeBase58(raw_addr);
}
bool verify_checksum(const data_chunk& data)
{
data_chunk body(data.begin(), data.end() - 4);
auto checksum = from_little_endian<uint32_t>(data.end() - 4);
return bitcoin_checksum(body) == checksum;
}
bool stealth_address::set_encoded(const std::string& encoded_address)
{
data_chunk raw_addr;
DecodeBase58(encoded_address, raw_addr);
if (!verify_checksum(raw_addr))
return false;
assert(raw_addr.size() >= 4);
auto checksum_begin = raw_addr.end() - 4;
// Delete checksum bytes.
raw_addr.erase(checksum_begin, raw_addr.end());
// https://wiki.unsystem.net/index.php/DarkWallet/Stealth#Address_format
// [version] [options] [scan_key] [N] ... [Nsigs] [prefix_length] ...
size_t estimated_data_size = 1 + 1 + 33 + 1 + 1 + 1;
assert(raw_addr.size() >= estimated_data_size);
auto iter = raw_addr.begin();
uint8_t version = *iter;
if (version != stealth_version_byte)
return false;
++iter;
options = *iter;
++iter;
auto scan_key_begin = iter;
iter += 33;
scan_pubkey = data_chunk(scan_key_begin, iter);
uint8_t number_spend_pubkeys = *iter;
++iter;
estimated_data_size += number_spend_pubkeys * 33;
assert(raw_addr.size() >= estimated_data_size);
for (size_t i = 0; i < number_spend_pubkeys; ++i)
{
auto spend_key_begin = iter;
iter += 33;
spend_pubkeys.emplace_back(data_chunk(spend_key_begin, iter));
}
number_signatures = *iter;
++iter;
prefix.number_bits = *iter;
++iter;
size_t number_bitfield_bytes = 0;
if (prefix.number_bits > 0)
number_bitfield_bytes = prefix.number_bits / 8 + 1;
estimated_data_size += number_bitfield_bytes;
assert(raw_addr.size() >= estimated_data_size);
// Unimplemented currently!
assert(number_bitfield_bytes == 0);
return true;
}
ec_secret generate_random_secret()
{
using namespace boost::random;
random_device rd;
mt19937 generator(rd());
uniform_int_distribution<uint8_t> dist(0, std::numeric_limits<uint8_t>::max());
ec_secret secret;
for (uint8_t& byte: secret)
byte = dist(generator);
return secret;
}
bool ec_multiply(ec_point& a, const ec_secret& b)
{
init.init();
return secp256k1_ecdsa_pubkey_tweak_mul(a.data(), a.size(), b.data());
}
hash_digest sha256_hash(const data_chunk& chunk)
{
hash_digest hash;
SHA256(chunk.data(), chunk.size(), hash.data());
return hash;
}
ec_secret shared_secret(const ec_secret& secret, ec_point point)
{
// diffie hellman stage
bool success = ec_multiply(point, secret);
assert(success);
// start the second stage
return sha256_hash(point);
}
bool ec_tweak_add(ec_point& a, const ec_secret& b)
{
init.init();
return secp256k1_ecdsa_pubkey_tweak_add(a.data(), a.size(), b.data());
}
ec_point secret_to_public_key(const ec_secret& secret,
bool compressed)
{
init.init();
size_t size = ec_uncompressed_size;
if (compressed)
size = ec_compressed_size;
ec_point out(size);
int out_size;
if (!secp256k1_ecdsa_pubkey_create(out.data(), &out_size, secret.data(),
compressed))
return ec_point();
assert(size == static_cast<size_t>(out_size));
return out;
}
ec_point initiate_stealth(
const ec_secret& ephem_secret, const ec_point& scan_pubkey,
const ec_point& spend_pubkey)
{
ec_point final = spend_pubkey;
// Generate shared secret
ec_secret shared = shared_secret(ephem_secret, scan_pubkey);
// Now generate address
bool success = ec_tweak_add(final, shared);
assert(success);
return final;
}
short_hash bitcoin_short_hash(const data_chunk& chunk)
{
hash_digest sha_hash;
SHA256(chunk.data(), chunk.size(), sha_hash.data());
short_hash ripemd_hash;
RIPEMD160(sha_hash.data(), sha_hash.size(), ripemd_hash.data());
return ripemd_hash;
}
void set_public_key(payment_address& address, const data_chunk& public_key)
{
address.set(fTestNet ? CBitcoinAddress::PUBKEY_ADDRESS_TEST : CBitcoinAddress::PUBKEY_ADDRESS,
bitcoin_short_hash(public_key));
}
payment_address::payment_address() : version_(invalid_version), hash_(null_short_hash)
{
}
payment_address::payment_address(uint8_t version, const short_hash& hash)
{
payment_address();
set(version, hash);
}
payment_address::payment_address(const std::string& encoded_address)
{
payment_address();
set_encoded(encoded_address);
}
void payment_address::set(uint8_t version, const short_hash& hash)
{
version_ = version;
hash_ = hash;
}
bool is_base58(const char c)
{
auto last = std::end(base58_chars) - 1;
// This works because the base58 characters happen to be in sorted order
return std::binary_search(base58_chars, last, c);
}
bool is_base58(const std::string& text)
{
return std::all_of(text.begin(), text.end(),
[](const char c){ return is_base58(c); });
}
bool payment_address::set_encoded(const std::string& encoded_address)
{
if (!is_base58(encoded_address))
return false;
data_chunk decoded_address;
DecodeBase58(encoded_address, decoded_address);
// version + 20 bytes short hash + 4 bytes checksum
if (decoded_address.size() != 25)
return false;
if (!verify_checksum(decoded_address))
return false;
version_ = decoded_address[0];
std::copy_n(decoded_address.begin() + 1, hash_.size(), hash_.begin());
return true;
}
std::string payment_address::encoded() const
{
data_chunk unencoded_address;
unencoded_address.reserve(25);
// Type, Hash, Checksum doth make thy address
unencoded_address.push_back(version_);
extend_data(unencoded_address, hash_);
append_checksum(unencoded_address);
assert(unencoded_address.size() == 25);
return EncodeBase58(unencoded_address);
}
ec_point uncover_stealth(
const ec_point& ephem_pubkey, const ec_secret& scan_secret,
const ec_point& spend_pubkey)
{
ec_point final = spend_pubkey;
ec_secret shared = shared_secret(scan_secret, ephem_pubkey);
bool success = ec_tweak_add(final, shared);
assert(success);
return final;
}
bool ec_add(ec_secret& a, const ec_secret& b)
{
init.init();
return secp256k1_ecdsa_privkey_tweak_add(a.data(), b.data());
}
ec_secret uncover_stealth_secret(
const ec_point& ephem_pubkey, const ec_secret& scan_secret,
const ec_secret& spend_secret)
{
ec_secret final = spend_secret;
ec_secret shared = shared_secret(scan_secret, ephem_pubkey);
bool success = ec_add(final, shared);
assert(success);
return final;
}
std::string secret_to_wif(const ec_secret& secret, bool compressed)
{
data_chunk data;
data.reserve(1 + hash_size + 1 + 4);
data.push_back(fTestNet ? CBitcoinSecret::PRIVKEY_ADDRESS_TEST : CBitcoinSecret::PRIVKEY_ADDRESS);
extend_data(data, secret);
if (compressed)
data.push_back(0x01);
append_checksum(data);
return EncodeBase58(data);
}
data_chunk decode_hex(std::string hex)
{
// Trim the fat.
boost::algorithm::trim(hex);
data_chunk result(hex.size() / 2);
for (size_t i = 0; i + 1 < hex.size(); i += 2)
{
assert(hex.size() - i >= 2);
auto byte_begin = hex.begin() + i;
auto byte_end = hex.begin() + i + 2;
// Perform conversion.
int val = -1;
std::stringstream converter;
converter << std::hex << std::string(byte_begin, byte_end);
converter >> val;
if (val == -1)
return data_chunk();
assert(val <= 0xff);
// Set byte.
result[i / 2] = val;
}
return result;
}
<commit_msg>Use secp256k1_ec_ prefix for non-ECDSA key operations See API change @ https://github.com/bitcoin/secp256k1/commit/ae6bc76e32016063a591399a7a2d7bac646603bc<commit_after>// Copyright (c) 2014 bushido
// Copyright (c) 2014 The Vertcoin developers
// Copyright (c) 2014 https://github.com/spesmilo/sx
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "stealth.h"
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/random/uniform_int_distribution.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/random_device.hpp>
hash_digest bitcoin_hash(const data_chunk& chunk)
{
hash_digest first_hash;
SHA256(chunk.data(), chunk.size(), first_hash.data());
hash_digest second_hash;
SHA256(first_hash.data(), first_hash.size(), second_hash.data());
// The hash is in the reverse of the expected order.
std::reverse(second_hash.begin(), second_hash.end());
return second_hash;
}
uint32_t bitcoin_checksum(const data_chunk& chunk)
{
hash_digest hash = bitcoin_hash(chunk);
return from_little_endian<uint32_t>(hash.rbegin());
}
void append_checksum(data_chunk& data)
{
uint32_t checksum = bitcoin_checksum(data);
extend_data(data, to_little_endian(checksum));
}
std::string stealth_address::encoded() const
{
data_chunk raw_addr;
raw_addr.push_back(stealth_version_byte);
raw_addr.push_back(options);
extend_data(raw_addr, scan_pubkey);
uint8_t number_spend_pubkeys = static_cast<uint8_t>(spend_pubkeys.size());
raw_addr.push_back(number_spend_pubkeys);
for (const ec_point& pubkey: spend_pubkeys)
extend_data(raw_addr, pubkey);
raw_addr.push_back(number_signatures);
//assert_msg(prefix.number_bits == 0, "Not yet implemented!");
raw_addr.push_back(0);
append_checksum(raw_addr);
return EncodeBase58(raw_addr);
}
bool verify_checksum(const data_chunk& data)
{
data_chunk body(data.begin(), data.end() - 4);
auto checksum = from_little_endian<uint32_t>(data.end() - 4);
return bitcoin_checksum(body) == checksum;
}
bool stealth_address::set_encoded(const std::string& encoded_address)
{
data_chunk raw_addr;
DecodeBase58(encoded_address, raw_addr);
if (!verify_checksum(raw_addr))
return false;
assert(raw_addr.size() >= 4);
auto checksum_begin = raw_addr.end() - 4;
// Delete checksum bytes.
raw_addr.erase(checksum_begin, raw_addr.end());
// https://wiki.unsystem.net/index.php/DarkWallet/Stealth#Address_format
// [version] [options] [scan_key] [N] ... [Nsigs] [prefix_length] ...
size_t estimated_data_size = 1 + 1 + 33 + 1 + 1 + 1;
assert(raw_addr.size() >= estimated_data_size);
auto iter = raw_addr.begin();
uint8_t version = *iter;
if (version != stealth_version_byte)
return false;
++iter;
options = *iter;
++iter;
auto scan_key_begin = iter;
iter += 33;
scan_pubkey = data_chunk(scan_key_begin, iter);
uint8_t number_spend_pubkeys = *iter;
++iter;
estimated_data_size += number_spend_pubkeys * 33;
assert(raw_addr.size() >= estimated_data_size);
for (size_t i = 0; i < number_spend_pubkeys; ++i)
{
auto spend_key_begin = iter;
iter += 33;
spend_pubkeys.emplace_back(data_chunk(spend_key_begin, iter));
}
number_signatures = *iter;
++iter;
prefix.number_bits = *iter;
++iter;
size_t number_bitfield_bytes = 0;
if (prefix.number_bits > 0)
number_bitfield_bytes = prefix.number_bits / 8 + 1;
estimated_data_size += number_bitfield_bytes;
assert(raw_addr.size() >= estimated_data_size);
// Unimplemented currently!
assert(number_bitfield_bytes == 0);
return true;
}
ec_secret generate_random_secret()
{
using namespace boost::random;
random_device rd;
mt19937 generator(rd());
uniform_int_distribution<uint8_t> dist(0, std::numeric_limits<uint8_t>::max());
ec_secret secret;
for (uint8_t& byte: secret)
byte = dist(generator);
return secret;
}
bool ec_multiply(ec_point& a, const ec_secret& b)
{
init.init();
return secp256k1_ec_pubkey_tweak_mul(a.data(), a.size(), b.data());
}
hash_digest sha256_hash(const data_chunk& chunk)
{
hash_digest hash;
SHA256(chunk.data(), chunk.size(), hash.data());
return hash;
}
ec_secret shared_secret(const ec_secret& secret, ec_point point)
{
// diffie hellman stage
bool success = ec_multiply(point, secret);
assert(success);
// start the second stage
return sha256_hash(point);
}
bool ec_tweak_add(ec_point& a, const ec_secret& b)
{
init.init();
return secp256k1_ec_pubkey_tweak_add(a.data(), a.size(), b.data());
}
ec_point secret_to_public_key(const ec_secret& secret,
bool compressed)
{
init.init();
size_t size = ec_uncompressed_size;
if (compressed)
size = ec_compressed_size;
ec_point out(size);
int out_size;
if (!secp256k1_ec_pubkey_create(out.data(), &out_size, secret.data(),
compressed))
return ec_point();
assert(size == static_cast<size_t>(out_size));
return out;
}
ec_point initiate_stealth(
const ec_secret& ephem_secret, const ec_point& scan_pubkey,
const ec_point& spend_pubkey)
{
ec_point final = spend_pubkey;
// Generate shared secret
ec_secret shared = shared_secret(ephem_secret, scan_pubkey);
// Now generate address
bool success = ec_tweak_add(final, shared);
assert(success);
return final;
}
short_hash bitcoin_short_hash(const data_chunk& chunk)
{
hash_digest sha_hash;
SHA256(chunk.data(), chunk.size(), sha_hash.data());
short_hash ripemd_hash;
RIPEMD160(sha_hash.data(), sha_hash.size(), ripemd_hash.data());
return ripemd_hash;
}
void set_public_key(payment_address& address, const data_chunk& public_key)
{
address.set(fTestNet ? CBitcoinAddress::PUBKEY_ADDRESS_TEST : CBitcoinAddress::PUBKEY_ADDRESS,
bitcoin_short_hash(public_key));
}
payment_address::payment_address() : version_(invalid_version), hash_(null_short_hash)
{
}
payment_address::payment_address(uint8_t version, const short_hash& hash)
{
payment_address();
set(version, hash);
}
payment_address::payment_address(const std::string& encoded_address)
{
payment_address();
set_encoded(encoded_address);
}
void payment_address::set(uint8_t version, const short_hash& hash)
{
version_ = version;
hash_ = hash;
}
bool is_base58(const char c)
{
auto last = std::end(base58_chars) - 1;
// This works because the base58 characters happen to be in sorted order
return std::binary_search(base58_chars, last, c);
}
bool is_base58(const std::string& text)
{
return std::all_of(text.begin(), text.end(),
[](const char c){ return is_base58(c); });
}
bool payment_address::set_encoded(const std::string& encoded_address)
{
if (!is_base58(encoded_address))
return false;
data_chunk decoded_address;
DecodeBase58(encoded_address, decoded_address);
// version + 20 bytes short hash + 4 bytes checksum
if (decoded_address.size() != 25)
return false;
if (!verify_checksum(decoded_address))
return false;
version_ = decoded_address[0];
std::copy_n(decoded_address.begin() + 1, hash_.size(), hash_.begin());
return true;
}
std::string payment_address::encoded() const
{
data_chunk unencoded_address;
unencoded_address.reserve(25);
// Type, Hash, Checksum doth make thy address
unencoded_address.push_back(version_);
extend_data(unencoded_address, hash_);
append_checksum(unencoded_address);
assert(unencoded_address.size() == 25);
return EncodeBase58(unencoded_address);
}
ec_point uncover_stealth(
const ec_point& ephem_pubkey, const ec_secret& scan_secret,
const ec_point& spend_pubkey)
{
ec_point final = spend_pubkey;
ec_secret shared = shared_secret(scan_secret, ephem_pubkey);
bool success = ec_tweak_add(final, shared);
assert(success);
return final;
}
bool ec_add(ec_secret& a, const ec_secret& b)
{
init.init();
return secp256k1_ec_privkey_tweak_add(a.data(), b.data());
}
ec_secret uncover_stealth_secret(
const ec_point& ephem_pubkey, const ec_secret& scan_secret,
const ec_secret& spend_secret)
{
ec_secret final = spend_secret;
ec_secret shared = shared_secret(scan_secret, ephem_pubkey);
bool success = ec_add(final, shared);
assert(success);
return final;
}
std::string secret_to_wif(const ec_secret& secret, bool compressed)
{
data_chunk data;
data.reserve(1 + hash_size + 1 + 4);
data.push_back(fTestNet ? CBitcoinSecret::PRIVKEY_ADDRESS_TEST : CBitcoinSecret::PRIVKEY_ADDRESS);
extend_data(data, secret);
if (compressed)
data.push_back(0x01);
append_checksum(data);
return EncodeBase58(data);
}
data_chunk decode_hex(std::string hex)
{
// Trim the fat.
boost::algorithm::trim(hex);
data_chunk result(hex.size() / 2);
for (size_t i = 0; i + 1 < hex.size(); i += 2)
{
assert(hex.size() - i >= 2);
auto byte_begin = hex.begin() + i;
auto byte_end = hex.begin() + i + 2;
// Perform conversion.
int val = -1;
std::stringstream converter;
converter << std::hex << std::string(byte_begin, byte_end);
converter >> val;
if (val == -1)
return data_chunk();
assert(val <= 0xff);
// Set byte.
result[i / 2] = val;
}
return result;
}
<|endoftext|> |
<commit_before>//==================================================
// Copyright (c) 2015 Deividas Kazlauskas
//
// See the file license.txt for copying permission.
//==================================================
/*
* =====================================================================================
*
* Filename: Sugar.hpp
*
* Description: Syntax sugar
*
* Version: 1.0
* Created: 07/07/2014 07:13:15 PM
* Compiler: gcc
*
* Author: David Kazlauskas (dk), david@templatious.org
*
* =====================================================================================
*/
#ifndef SUGAR_RISZR4GH
#define SUGAR_RISZR4GH
#include <templatious/CollectionAdapter.hpp>
#include <templatious/adapters/PtrAdapter.hpp>
#include <templatious/StaticFactory.hpp>
#include <templatious/StaticManipulator.hpp>
namespace templatious {
template <class T>
struct __ForeachCounter {
typedef T Iter;
Iter _i;
bool _keepGoing;
__ForeachCounter(const Iter i) : _i(i), _keepGoing(true) {}
Iter operator++() {
flipGoing();
return ++_i;
}
void flipGoing() {
_keepGoing = !_keepGoing;
}
Iter operator--() {
flipGoing();
return --_i;
}
};
/**
* Templatious foreach macro.
* @param var Loop variable name.
* @param col Collection to traverse.
*
* Example:
* ~~~~~~~
* std::vector<int> v;
* SA::add(v,1,3,5);
* // v contains {1,3,5}
*
* TEMPLATIOUS_FOREACH(auto& i,v) {
* std::cout << i << " ";
* i *= 2;
* }
*
* // prints out
* // 1 3 5
* // v now contains {2,6,10}
* ~~~~~~~
*/
#define TEMPLATIOUS_FOREACH(var,col) \
for (::templatious::__ForeachCounter<decltype(::templatious::StaticAdapter::begin(col))> \
__tmp_i(::templatious::StaticAdapter::begin(col)); \
__tmp_i._i != ::templatious::StaticAdapter::end(col) \
&& __tmp_i._keepGoing; \
++__tmp_i) \
for (var = *__tmp_i._i; ; ({__tmp_i.flipGoing();break;}))
/**
* 0 to N traversal.
* @param var Loop variable name (type is long)
* @param to Number to traverse to
*
* Example:
* ~~~~~~~
* int sumA = 0;
* int sumB = 0;
*
* for (int i = 0; i < 10; ++i) {
* sumA += i;
* }
*
* TEMPLATIOUS_0_TO_N(i,10) {
* sumB += i;
* }
*
* assert( sumA == sumB );
* ~~~~~~~
*/
#define TEMPLATIOUS_0_TO_N(var,to) \
for (long var = 0; var < to; ++var)
/**
* Repeat underlying block of code n times.
*
* Example:
* ~~~~~~~
* int count = 0;
* TEMPLATIOUS_REPEAT( 7 ) {
* ++count;
* }
* assert( count == 7 );
* ~~~~~~~
*/
#define TEMPLATIOUS_REPEAT(n) \
for (long __tmp_i = 0; __tmp_i < n; ++__tmp_i)
#define TEMPLATIOUS_TRIPLET(AdName,FactName,ManipName) \
typedef templatious::StaticAdapter AdName;\
typedef templatious::StaticFactory FactName;\
typedef templatious::StaticManipulator ManipName;
/**
* Macro to define main three templatious classes:
* templatious::StaticAdapter
* templatious::StaticFactory
* templatious::StaticManipulator
*
* Expands to:
* ~~~~~~~
* typedef templatious::StaticAdapter SA;
* typedef templatious::StaticFactory SF;
* typedef templatious::StaticManipulator SM;
* ~~~~~~~
*/
#define TEMPLATIOUS_TRIPLET_STD TEMPLATIOUS_TRIPLET(SA,SF,SM)
#define TEMPLATIOUS_VPCORE templatious::VirtualPackCore
#define TEMPLATIOUS_CALLEACH_FCTOR(name, expr) \
TEMPLATIOUS_TRIPLET_STD;\
struct name {\
template <class T>\
void operator()(T&& i) {\
expr;\
}\
};
/**
* Define a functor class with storage to be
* and arbitrary signature to be passed into
* SM::callEach. Needed if packs contain
* different types of variables and C++11 lambda
* expression does not suffice.
* If you happen to be on C++14
* just use lambda expression with auto
* parameter type instead.
*
* @param name Name of the instantiated struct.
* @param expr Expression to perform when called.
* _c is the storage variable while i is the
* loop variable.
*
* Example:
* ~~~~~~~
* TEMPLATIOUS_CALLEACH_FCTOR_WSTOR(SumFctor, _c += i);
*
* ...
*
* auto pack = SF::pack(1,2,3,4);
*
* SumFctor<int> sf(0);
* SM::callEach(sf,pack);
*
* int expSum = 1 + 2 + 3 + 4;
* assert( sf._c == expSum );
* ~~~~~~~
*/
#define TEMPLATIOUS_CALLEACH_FCTOR_WSTOR(name, expr) \
TEMPLATIOUS_TRIPLET_STD;\
template <class StorType>\
struct name {\
name(const StorType& t) : _c(t) {}\
name() {}\
template <class T>\
bool operator()(T&& i) {\
expr;\
return true;\
}\
StorType _c;\
};
}
#endif /* end of include guard: SUGAR_RISZR4GH */
<commit_msg>sugar done<commit_after>//==================================================
// Copyright (c) 2015 Deividas Kazlauskas
//
// See the file license.txt for copying permission.
//==================================================
/*
* =====================================================================================
*
* Filename: Sugar.hpp
*
* Description: Syntax sugar
*
* Version: 1.0
* Created: 07/07/2014 07:13:15 PM
* Compiler: gcc
*
* Author: David Kazlauskas (dk), david@templatious.org
*
* =====================================================================================
*/
#ifndef SUGAR_RISZR4GH
#define SUGAR_RISZR4GH
#include <templatious/CollectionAdapter.hpp>
#include <templatious/adapters/PtrAdapter.hpp>
#include <templatious/StaticFactory.hpp>
#include <templatious/StaticManipulator.hpp>
namespace templatious {
template <class T>
struct __ForeachCounter {
typedef T Iter;
Iter _i;
bool _keepGoing;
__ForeachCounter(const Iter i) : _i(i), _keepGoing(true) {}
Iter operator++() {
flipGoing();
return ++_i;
}
void flipGoing() {
_keepGoing = !_keepGoing;
}
Iter operator--() {
flipGoing();
return --_i;
}
};
/**
* Templatious foreach macro.
* @param var Loop variable name.
* @param col Collection to traverse.
*
* Example:
* ~~~~~~~
* std::vector<int> v;
* SA::add(v,1,3,5);
* // v contains {1,3,5}
*
* TEMPLATIOUS_FOREACH(auto& i,v) {
* std::cout << i << " ";
* i *= 2;
* }
*
* // prints out
* // 1 3 5
* // v now contains {2,6,10}
* ~~~~~~~
*/
#define TEMPLATIOUS_FOREACH(var,col) \
for (::templatious::__ForeachCounter<decltype(::templatious::StaticAdapter::begin(col))> \
__tmp_i(::templatious::StaticAdapter::begin(col)); \
__tmp_i._i != ::templatious::StaticAdapter::end(col) \
&& __tmp_i._keepGoing; \
++__tmp_i) \
for (var = *__tmp_i._i; ; ({__tmp_i.flipGoing();break;}))
/**
* 0 to N traversal.
* @param var Loop variable name (type is long)
* @param to Number to traverse to
*
* Example:
* ~~~~~~~
* int sumA = 0;
* int sumB = 0;
*
* for (int i = 0; i < 10; ++i) {
* sumA += i;
* }
*
* TEMPLATIOUS_0_TO_N(i,10) {
* sumB += i;
* }
*
* assert( sumA == sumB );
* ~~~~~~~
*/
#define TEMPLATIOUS_0_TO_N(var,to) \
for (long var = 0; var < to; ++var)
/**
* Repeat underlying block of code n times.
*
* Example:
* ~~~~~~~
* int count = 0;
* TEMPLATIOUS_REPEAT( 7 ) {
* ++count;
* }
* assert( count == 7 );
* ~~~~~~~
*/
#define TEMPLATIOUS_REPEAT(n) \
for (long __tmp_i = 0; __tmp_i < n; ++__tmp_i)
#define TEMPLATIOUS_TRIPLET(AdName,FactName,ManipName) \
typedef templatious::StaticAdapter AdName;\
typedef templatious::StaticFactory FactName;\
typedef templatious::StaticManipulator ManipName;
/**
* Macro to define main three templatious classes:
* templatious::StaticAdapter
* templatious::StaticFactory
* templatious::StaticManipulator
*
* Expands to:
* ~~~~~~~
* typedef templatious::StaticAdapter SA;
* typedef templatious::StaticFactory SF;
* typedef templatious::StaticManipulator SM;
* ~~~~~~~
*/
#define TEMPLATIOUS_TRIPLET_STD TEMPLATIOUS_TRIPLET(SA,SF,SM)
#define TEMPLATIOUS_VPCORE templatious::VirtualPackCore
/**
* Define a functor class to be
* used with arbitrary type signature when passed into
* SM::callEach. Needed if packs contain
* different types of variables and C++11 lambda
* expression does not suffice.
* If you happen to be on C++14
* just use lambda expression with auto
* parameter type instead.
*
* @param name Name of the instantiated struct.
* @param expr Expression to perform when called,
* i is the loop variable.
*
* Example:
* ~~~~~~~
* TEMPLATIOUS_CALLEACH_FCTOR(PrintFctor,{
* std::cout << i << " ";
* });
*
* ...
*
* auto pack = SF::pack(1,2.2,"3.3",std::string("4.4"));
*
* PrintFctor sf;
* SM::callEach(sf,pack);
*
* // prints out
* // 1 2.2 3.3 4.4
* ~~~~~~~
*/
#define TEMPLATIOUS_CALLEACH_FCTOR(name, expr) \
TEMPLATIOUS_TRIPLET_STD;\
struct name {\
template <class T>\
void operator()(T&& i) {\
expr;\
}\
};
/**
* Define a functor class with storage to be
* used with arbitrary type signature when passed into
* SM::callEach. Needed if packs contain
* different types of variables and C++11 lambda
* expression does not suffice.
* If you happen to be on C++14
* just use lambda expression with auto
* parameter type instead.
*
* @param name Name of the instantiated struct.
* @param expr Expression to perform when called.
* _c is the storage variable while i is the
* loop variable.
*
* Example:
* ~~~~~~~
* TEMPLATIOUS_CALLEACH_FCTOR_WSTOR(SumFctor, _c += i);
*
* ...
*
* auto pack = SF::pack(1,2,3,4);
*
* SumFctor<int> sf(0);
* SM::callEach(sf,pack);
*
* int expSum = 1 + 2 + 3 + 4;
* assert( sf._c == expSum );
* ~~~~~~~
*/
#define TEMPLATIOUS_CALLEACH_FCTOR_WSTOR(name, expr) \
TEMPLATIOUS_TRIPLET_STD;\
template <class StorType>\
struct name {\
name(const StorType& t) : _c(t) {}\
name() {}\
template <class T>\
bool operator()(T&& i) {\
expr;\
return true;\
}\
StorType _c;\
};
}
#endif /* end of include guard: SUGAR_RISZR4GH */
<|endoftext|> |
<commit_before>#pragma once
#include "util.cpp"
#include <set>
struct Coord {
int r, c, h;
};
bool operator < (const Coord &a, const Coord &b) {
if (a.r != b.r)
return a.r < b.r;
else if (a.c != b.c)
return a.c < b.c;
else
return a.h < b.h;
}
void check_cell(Input &input, Coord cur, vector<Coord>& path, vector<int>& prev, set<Coord>& visited, vector<int>& dist, int idx) {
//cerr << "adding balloon: " << cur.r << ' ' << cur.c << ' ' << cur.h << endl;
int dr = input.movement_r[cur.r][cur.c][cur.h];
int dc = input.movement_c[cur.r][cur.c][cur.h];
cur.r += dr;
cur.c += dc;
cur.c = (cur.c + input.c) % input.c;
//cerr << "done\n";
if (visited.find(cur) != visited.end())
return;
path.push_back(cur);
prev.push_back(idx);
dist.push_back(dist[idx]+1);
visited.insert(cur);
}
void bfs(Input &input, vector<Coord>& path, vector<int>& prev) {
set<Coord> visited;
vector<int> dist;
int idx = 0;
dist.push_back(idx);
visited.insert(path[idx]);
while (idx < path.size()) {
Coord cur = path[idx];
//cerr << "current balloon: " << cur.r << ' ' << cur.c << ' ' << cur.h << endl;
if (dist[idx] > 5)
break;
// out of bounds -> stay there
if (cur.r >= input.r || cur.r < 0) {
path.push_back(cur);
prev.push_back(idx);
dist.push_back(dist[idx]+1);
}
// try changing the altitude
else {
check_cell(input,cur,path,prev,visited,dist,idx);
if (cur.h > 1)
{
cur.h--;
check_cell(input,cur,path,prev,visited,dist,idx);
cur.h++;
}
if (cur.h < input.a)
{
cur.h++;
check_cell(input,cur,path,prev,visited,dist,idx);
cur.h--;
}
}
idx++;
}
}
void pathfinding(Input& input, int balloon, double r, double c, int delta) {
//TODO fill me
vector<Coord> path;
vector<int> prev;
// add starting cell
Coord start;
start.r = input.balloons[balloon].r.back();
start.c = input.balloons[balloon].c.back();
start.h = input.balloons[balloon].h.back();
path.push_back(start);
prev.push_back(-1);
//run bfs
bfs(input,path,prev);
// choose the closest end point
double mind = 1e9, curd;
int idx_min;
for (int i = 0; i < path.size(); i++)
{
curd = ((double)path[i].r-r)*((double)path[i].r-r) + ((double)path[i].c-c)*((double)path[i].c-c);
if (curd < mind)
{
idx_min = i;
mind = curd;
}
}
vector<Coord> reversed_path;
for (int i = idx_min; i != 0; i = prev[i])
reversed_path.push_back(path[i]);
/*cerr << "flying from: " << start.r << ' ' << start.c << ' ' << start.h << endl;
cerr << "path\n";
for (int i = reversed_path.size()-1; i >= 0; i--)
cerr << reversed_path[i].r << ' ' << reversed_path[i].c << ' ' << reversed_path[i].h << endl;
cerr << "end of path\n";*/
for (int i = reversed_path.size()-1; i >= 0; i--)
{
input.balloons[balloon].h.push_back(reversed_path[i].h);
input.balloons[balloon].r.push_back(reversed_path[i].r);
input.balloons[balloon].c.push_back(reversed_path[i].c);
if (input.balloons[balloon].h.size() > input.t)
break;
}
}
<commit_msg>pathfinding small change<commit_after>#pragma once
#include "util.cpp"
#include <set>
struct Coord {
int r, c, h;
};
bool operator < (const Coord &a, const Coord &b) {
if (a.r != b.r)
return a.r < b.r;
else if (a.c != b.c)
return a.c < b.c;
else
return a.h < b.h;
}
void check_cell(Input &input, Coord cur, vector<Coord>& path, vector<int>& prev, set<Coord>& visited, vector<int>& dist, int idx) {
//cerr << "adding balloon: " << cur.r << ' ' << cur.c << ' ' << cur.h << endl;
int dr = input.movement_r[cur.r][cur.c][cur.h];
int dc = input.movement_c[cur.r][cur.c][cur.h];
cur.r += dr;
cur.c += dc;
cur.c = (cur.c + input.c) % input.c;
//cerr << "done\n";
if (visited.find(cur) != visited.end())
return;
path.push_back(cur);
prev.push_back(idx);
dist.push_back(dist[idx]+1);
visited.insert(cur);
}
void bfs(Input &input, vector<Coord>& path, vector<int>& prev) {
set<Coord> visited;
vector<int> dist;
int idx = 0;
dist.push_back(idx);
visited.insert(path[idx]);
while (idx < path.size()) {
Coord cur = path[idx];
//cerr << "current balloon: " << cur.r << ' ' << cur.c << ' ' << cur.h << endl;
if (dist[idx] > 5)
break;
// out of bounds -> stay there
if (cur.r >= input.r || cur.r < 0) {
path.push_back(cur);
prev.push_back(idx);
dist.push_back(dist[idx]+1);
}
// try changing the altitude
else {
check_cell(input,cur,path,prev,visited,dist,idx);
if (cur.h > 1)
{
cur.h--;
check_cell(input,cur,path,prev,visited,dist,idx);
cur.h++;
}
if (cur.h < input.a)
{
cur.h++;
check_cell(input,cur,path,prev,visited,dist,idx);
cur.h--;
}
}
idx++;
}
}
void pathfinding(Input& input, int balloon, double r, double c, int delta) {
//TODO fill me
vector<Coord> path;
vector<int> prev;
// add starting cell
Coord start;
start.r = input.balloons[balloon].r.back();
start.c = input.balloons[balloon].c.back();
start.h = input.balloons[balloon].h.back();
path.push_back(start);
prev.push_back(-1);
//run bfs
bfs(input,path,prev);
// choose the closest end point
double mind = 1e9, curd;
int idx_min = 1;
for (int i = 0; i < path.size(); i++)
{
curd = ((double)path[i].r-r)*((double)path[i].r-r) + ((double)path[i].c-c)*((double)path[i].c-c);
if (curd < mind)
{
idx_min = i;
mind = curd;
}
}
vector<Coord> reversed_path;
for (int i = idx_min; i != 0; i = prev[i])
reversed_path.push_back(path[i]);
/*cerr << "flying from: " << start.r << ' ' << start.c << ' ' << start.h << endl;
cerr << "path\n";
for (int i = reversed_path.size()-1; i >= 0; i--)
cerr << reversed_path[i].r << ' ' << reversed_path[i].c << ' ' << reversed_path[i].h << endl;
cerr << "end of path\n";*/
for (int i = reversed_path.size()-1; i >= 0; i--)
{
input.balloons[balloon].h.push_back(reversed_path[i].h);
input.balloons[balloon].r.push_back(reversed_path[i].r);
input.balloons[balloon].c.push_back(reversed_path[i].c);
if (input.balloons[balloon].h.size() > input.t)
break;
}
}
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief ソフトウェア SPI テンプレートクラス
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2016, 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/R8C/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdint>
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ソフトウェア SPI テンプレートクラス
@param[in] CLK クロック・クラス
@param[in] OUT 出力・クラス
@param[in] INP 入力・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class CLK, class OUT, class INP>
class spi_io {
uint8_t delay_;
inline void clock_() {
uint8_t n = delay_;
while(n > 3) { --n; asm("nop"); }
CLK::P = 1;
n = delay_;
while(n > 0) { --n; asm("nop"); }
CLK::P = 0;
}
inline void send_(uint8_t d) {
if(d & 0x80) OUT::P = 1; else OUT::P = 0; /* bit7 */
clock_();
if(d & 0x40) OUT::P = 1; else OUT::P = 0; /* bit6 */
clock_();
if(d & 0x20) OUT::P = 1; else OUT::P = 0; /* bit5 */
clock_();
if(d & 0x10) OUT::P = 1; else OUT::P = 0; /* bit4 */
clock_();
if(d & 0x08) OUT::P = 1; else OUT::P = 0; /* bit3 */
clock_();
if(d & 0x04) OUT::P = 1; else OUT::P = 0; /* bit2 */
clock_();
if(d & 0x02) OUT::P = 1; else OUT::P = 0; /* bit1 */
clock_();
if(d & 0x01) OUT::P = 1; else OUT::P = 0; /* bit0 */
clock_();
}
inline uint8_t recv_(bool out = 1) {
OUT::P = out;
uint8_t r = 0;
if(INP::P()) ++r; // bit7
clock_();
r <<= 1; if(INP::P()) ++r; // bit6
clock_();
r <<= 1; if(INP::P()) ++r; // bit5
clock_();
r <<= 1; if(INP::P()) ++r; // bit4
clock_();
r <<= 1; if(INP::P()) ++r; // bit3
clock_();
r <<= 1; if(INP::P()) ++r; // bit2
clock_();
r <<= 1; if(INP::P()) ++r; // bit1
clock_();
r <<= 1; if(INP::P()) ++r; // bit0
clock_();
return r;
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
spi_io() : delay_(0) { }
//-----------------------------------------------------------------//
/*!
@brief 開始
@param[in] delay クロック遅延(速度)
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool start(uint8_t delay = 0) {
delay_ = delay;
CLK::DIR = 1;
OUT::DIR = 1;
INP::DIR = 0;
return true;
}
//----------------------------------------------------------------//
/*!
@brief リード
@return 読み出しデータ
*/
//----------------------------------------------------------------//
uint8_t xchg() { return recv_(); }
//----------------------------------------------------------------//
/*!
@brief リード・ライト
@param[in] d 書き込みデータ
@return 読み出しデータ
*/
//----------------------------------------------------------------//
uint8_t xchg(uint8_t d)
{
uint8_t r = 0;
if(INP::P()) ++r; // bit7
if(d & 0x80) OUT::P = 1; else OUT::P = 0; // bit7
clock_();
r <<= 1;
if(INP::P()) ++r; // bit6
if(d & 0x40) OUT::P = 1; else OUT::P = 0; // bit6
clock_();
r <<= 1;
if(INP::P()) ++r; // bit5
if(d & 0x20) OUT::P = 1; else OUT::P = 0; // bit5
clock_();
r <<= 1;
if(INP::P()) ++r; // bit4
if(d & 0x10) OUT::P = 1; else OUT::P = 0; // bit4
clock_();
r <<= 1;
if(INP::P()) ++r; // bit3
if(d & 0x08) OUT::P = 1; else OUT::P = 0; // bit3
clock_();
r <<= 1;
if(INP::P()) ++r; // bit2
if(d & 0x04) OUT::P = 1; else OUT::P = 0; // bit2
clock_();
r <<= 1;
if(INP::P()) ++r; // bit1
if(d & 0x02) OUT::P = 1; else OUT::P = 0; // bit1
clock_();
r <<= 1;
if(INP::P()) ++r; // bit0
if(d & 0x01) OUT::P = 1; else OUT::P = 0; // bit0
clock_();
return r;
}
//----------------------------------------------------------------//
/*!
@brief スキップ
@param[in] count スキップ数
*/
//----------------------------------------------------------------//
void skip(uint16_t count = 1) {
OUT::P = 1;
while(count > 0) {
clock_();
clock_();
clock_();
clock_();
clock_();
clock_();
clock_();
clock_();
--count;
}
}
//-----------------------------------------------------------------//
/*!
@brief シリアル送信
@param[in] src 送信ソース
@param[in] size 送信サイズ
*/
//-----------------------------------------------------------------//
void send(const uint8_t* src, uint16_t size)
{
auto end = src + size;
while(src < end) {
send_(*src);
++src;
}
}
//-----------------------------------------------------------------//
/*!
@brief シリアル受信
@param[out] dst 受信先
@param[in] cnt 受信サイズ
*/
//-----------------------------------------------------------------//
void recv(uint8_t* dst, uint16_t size)
{
auto end = dst + size;
while(dst < end) {
*dst = recv_();
++dst;
}
}
};
}
<commit_msg>update pointer type<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief ソフトウェア SPI テンプレートクラス
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2016, 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/R8C/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdint>
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ソフトウェア SPI テンプレートクラス
@param[in] CLK クロック・クラス
@param[in] OUT 出力・クラス
@param[in] INP 入力・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class CLK, class OUT, class INP>
class spi_io {
uint8_t delay_;
inline void clock_() {
uint8_t n = delay_;
while(n > 3) { --n; asm("nop"); }
CLK::P = 1;
n = delay_;
while(n > 0) { --n; asm("nop"); }
CLK::P = 0;
}
inline void send_(uint8_t d) {
if(d & 0x80) OUT::P = 1; else OUT::P = 0; /* bit7 */
clock_();
if(d & 0x40) OUT::P = 1; else OUT::P = 0; /* bit6 */
clock_();
if(d & 0x20) OUT::P = 1; else OUT::P = 0; /* bit5 */
clock_();
if(d & 0x10) OUT::P = 1; else OUT::P = 0; /* bit4 */
clock_();
if(d & 0x08) OUT::P = 1; else OUT::P = 0; /* bit3 */
clock_();
if(d & 0x04) OUT::P = 1; else OUT::P = 0; /* bit2 */
clock_();
if(d & 0x02) OUT::P = 1; else OUT::P = 0; /* bit1 */
clock_();
if(d & 0x01) OUT::P = 1; else OUT::P = 0; /* bit0 */
clock_();
}
inline uint8_t recv_(bool out = 1) {
OUT::P = out;
uint8_t r = 0;
if(INP::P()) ++r; // bit7
clock_();
r <<= 1; if(INP::P()) ++r; // bit6
clock_();
r <<= 1; if(INP::P()) ++r; // bit5
clock_();
r <<= 1; if(INP::P()) ++r; // bit4
clock_();
r <<= 1; if(INP::P()) ++r; // bit3
clock_();
r <<= 1; if(INP::P()) ++r; // bit2
clock_();
r <<= 1; if(INP::P()) ++r; // bit1
clock_();
r <<= 1; if(INP::P()) ++r; // bit0
clock_();
return r;
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
spi_io() : delay_(0) { }
//-----------------------------------------------------------------//
/*!
@brief 開始
@param[in] delay クロック遅延(速度)
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool start(uint8_t delay = 0) {
delay_ = delay;
CLK::DIR = 1;
OUT::DIR = 1;
INP::DIR = 0;
return true;
}
//----------------------------------------------------------------//
/*!
@brief リード
@return 読み出しデータ
*/
//----------------------------------------------------------------//
uint8_t xchg() { return recv_(); }
//----------------------------------------------------------------//
/*!
@brief リード・ライト
@param[in] d 書き込みデータ
@return 読み出しデータ
*/
//----------------------------------------------------------------//
uint8_t xchg(uint8_t d)
{
uint8_t r = 0;
if(INP::P()) ++r; // bit7
if(d & 0x80) OUT::P = 1; else OUT::P = 0; // bit7
clock_();
r <<= 1;
if(INP::P()) ++r; // bit6
if(d & 0x40) OUT::P = 1; else OUT::P = 0; // bit6
clock_();
r <<= 1;
if(INP::P()) ++r; // bit5
if(d & 0x20) OUT::P = 1; else OUT::P = 0; // bit5
clock_();
r <<= 1;
if(INP::P()) ++r; // bit4
if(d & 0x10) OUT::P = 1; else OUT::P = 0; // bit4
clock_();
r <<= 1;
if(INP::P()) ++r; // bit3
if(d & 0x08) OUT::P = 1; else OUT::P = 0; // bit3
clock_();
r <<= 1;
if(INP::P()) ++r; // bit2
if(d & 0x04) OUT::P = 1; else OUT::P = 0; // bit2
clock_();
r <<= 1;
if(INP::P()) ++r; // bit1
if(d & 0x02) OUT::P = 1; else OUT::P = 0; // bit1
clock_();
r <<= 1;
if(INP::P()) ++r; // bit0
if(d & 0x01) OUT::P = 1; else OUT::P = 0; // bit0
clock_();
return r;
}
//----------------------------------------------------------------//
/*!
@brief スキップ
@param[in] count スキップ数
*/
//----------------------------------------------------------------//
void skip(uint16_t count = 1) {
OUT::P = 1;
while(count > 0) {
clock_();
clock_();
clock_();
clock_();
clock_();
clock_();
clock_();
clock_();
--count;
}
}
//-----------------------------------------------------------------//
/*!
@brief シリアル送信
@param[in] src 送信ソース
@param[in] size 送信サイズ
*/
//-----------------------------------------------------------------//
void send(const void* src, uint16_t size)
{
const uint8_t* p = static_cast<const uint8_t*>(src);
auto end = p + size;
while(p < end) {
send_(*p);
++p;
}
}
//-----------------------------------------------------------------//
/*!
@brief シリアル受信
@param[out] dst 受信先
@param[in] cnt 受信サイズ
*/
//-----------------------------------------------------------------//
void recv(void* dst, uint16_t size)
{
uint8_t* p = static_cast<uint8_t*>(dst);
auto end = p + size;
while(p < end) {
*p = recv_();
++p;
}
}
};
}
<|endoftext|> |
<commit_before>#pragma ident "$Id: $"
/**
* @file NetworkObsStreams.cpp
* This class synchronizes rinex observation data streams.
*/
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// any later version.
//
// The GPSTk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Wei Yan - Chinese Academy of Sciences . 2009, 2010
//
//============================================================================
#include "NetworkObsStreams.hpp"
#include "RinexObsHeader.hpp"
namespace gpstk
{
// Add a rinex obs file to the network
// @obsFile Rinex observation file name
bool NetworkObsStreams::addRinexObsFile(const std::string& obsFile)
{
// object to hold the data
ObsData oData;
oData.obsFile = obsFile;
try
{
// allocate memory
oData.pObsStream = new RinexObsStream();
if(!oData.pObsStream)
{
// Failed to allocate memory
return false;
}
// Open the file
oData.pObsStream->exceptions(ios::failbit);
oData.pObsStream->open(oData.obsFile, std::ios::in);
// We reader the header of the obs file
RinexObsHeader obsHeader;
(*oData.pObsStream) >> obsHeader;
// Try to get the SourceID of the receiver
gnssRinex gRin;
obsHeader >> gRin;
oData.obsSource = gRin.header.source;
// Now, we should store the data for the receiver
allStreamData.push_back(oData);
mapSourceStream[gRin.header.source] = oData.pObsStream;
referenceSource = gRin.header.source;
return true;
}
catch(...)
{
// Problem opening the file
// Maybe it doesn't exist or you don't have proper read permissions
// We have to deallocate the memory here
delete oData.pObsStream;
oData.pObsStream = (RinexObsStream*)0;
return false;
}
} // End of method 'NetworkObsStreams::addRinexObsFile()'
// Get epoch data of the network
// @gdsMap Object hold epoch observation data of the network
// @return Is there more epoch data for the network
bool NetworkObsStreams::readEpochData(gnssDataMap& gdsMap)
throw(SynchronizeException)
{
// First, We clear the data map
gdsMap.clear();
RinexObsStream* pRefObsStream = mapSourceStream[referenceSource];
gnssRinex gRef;
if( (*pRefObsStream) >> gRef )
{
gdsMap.addGnssRinex(gRef);
std::map<SourceID, RinexObsStream*>::iterator it;
for( it = mapSourceStream.begin();
it != mapSourceStream.end();
++it)
{
if( it->first == referenceSource) continue;
Synchronize synchro( (*(*it).second), gRef);
gnssRinex gRin;
try
{
gRin >> synchro;
gdsMap.addGnssRinex(gRin);
}
catch(...)
{
if(synchronizeException)
{
stringstream ss;
ss << "Exception when try to synchronize at epoch: "
<< gRef.header.epoch << endl;
SynchronizeException e(ss.str());
GPSTK_THROW(e);
}
}
} // End of 'for(std::map<SourceID, RinexObsStream*>::iterator it;
return true;
} // End of 'if( (*pRefObsStream) >> gRef )'
return false;
} // End of method 'NetworkObsStreams::readEpochData()'
// do some clean operation
void NetworkObsStreams::cleanUp()
{
mapSourceStream.clear();
std::list<ObsData>::iterator it;
for( it = allStreamData.begin();
it != allStreamData.end();
++it)
{
it->pObsStream->close();
delete it->pObsStream;
it->pObsStream = (RinexObsStream*)0;
}
allStreamData.clear();
} // End of method 'NetworkObsStreams::cleanUp()'
// Get the SourceID of the rinex observation file
SourceID NetworkObsStreams::sourceIDOfRinexObsFile(std::string obsFile)
{
try
{
RinexObsStream rin;
rin.exceptions(ios::failbit);
rin.open(obsFile, std::ios::in);
gnssRinex gRin;
rin >> gRin;
rin.close();
return gRin.header.source;
}
catch(...)
{
// Problem opening the file
// Maybe it doesn't exist or you don't have proper read permissions
Exception e("Problem opening the file "
+ obsFile
+ "Maybe it doesn't exist or you don't have proper read permissions");
GPSTK_THROW(e);
}
} // End of method 'NetworkObsStreams::sourceIDOfRinexObsFile'
} // End of namespace gpstk
<commit_msg>Added some missing 'std::' prefixes to 'NetworkObsStreams.cpp' file, which were preventing proper compilation in ANSI C++ compilers.<commit_after>#pragma ident "$Id: $"
/**
* @file NetworkObsStreams.cpp
* This class synchronizes rinex observation data streams.
*/
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// any later version.
//
// The GPSTk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Wei Yan - Chinese Academy of Sciences . 2009, 2010
//
//============================================================================
#include "NetworkObsStreams.hpp"
#include "RinexObsHeader.hpp"
namespace gpstk
{
// Add a rinex obs file to the network
// @obsFile Rinex observation file name
bool NetworkObsStreams::addRinexObsFile(const std::string& obsFile)
{
// object to hold the data
ObsData oData;
oData.obsFile = obsFile;
try
{
// allocate memory
oData.pObsStream = new RinexObsStream();
if(!oData.pObsStream)
{
// Failed to allocate memory
return false;
}
// Open the file
oData.pObsStream->exceptions(std::ios::failbit);
oData.pObsStream->open(oData.obsFile, std::ios::in);
// We reader the header of the obs file
RinexObsHeader obsHeader;
(*oData.pObsStream) >> obsHeader;
// Try to get the SourceID of the receiver
gnssRinex gRin;
obsHeader >> gRin;
oData.obsSource = gRin.header.source;
// Now, we should store the data for the receiver
allStreamData.push_back(oData);
mapSourceStream[gRin.header.source] = oData.pObsStream;
referenceSource = gRin.header.source;
return true;
}
catch(...)
{
// Problem opening the file
// Maybe it doesn't exist or you don't have proper read permissions
// We have to deallocate the memory here
delete oData.pObsStream;
oData.pObsStream = (RinexObsStream*)0;
return false;
}
} // End of method 'NetworkObsStreams::addRinexObsFile()'
// Get epoch data of the network
// @gdsMap Object hold epoch observation data of the network
// @return Is there more epoch data for the network
bool NetworkObsStreams::readEpochData(gnssDataMap& gdsMap)
throw(SynchronizeException)
{
// First, We clear the data map
gdsMap.clear();
RinexObsStream* pRefObsStream = mapSourceStream[referenceSource];
gnssRinex gRef;
if( (*pRefObsStream) >> gRef )
{
gdsMap.addGnssRinex(gRef);
std::map<SourceID, RinexObsStream*>::iterator it;
for( it = mapSourceStream.begin();
it != mapSourceStream.end();
++it)
{
if( it->first == referenceSource) continue;
Synchronize synchro( (*(*it).second), gRef);
gnssRinex gRin;
try
{
gRin >> synchro;
gdsMap.addGnssRinex(gRin);
}
catch(...)
{
if(synchronizeException)
{
std::stringstream ss;
ss << "Exception when try to synchronize at epoch: "
<< gRef.header.epoch << std::endl;
SynchronizeException e(ss.str());
GPSTK_THROW(e);
}
}
} // End of 'for(std::map<SourceID, RinexObsStream*>::iterator it;
return true;
} // End of 'if( (*pRefObsStream) >> gRef )'
return false;
} // End of method 'NetworkObsStreams::readEpochData()'
// do some clean operation
void NetworkObsStreams::cleanUp()
{
mapSourceStream.clear();
std::list<ObsData>::iterator it;
for( it = allStreamData.begin();
it != allStreamData.end();
++it)
{
it->pObsStream->close();
delete it->pObsStream;
it->pObsStream = (RinexObsStream*)0;
}
allStreamData.clear();
} // End of method 'NetworkObsStreams::cleanUp()'
// Get the SourceID of the rinex observation file
SourceID NetworkObsStreams::sourceIDOfRinexObsFile(std::string obsFile)
{
try
{
RinexObsStream rin;
rin.exceptions(std::ios::failbit);
rin.open(obsFile, std::ios::in);
gnssRinex gRin;
rin >> gRin;
rin.close();
return gRin.header.source;
}
catch(...)
{
// Problem opening the file
// Maybe it doesn't exist or you don't have proper read permissions
Exception e("Problem opening the file "
+ obsFile
+ "Maybe it doesn't exist or you don't have proper read permissions");
GPSTK_THROW(e);
}
} // End of method 'NetworkObsStreams::sourceIDOfRinexObsFile'
} // End of namespace gpstk
<|endoftext|> |
<commit_before>/*
The MIT License (MIT)
Copyright (c) 2014 https://github.com/labyrinthofdreams
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 <algorithm>
#include <stdexcept>
#include "types.hpp"
using namespace templet;
using namespace templet::types;
std::string Data::getValue() const {
throw std::runtime_error("Data item is not of type value");
}
const DataVector& Data::getList() const {
throw std::runtime_error("Data item is not of type list");
}
const DataMap&Data::getMap() const {
throw std::runtime_error("Data item is not of type map");
}
DataValue::DataValue(std::string value)
: _value(std::move(value)) {
}
bool DataValue::empty() const {
return _value.empty();
}
std::string DataValue::getValue() const {
return _value;
}
DataType DataValue::type() const {
return DataType::String;
}
DataList::DataList(DataVector data)
: _data(std::move(data)) {
}
DataList::DataList(std::initializer_list<std::string> items)
: _data() {
for(auto& item : items) {
_data.push_back(make_data(std::move(item)));
}
}
bool DataList::empty() const {
return _data.empty();
}
const DataVector& DataList::getList() const {
return _data;
}
DataType DataList::type() const {
return DataType::List;
}
DataMapper::DataMapper(DataMap data) : _data(std::move(data)) {
}
bool DataMapper::empty() const {
return _data.empty();
}
const DataMap& DataMapper::getMap() const {
return _data;
}
DataType DataMapper::type() const {
return DataType::Mapper;
}
<commit_msg>Formatting<commit_after>/*
The MIT License (MIT)
Copyright (c) 2014 https://github.com/labyrinthofdreams
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 <algorithm>
#include <stdexcept>
#include "types.hpp"
using namespace templet;
using namespace templet::types;
std::string Data::getValue() const {
throw std::runtime_error("Data item is not of type value");
}
const DataVector& Data::getList() const {
throw std::runtime_error("Data item is not of type list");
}
const DataMap& Data::getMap() const {
throw std::runtime_error("Data item is not of type map");
}
DataValue::DataValue(std::string value)
: _value(std::move(value)) {
}
bool DataValue::empty() const {
return _value.empty();
}
std::string DataValue::getValue() const {
return _value;
}
DataType DataValue::type() const {
return DataType::String;
}
DataList::DataList(DataVector data)
: _data(std::move(data)) {
}
DataList::DataList(std::initializer_list<std::string> items)
: _data() {
for(auto& item : items) {
_data.push_back(make_data(std::move(item)));
}
}
bool DataList::empty() const {
return _data.empty();
}
const DataVector& DataList::getList() const {
return _data;
}
DataType DataList::type() const {
return DataType::List;
}
DataMapper::DataMapper(DataMap data) : _data(std::move(data)) {
}
bool DataMapper::empty() const {
return _data.empty();
}
const DataMap& DataMapper::getMap() const {
return _data;
}
DataType DataMapper::type() const {
return DataType::Mapper;
}
<|endoftext|> |
<commit_before>//
// Copyright © 2015 Slack Technologies, Inc. All rights reserved.
//
#include "slack/types.h"
#include "slack/set_option.h"
#include <json/json.h>
#include "uricodec.h"
namespace slack
{
//overload for our own json type. Clever way to get around exposing the json.h file in public interfaces. I hope.
template<>
channel::channel(const Json::Value &parsed_json) :
id{parsed_json["id"].asString()},
name{parsed_json["name"].asString()},
is_channel{parsed_json["is_channel"].asBool()},
created{parsed_json["created"].asInt()},
creator{parsed_json["creator"].asString()},
is_archived{parsed_json["is_archived"].asBool()},
is_general{parsed_json["is_general"].asBool()},
is_member{parsed_json["is_member"].asBool()},
last_read{parsed_json["last_read"].asString()},
unread_count{parsed_json["unread_count"].asInt()},
unread_display_count{parsed_json["unread_display_count"].asInt()}
{
for (const auto member_obj : parsed_json["members"])
{
members.emplace_back(member_obj.asString());
}
topic = {
parsed_json["topic"]["value"].asString(),
parsed_json["topic"]["creator"].asString(),
parsed_json["topic"]["last_set"].asInt()
};
purpose = {
parsed_json["purpose"]["value"].asString(),
parsed_json["purpose"]["creator"].asString(),
parsed_json["purpose"]["last_set"].asInt()
};
}
template<>
message::message(const Json::Value &parsed_json)
{
text = parsed_json["text"].asString();
//TODO this needs more nuance.
ts = parsed_json["ts"].asString();
//TODO these are going to be optional probably
username = parsed_json["username"].asString();
type = parsed_json["type"].asString();
if (!parsed_json["subtype"].isNull())
{
subtype = parsed_json["subtype"].asString();
}
}
command::command(const std::map<std::string, std::string> ¶ms)
{
if (params.count("token")) token = UriDecode(params.at("token"));
if (params.count("team_id")) team_id = UriDecode(params.at("team_id"));
if (params.count("team_domain")) team_domain = UriDecode(params.at("team_domain"));
if (params.count("channel_id")) channel_id = UriDecode(params.at("channel_id"));
if (params.count("channel_name")) channel_name = UriDecode(params.at("channel_name"));
if (params.count("user_id")) user_id = UriDecode(params.at("user_id"));
if (params.count("user_name")) user_name = UriDecode(params.at("user_name"));
if (params.count("command")) command_name = UriDecode(params.at("command"));
if (params.count("text")) text = UriDecode(params.at("text"));
if (params.count("response_url")) response_url = UriDecode(params.at("response_url"));
}
template<>
field::operator Json::Value()
{
Json::Value root;
root["title"] = title;
root["value"] = value;
if (is_short)
{
root["short"] = *is_short;
}
return root;
}
template<>
attachment::operator Json::Value()
{
Json::Value root;
if (fallback) root["fallback"] = *fallback;
if (color) root["color"] = *color;
if (pretext) root["pretext"] = *pretext;
if (author_name) root["author_name"] = *author_name;
if (author_link) root["author_link"] = *author_link;
if (author_icon) root["author_icon"] = *author_icon;
if (title) root["title"] = *title;
if (title_link) root["title_link"] = *title_link;
if (text) root["text"] = *text;
if (fields)
{
Json::Value fs;
for (auto &f : *fields)
{
fs.append(f);
}
root["fields"] = fs;
}
if (mrkdwn_in) {
Json::Value ms;
for (auto &m : *mrkdwn_in)
{
ms.append(m);
}
root["mrkdwn_in"] = ms;
}
if (image_url) root["image_url"] = *image_url;
if (thumb_url) root["thumb_url"] = *thumb_url;
return root;
}
namespace incoming_webhook
{
payload::payload(const parameter::text &text) : text_{text}
{ }
payload::payload(const parameter::attachments &attachments) : attachments_{attachments}
{ }
payload::operator std::string()
{
Json::Value root;
root["text"] = text_;
if (channel_) root["channel"] = *channel_;
if (username_) root["username"] = *username_;
if (icon_emoji_) root["icon_emoji"] = *icon_emoji_;
if (mrkdwn_) root["mrkdwn"] = *mrkdwn_ ? "true" : "false";
if (response_type_)
{
std::string val{""};
switch (*response_type_)
{
case parameter::response_type::in_channel:
val = "in_channel";
break;
case parameter::response_type::ephemeral:
val = "ephemeral";
}
root["response_type"] = val;
}
if (attachments_)
{
Json::Value as;
for (auto &a : *attachments_)
{
as.append(a);
}
root["attachments"] = as;
}
//TODO there is probably a better way?
std::stringstream ss;
ss << root;
return ss.str();
}
} //namespace incoming_webhook
} //namespace slack<commit_msg>Make it compile<commit_after>//
// Copyright © 2015 Slack Technologies, Inc. All rights reserved.
//
#include "slack/types.h"
#include "slack/set_option.h"
#include <json/json.h>
#include "uricodec.h"
namespace slack
{
//overload for our own json type. Clever way to get around exposing the json.h file in public interfaces. I hope.
template<>
channel::channel(const Json::Value &parsed_json) :
id{parsed_json["id"].asString()},
name{parsed_json["name"].asString()},
is_channel{parsed_json["is_channel"].asBool()},
created{parsed_json["created"].asInt()},
creator{parsed_json["creator"].asString()},
is_archived{parsed_json["is_archived"].asBool()},
is_general{parsed_json["is_general"].asBool()},
is_member{parsed_json["is_member"].asBool()},
last_read{parsed_json["last_read"].asString()},
unread_count{parsed_json["unread_count"].asInt()},
unread_display_count{parsed_json["unread_display_count"].asInt()}
{
for (const auto member_obj : parsed_json["members"])
{
members.emplace_back(member_obj.asString());
}
topic = {
parsed_json["topic"]["value"].asString(),
parsed_json["topic"]["creator"].asString(),
parsed_json["topic"]["last_set"].asInt()
};
purpose = {
parsed_json["purpose"]["value"].asString(),
parsed_json["purpose"]["creator"].asString(),
parsed_json["purpose"]["last_set"].asInt()
};
}
template<>
message::message(const Json::Value &parsed_json)
{
text = parsed_json["text"].asString();
//TODO this needs more nuance.
ts = parsed_json["ts"].asString();
//TODO these are going to be optional probably
username = parsed_json["username"].asString();
type = parsed_json["type"].asString();
if (!parsed_json["subtype"].isNull())
{
subtype = parsed_json["subtype"].asString();
}
}
command::command(const std::map<std::string, std::string> ¶ms)
{
if (params.count("token")) token = UriDecode(params.at("token"));
if (params.count("team_id")) team_id = UriDecode(params.at("team_id"));
if (params.count("team_domain")) team_domain = UriDecode(params.at("team_domain"));
if (params.count("channel_id")) channel_id = UriDecode(params.at("channel_id"));
if (params.count("channel_name")) channel_name = UriDecode(params.at("channel_name"));
if (params.count("user_id")) user_id = UriDecode(params.at("user_id"));
if (params.count("user_name")) user_name = UriDecode(params.at("user_name"));
if (params.count("command")) command_name = UriDecode(params.at("command"));
if (params.count("text")) text = UriDecode(params.at("text"));
if (params.count("response_url")) response_url = UriDecode(params.at("response_url"));
}
template<>
field::operator Json::Value()
{
Json::Value root;
root["title"] = title;
root["value"] = value;
if (is_short)
{
root["short"] = *is_short;
}
return root;
}
template<>
attachment::operator Json::Value()
{
Json::Value root;
if (fallback) root["fallback"] = *fallback;
if (color) root["color"] = *color;
if (pretext) root["pretext"] = *pretext;
if (author_name) root["author_name"] = *author_name;
if (author_link) root["author_link"] = *author_link;
if (author_icon) root["author_icon"] = *author_icon;
if (title) root["title"] = *title;
if (title_link) root["title_link"] = *title_link;
if (text) root["text"] = *text;
if (fields)
{
Json::Value fs;
for (auto &f : *fields)
{
fs.append(f);
}
root["fields"] = fs;
}
if (mrkdwn_in) {
Json::Value ms;
for (auto &m : *mrkdwn_in)
{
ms.append(m);
}
root["mrkdwn_in"] = ms;
}
if (image_url) root["image_url"] = *image_url;
if (thumb_url) root["thumb_url"] = *thumb_url;
return root;
}
namespace incoming_webhook
{
payload::payload(const parameter::text &text) : text_{text}
{ }
payload::payload(const parameter::attachments &attachments) : attachments_{attachments}
{ }
payload::operator std::string()
{
Json::Value root;
if (text_) root["text"] = *text_;
if (channel_) root["channel"] = *channel_;
if (username_) root["username"] = *username_;
if (icon_emoji_) root["icon_emoji"] = *icon_emoji_;
if (mrkdwn_) root["mrkdwn"] = *mrkdwn_ ? "true" : "false";
if (response_type_)
{
std::string val{""};
switch (*response_type_)
{
case parameter::response_type::in_channel:
val = "in_channel";
break;
case parameter::response_type::ephemeral:
val = "ephemeral";
}
root["response_type"] = val;
}
if (attachments_)
{
Json::Value as;
for (auto &a : *attachments_)
{
as.append(a);
}
root["attachments"] = as;
}
//TODO there is probably a better way?
std::stringstream ss;
ss << root;
return ss.str();
}
} //namespace incoming_webhook
} //namespace slack<|endoftext|> |
<commit_before>#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
#include <sstream>
#include "StateSpace.h"
#include "PriorityQueue.h"
#include "State.h"
#include "encoder.h"
#include "CreateModule.h"
/**
* @brief Gives a std::string representation of a primitive type
*
* @param x Primitive type such as int, double, long
* @return std::string conversion of param x
*/
template<typename T> std::string to_string(T x) {
return static_cast<std::ostringstream&>((std::ostringstream() << std::dec << x)).str();
}
//function to calculate a temperature for the select action function as a function of time
double temperature();
//function to select next action
int * selectAction(PriorityQueue<int,double>& a_queue);
//function to update a q value
void updateQ(StateSpace & space, int * action, State & new_state, State & old_state, double alpha, double gamma);
int main()
{
// STUFF WE DONT UNDERSTAND, AND DONT NEED TO
//__________________________________________________________________________________________
//__________________________________________________________________________________________
// Libraries to load
std::string bodyLibName = "bodyinfo";
std::string movementLibName = "movementtools";
// Name of camera module in library
std::string bodyModuleName = "BodyInfo";
std::string movementModuleName = "MovementTools";
// Set broker name, ip and port, finding first available port from 54000
const std::string brokerName = "MotionTimingBroker";
int brokerPort = qi::os::findAvailablePort(54000);
const std::string brokerIp = "0.0.0.0";
// Default parent port and ip
int pport = 9559;
std::string pip = "127.0.0.1";
// Need this for SOAP serialisation of floats to work
setlocale(LC_NUMERIC, "C");
// Create a broker
boost::shared_ptr<AL::ALBroker> broker;
try
{
broker = AL::ALBroker::createBroker(
brokerName,
brokerIp,
brokerPort,
pip,
pport,
0);
}
// Throw error and quit if a broker could not be created
catch(...)
{
std::cerr << "Failed to connect broker to: "
<< pip
<< ":"
<< pport
<< std::endl;
AL::ALBrokerManager::getInstance()->killAllBroker();
AL::ALBrokerManager::kill();
return 1;
}
// Add the broker to NAOqi
AL::ALBrokerManager::setInstance(broker->fBrokerManager.lock());
AL::ALBrokerManager::getInstance()->addBroker(broker);
CreateModule(movementLibName, movementModuleName, broker, false, true);
CreateModule(bodyLibName, bodyModuleName, broker, false, true);
AL::ALProxy bodyInfoProxy(bodyModuleName, pip, pport);
AL::ALProxy movementToolsProxy(movementModuleName, pip, pport);
AL::ALMotionProxy motion(pip, pport);
//__________________________________________________________________________________________
//__________________________________________________________________________________________
//END OF STUFF WE DONT UNDERSTAND, BREATHE NOW
//learning factor
const double alpha=0.5;
//discount factor
const double gamma=0.5;
//seed rng
std::srand(std::time(NULL));
int action_forwards = FORWARD;
int* p_action_forwards = &action_forwards;
int action_backwards = BACKWARD;
int* p_action_backwards = &action_backwards;
int* chosen_action = &action_forwards;
//create a priority queue to copy to all the state space priority queues
PriorityQueue<int*,double> initiator_queue(MAX);
initiator_queue.enqueueWithPriority(p_action_forwards,0);
initiator_queue.enqueueWithPriority(p_action_backwards,0);
//create encoder
Encoder encoder();
encoder.calibrate();
//create the state space
StateSpace space(initiator_queue);
space.setAngle(100);
space.setVelocity(50);
//state objects
State current_state(0,0,FORWARD);
State old_state(0,0,FORWARD);
while(true)
{
current_state.theta= M_PI * encoder.GetAngle()/180;
current_state.theta_dot=(current_state.theta - old_state.theta)/700; //Needs actual time
current_state.robot_state=*chosen_action;
updateQ(space, chosen_action, old_state, current_state, alpha, gamma);
old_state=current_state;
chosen_action=selectAction(space[current_state]);
(*chosen_action)?movementToolsProxy.callVoid("swingForwards"):movementToolsProxy.callVoid("swingBackwards");
}
return 1;
}
double temperature()
{
return std::time(NULL);
}
//function is fed with a priority queue of action-values
//generates Boltzmann distribution of these action-values
//and selects an action based on probabilities
int * selectAction(PriorityQueue<int *,double>& a_queue)
{
typedef PriorityQueue<int *,double> PQ;
typedef std::vector< std::pair<int *, double> > Vec_Pair;
typedef std::pair<int *, double> Pair;
double sum= 0;
int i = 0;
int size = a_queue.getSize();
Vec_Pair action_vec(size);
//Calculate partition function by iterating over action-values
for(PQ::const_iterator iter = a_queue.begin(),end=a_queue.end(); iter < end; ++iter)
{
sum += std::exp((iter->second)/temperature());
}
//Calculate boltzmann factors for action-values
for(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)
{
it->first = a_queue[i].first;
it->second = std::exp(a_queue[i].second /temperature()) / sum;
++i;
}
//calculate cumulative probability distribution
for(Vec_Pair::iterator it1 = action_vec.begin()++,it2 = action_vec.begin(),end=action_vec.end(); it < end; ++it1,++it2)
{
it1->second += it2->second;
}
//generate RN between 0 and 1
double rand_num = static_cast<double>(rand()/ (RAND_MAX));
//select action based on probability
for(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)
{
//if RN falls within cumulative probability bin return the corresponding action
if(rand_num < it->second)return &(it->first);
}
return NULL; //note that this line should never be reached
}
void updateQ(StateSpace & space, int * action, State & new_state, State & old_state, double alpha, double gamma)
{
//oldQ value reference
double oldQ = space[old_state].search(action).second;
//reward given to current state
double R = new_state.getReward();
//optimal Q value for new state i.e. first element
double maxQ = space[current_state].peekFront().second;
//new Q value determined by Q learning algorithm
double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ);
// change priority of action to new Q value
space[old_state].changePriority(action, newQ);
}
<commit_msg>de-pointerify<commit_after>#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
#include <sstream>
#include "StateSpace.h"
#include "PriorityQueue.h"
#include "State.h"
#include "encoder.h"
#include "CreateModule.h"
/**
* @brief Gives a std::string representation of a primitive type
*
* @param x Primitive type such as int, double, long
* @return std::string conversion of param x
*/
template<typename T> std::string to_string(T x) {
return static_cast<std::ostringstream&>((std::ostringstream() << std::dec << x)).str();
}
//function to calculate a temperature for the select action function as a function of time
double temperature();
//function to select next action
int selectAction(PriorityQueue<int,double>& a_queue);
//function to update a q value
void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma);
int main()
{
// STUFF WE DONT UNDERSTAND, AND DONT NEED TO
//__________________________________________________________________________________________
//__________________________________________________________________________________________
// Libraries to load
std::string bodyLibName = "bodyinfo";
std::string movementLibName = "movementtools";
// Name of camera module in library
std::string bodyModuleName = "BodyInfo";
std::string movementModuleName = "MovementTools";
// Set broker name, ip and port, finding first available port from 54000
const std::string brokerName = "MotionTimingBroker";
int brokerPort = qi::os::findAvailablePort(54000);
const std::string brokerIp = "0.0.0.0";
// Default parent port and ip
int pport = 9559;
std::string pip = "127.0.0.1";
// Need this for SOAP serialisation of floats to work
setlocale(LC_NUMERIC, "C");
// Create a broker
boost::shared_ptr<AL::ALBroker> broker;
try
{
broker = AL::ALBroker::createBroker(
brokerName,
brokerIp,
brokerPort,
pip,
pport,
0);
}
// Throw error and quit if a broker could not be created
catch(...)
{
std::cerr << "Failed to connect broker to: "
<< pip
<< ":"
<< pport
<< std::endl;
AL::ALBrokerManager::getInstance()->killAllBroker();
AL::ALBrokerManager::kill();
return 1;
}
// Add the broker to NAOqi
AL::ALBrokerManager::setInstance(broker->fBrokerManager.lock());
AL::ALBrokerManager::getInstance()->addBroker(broker);
CreateModule(movementLibName, movementModuleName, broker, false, true);
CreateModule(bodyLibName, bodyModuleName, broker, false, true);
AL::ALProxy bodyInfoProxy(bodyModuleName, pip, pport);
AL::ALProxy movementToolsProxy(movementModuleName, pip, pport);
AL::ALMotionProxy motion(pip, pport);
//__________________________________________________________________________________________
//__________________________________________________________________________________________
//END OF STUFF WE DONT UNDERSTAND, BREATHE NOW
//learning factor
const double alpha=0.5;
//discount factor
const double gamma=0.5;
//seed rng
std::srand(std::time(NULL));
int action_forwards = FORWARD;
int action_backwards = BACKWARD;
int chosen_action = action_forwards;
//create a priority queue to copy to all the state space priority queues
PriorityQueue<int,double> initiator_queue(MAX);
initiator_queue.enqueueWithPriority(action_forwards,0);
initiator_queue.enqueueWithPriority(action_backwards,0);
//create encoder
Encoder encoder();
encoder.calibrate();
//create the state space
StateSpace space(initiator_queue);
space.setAngle(100);
space.setVelocity(50);
//state objects
State current_state(0,0,FORWARD);
State old_state(0,0,FORWARD);
while(true)
{
current_state.theta= M_PI * encoder.GetAngle()/180;
current_state.theta_dot=(current_state.theta - old_state.theta)/700; //Needs actual time
current_state.robot_state=chosen_action;
updateQ(space, chosen_action, old_state, current_state, alpha, gamma);
old_state=current_state;
chosen_action=selectAction(space[current_state]);
(chosen_action)?movementToolsProxy.callVoid("swingForwards"):movementToolsProxy.callVoid("swingBackwards");
}
return 1;
}
double temperature()
{
return std::time(NULL);
}
//function is fed with a priority queue of action-values
//generates Boltzmann distribution of these action-values
//and selects an action based on probabilities
int selectAction(PriorityQueue<int,double>& a_queue)
{
typedef PriorityQueue<int,double> PQ;
typedef std::vector< std::pair<int *, double> > Vec_Pair;
typedef std::pair<int, double> Pair;
double sum= 0;
int i = 0;
int size = a_queue.getSize();
Vec_Pair action_vec(size);
//Calculate partition function by iterating over action-values
for(PQ::const_iterator iter = a_queue.begin(),end=a_queue.end(); iter < end; ++iter)
{
sum += std::exp((iter->second)/temperature());
}
//Calculate boltzmann factors for action-values
for(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)
{
it->first = a_queue[i].first;
it->second = std::exp(a_queue[i].second /temperature()) / sum;
++i;
}
//calculate cumulative probability distribution
for(Vec_Pair::iterator it1 = action_vec.begin()++,it2 = action_vec.begin(),end=action_vec.end(); it < end; ++it1,++it2)
{
it1->second += it2->second;
}
//generate RN between 0 and 1
double rand_num = static_cast<double>(rand()/ (RAND_MAX));
//select action based on probability
for(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)
{
//if RN falls within cumulative probability bin return the corresponding action
if(rand_num < it->second)return it->first;
}
return NULL; //note that this line should never be reached
}
void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma)
{
//oldQ value reference
double oldQ = space[old_state].search(action).second;
//reward given to current state
double R = new_state.getReward();
//optimal Q value for new state i.e. first element
double maxQ = space[current_state].peekFront().second;
//new Q value determined by Q learning algorithm
double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ);
// change priority of action to new Q value
space[old_state].changePriority(action, newQ);
}
<|endoftext|> |
<commit_before>#include <imq/vm.h>
#include <imq/expressions.h>
#include <imq/mathexpr.h>
#include <imq/image.h>
#include <gtest/gtest.h>
using namespace imq;
TEST(VMachine, CallFunctionExpr)
{
ContextPtr ctx(new SimpleContext());
bool functionCalled = false;
QValue func = QValue::Function([&](int32_t argCount, QValue* args, QValue* result) -> Result {
if (argCount == 1)
{
*result = args[0];
}
else if (argCount == 2)
{
*result = QValue::Float(3.f);
}
else
{
*result = QValue::Integer(argCount);
}
functionCalled = true;
return true;
});
CallFunctionExpr* expr = new CallFunctionExpr(new ConstantExpr(func, { 0, 0 }), 0, nullptr, { 0, 0 });
QValue value;
ASSERT_TRUE(expr->execute(ctx, &value));
ASSERT_TRUE(functionCalled);
ASSERT_EQ(value, QValue::Integer(0));
functionCalled = false;
delete expr;
VExpression** args = new VExpression*[1]{ new ConstantExpr(QValue::Integer(321), {0,0}) };
expr = new CallFunctionExpr(new ConstantExpr(func, { 0, 0 }), 1, args, { 0, 0 });
ASSERT_TRUE(expr->execute(ctx, &value));
ASSERT_TRUE(functionCalled);
ASSERT_EQ(value, QValue::Integer(321));
functionCalled = false;
delete expr;
args = new VExpression*[2]{ new ConstantExpr(QValue::Integer(321), {0,0}), new ConstantExpr(QValue::Integer(123), {0,0}) };
expr = new CallFunctionExpr(new ConstantExpr(func, { 0,0 }), 2, args, { 0, 0 });
ASSERT_TRUE(expr->execute(ctx, &value));
ASSERT_TRUE(functionCalled);
ASSERT_EQ(value, QValue::Float(3.f));
delete expr;
}
TEST(VMachine, Variables)
{
ContextPtr ctx(new SimpleContext());
QValue value;
VExpression* expr = new RetrieveVariableExpr("foo", { 1, 2 });
Result result = expr->execute(ctx, &value);
ASSERT_FALSE(result);
ASSERT_EQ(result.getErr(), "line 1:2: Unknown variable \"foo\"");
VStatement* stm = new SetVariableStm("foo", new ConstantExpr(QValue::Integer(345), { 0, 0 }), { 0, 0 });
ASSERT_TRUE(stm->execute(ctx));
ASSERT_TRUE(expr->execute(ctx, &value));
ASSERT_EQ(value, QValue::Integer(345));
delete expr;
delete stm;
}
TEST(VMachine, Fields)
{
ContextPtr ctx(new SimpleContext());
QValue obj = QValue::Object(new QColor(1.f, 0.3f, 0.4f, 1.f));
QValue value;
VExpression* expr = new RetrieveFieldExpr(new ConstantExpr(obj, { 0, 0 }), "foo", { 0, 0 });
ASSERT_FALSE(expr->execute(ctx, &value));
delete expr;
expr = new RetrieveFieldExpr(new ConstantExpr(obj, { 0, 0 }), "g", { 0, 0 });
ASSERT_TRUE(expr->execute(ctx, &value));
ASSERT_EQ(value, QValue::Float(0.3f));
VStatement* stm = new SetFieldStm(new ConstantExpr(obj, { 0, 0 }), "green", new ConstantExpr(QValue::Float(0.89f), { 0,0 }), { 0, 0 });
ASSERT_FALSE(stm->execute(ctx));
ASSERT_TRUE(expr->execute(ctx, &value));
ASSERT_EQ(value, QValue::Float(0.3f));
delete expr;
delete stm;
}
TEST(VMachine, Indices)
{
ContextPtr ctx(new SimpleContext());
QValue obj = QValue::Object(new QColor(1.f, 0.3f, 0.4f, 1.f));
QValue value;
VExpression* expr = new RetrieveIndexExpr(new ConstantExpr(obj, { 0,0 }), new ConstantExpr(QValue::Integer(-1), { 0,0 }), { 0, 0 });
ASSERT_FALSE(expr->execute(ctx, &value));
delete expr;
expr = new RetrieveIndexExpr(new ConstantExpr(obj, { 0,0 }), new ConstantExpr(QValue::Integer(2), { 0,0 }), { 0, 0 });
ASSERT_TRUE(expr->execute(ctx, &value));
ASSERT_EQ(value, QValue::Float(0.4f));
VStatement* stm = new SetIndexStm(new ConstantExpr(obj, { 0, 0 }), new ConstantExpr(QValue::Integer(2), { 0,0 }), new ConstantExpr(QValue::Float(0.132f), { 0,0 }), { 0,0 });
ASSERT_FALSE(stm->execute(ctx));
ASSERT_TRUE(expr->execute(ctx, &value));
ASSERT_EQ(value, QValue::Float(0.4f));
delete expr;
delete stm;
}
TEST(VMachine, Select)
{
ContextPtr ctx(new SimpleContext());
std::shared_ptr<QImage> imageA(new QImage(100, 100, QColor(1.f, 1.f, 1.f, 1.f)));
std::shared_ptr<QImage> imageB(new QImage(100, 100, QColor(0.f, 0.f, 0.f, 0.f)));
VStatement* stm = new SelectStm(
new ConstantExpr(QValue::Object(imageB), { 0, 0 }),
new ConstantExpr(QValue::Object(imageA), { 0, 0 }),
new RetrieveVariableExpr("color", { 0, 0 }),
nullptr,
nullptr,
0,
nullptr,
{ 0, 0 }
);
ASSERT_TRUE(stm->execute(ctx));
QColor color;
for (int32_t y = 0; y < 100; ++y)
{
for (int32_t x = 0; x < 100; ++x)
{
ASSERT_TRUE(imageB->getPixel(x, y, &color));
ASSERT_EQ(color, QColor(1.f, 1.f, 1.f, 1.f));
}
}
}
TEST(VMachine, MathExpressions)
{
ContextPtr ctx(new SimpleContext());
// (8 + (5 - 3)) / 2 * 4
VExpression* expr = new MulExpr(
new DivExpr(
new AddExpr(
new ConstantExpr(QValue::Integer(8), { 0,0 }),
new SubExpr(
new ConstantExpr(QValue::Integer(5), { 0,0 }),
new ConstantExpr(QValue::Integer(3), { 0,0 }),
{ 0,0 }
),
{ 0,0 }
),
new ConstantExpr(QValue::Integer(2), { 0,0 }),
{ 0,0 }
),
new ConstantExpr(QValue::Integer(4), { 0,0 }),
{ 0,0 }
);
QValue value;
int32_t i;
ASSERT_TRUE(expr->execute(ctx, &value));
ASSERT_TRUE(value.getInteger(&i));
ASSERT_EQ(i, 20);
delete expr;
// 25.8 / 2
expr = new DivExpr(
new ConstantExpr(QValue::Float(25.8f), { 0,0 }),
new ConstantExpr(QValue::Integer(2), { 0,0 }),
{ 0,0 }
);
float f;
ASSERT_TRUE(expr->execute(ctx, &value));
ASSERT_TRUE(value.getFloat(&f));
ASSERT_FLOAT_EQ(f, 12.9f);
delete expr;
// true || (false && !(5 == 5))
expr = new OrExpr(
new ConstantExpr(QValue::Bool(true), { 0,0 }),
new AndExpr(
new ConstantExpr(QValue::Bool(false), { 0,0 }),
new NotExpr(
new EqualExpr(
new ConstantExpr(QValue::Integer(5), { 0,0 }),
new ConstantExpr(QValue::Integer(5), { 0,0 }),
{ 0,0 }
),
{ 0,0 }
),
{ 0,0 }
),
{ 0,0 }
);
bool b;
ASSERT_TRUE(expr->execute(ctx, &value));
ASSERT_TRUE(value.getBool(&b));
ASSERT_TRUE(b);
delete expr;
}
TEST(VMachine, DefineInput)
{
ContextPtr ctx(new SimpleContext());
VStatement* stm = new DefineInputStm("foo", new ConstantExpr(QValue::Nil(), { 0,0 }), { 0,0 });
Result res = stm->execute(ctx);
ASSERT_FALSE(res);
ASSERT_EQ(res.getErr(), "line 0:0: Inputs/outputs must be defined in the root context.");
delete stm;
std::shared_ptr<RootContext> rootCtx(new RootContext());
stm = new DefineInputStm("foo", new ConstantExpr(QValue::Nil(), { 0,0 }), { 0,0 });
ASSERT_TRUE(stm->execute(rootCtx));
ASSERT_TRUE(rootCtx->hasValue("foo"));
QValue value;
ASSERT_TRUE(rootCtx->getValue("foo", &value));
ASSERT_EQ(value, QValue::Nil());
rootCtx->setInput("foo", QValue::Integer(123));
ASSERT_TRUE(rootCtx->getValue("foo", &value));
ASSERT_EQ(value, QValue::Integer(123));
res = stm->execute(rootCtx);
ASSERT_FALSE(res);
ASSERT_EQ(res.getErr(), "line 0:0: Input foo has the wrong type.");
delete stm;
stm = new DefineInputStm("bar", new ConstantExpr(QValue::Float(1.34f), { 0,0 }), { 0,0 });
ASSERT_TRUE(stm->execute(rootCtx));
ASSERT_TRUE(rootCtx->hasValue("bar"));
ASSERT_TRUE(rootCtx->getValue("bar", &value));
ASSERT_EQ(value, QValue::Float(1.34f));
delete stm;
}
TEST(VMachine, DefineOutput)
{
ContextPtr ctx(new SimpleContext());
VStatement* stm = new DefineOutputStm("foo", nullptr, { 0,0 });
Result res = stm->execute(ctx);
ASSERT_FALSE(res);
ASSERT_EQ(res.getErr(), "line 0:0: Inputs/outputs must be defined in the root context.");
delete stm;
std::shared_ptr<RootContext> rootCtx(new RootContext());
stm = new DefineOutputStm("foo", nullptr, { 0,0 });
ASSERT_TRUE(stm->execute(rootCtx));
ASSERT_TRUE(rootCtx->hasValue("foo"));
QValue value;
ASSERT_TRUE(rootCtx->getValue("foo", &value));
ASSERT_EQ(value, QValue::Nil());
rootCtx->setOutput("foo", QValue::Integer(123));
ASSERT_TRUE(rootCtx->getValue("foo", &value));
ASSERT_EQ(value, QValue::Integer(123));
res = stm->execute(rootCtx);
ASSERT_FALSE(res);
ASSERT_EQ(res.getErr(), "line 0:0: Outputs may not be redefined.");
delete stm;
stm = new DefineOutputStm("bar", new ConstantExpr(QValue::Float(1.34f), { 0,0 }), { 0,0 });
ASSERT_TRUE(stm->execute(rootCtx));
ASSERT_TRUE(rootCtx->hasValue("bar"));
ASSERT_TRUE(rootCtx->getValue("bar", &value));
ASSERT_EQ(value, QValue::Float(1.34f));
delete stm;
}
TEST(VMachine, Branch)
{
ContextPtr ctx(new SimpleContext());
bool trueCalled = false;
bool falseCalled = false;
QValue trueFunc = QValue::Function([&](int32_t argCount, QValue* args, QValue* result) -> Result {
trueCalled = true;
*result = QValue::Nil();
return true;
});
QValue falseFunc = QValue::Function([&](int32_t argCount, QValue* args, QValue* result) -> Result {
falseCalled = true;
*result = QValue::Nil();
return true;
});
VStatement* stm = new BranchStm(new ConstantExpr(QValue::Integer(123), { 0,0 }), nullptr, nullptr, { 0,0 });
Result res = stm->execute(ctx);
ASSERT_FALSE(res);
ASSERT_EQ(res.getErr(), "line 0:0: Subexpression must return a boolean within a Branch");
delete stm;
stm = new BranchStm(
new ConstantExpr(QValue::Bool(false), { 0,0 }),
new VExpressionAsStatement(new CallFunctionExpr(new ConstantExpr(trueFunc, { 0,0 }), 0, nullptr, { 0,0 }), { 0,0 }),
new VExpressionAsStatement(new CallFunctionExpr(new ConstantExpr(falseFunc, { 0,0 }), 0, nullptr, { 0,0 }), { 0,0 }),
{ 0,0 }
);
ASSERT_TRUE(stm->execute(ctx));
EXPECT_FALSE(trueCalled);
EXPECT_TRUE(falseCalled);
trueCalled = false;
falseCalled = false;
delete stm;
stm = new BranchStm(
new ConstantExpr(QValue::Bool(true), { 0,0 }),
new VExpressionAsStatement(new CallFunctionExpr(new ConstantExpr(trueFunc, { 0,0 }), 0, nullptr, { 0,0 }), { 0,0 }),
new VExpressionAsStatement(new CallFunctionExpr(new ConstantExpr(falseFunc, { 0,0 }), 0, nullptr, { 0,0 }), { 0,0 }),
{ 0,0 }
);
ASSERT_TRUE(stm->execute(ctx));
EXPECT_TRUE(trueCalled);
EXPECT_FALSE(falseCalled);
delete stm;
}<commit_msg>missing delete in VMachine.Select test<commit_after>#include <imq/vm.h>
#include <imq/expressions.h>
#include <imq/mathexpr.h>
#include <imq/image.h>
#include <gtest/gtest.h>
using namespace imq;
TEST(VMachine, CallFunctionExpr)
{
ContextPtr ctx(new SimpleContext());
bool functionCalled = false;
QValue func = QValue::Function([&](int32_t argCount, QValue* args, QValue* result) -> Result {
if (argCount == 1)
{
*result = args[0];
}
else if (argCount == 2)
{
*result = QValue::Float(3.f);
}
else
{
*result = QValue::Integer(argCount);
}
functionCalled = true;
return true;
});
CallFunctionExpr* expr = new CallFunctionExpr(new ConstantExpr(func, { 0, 0 }), 0, nullptr, { 0, 0 });
QValue value;
ASSERT_TRUE(expr->execute(ctx, &value));
ASSERT_TRUE(functionCalled);
ASSERT_EQ(value, QValue::Integer(0));
functionCalled = false;
delete expr;
VExpression** args = new VExpression*[1]{ new ConstantExpr(QValue::Integer(321), {0,0}) };
expr = new CallFunctionExpr(new ConstantExpr(func, { 0, 0 }), 1, args, { 0, 0 });
ASSERT_TRUE(expr->execute(ctx, &value));
ASSERT_TRUE(functionCalled);
ASSERT_EQ(value, QValue::Integer(321));
functionCalled = false;
delete expr;
args = new VExpression*[2]{ new ConstantExpr(QValue::Integer(321), {0,0}), new ConstantExpr(QValue::Integer(123), {0,0}) };
expr = new CallFunctionExpr(new ConstantExpr(func, { 0,0 }), 2, args, { 0, 0 });
ASSERT_TRUE(expr->execute(ctx, &value));
ASSERT_TRUE(functionCalled);
ASSERT_EQ(value, QValue::Float(3.f));
delete expr;
}
TEST(VMachine, Variables)
{
ContextPtr ctx(new SimpleContext());
QValue value;
VExpression* expr = new RetrieveVariableExpr("foo", { 1, 2 });
Result result = expr->execute(ctx, &value);
ASSERT_FALSE(result);
ASSERT_EQ(result.getErr(), "line 1:2: Unknown variable \"foo\"");
VStatement* stm = new SetVariableStm("foo", new ConstantExpr(QValue::Integer(345), { 0, 0 }), { 0, 0 });
ASSERT_TRUE(stm->execute(ctx));
ASSERT_TRUE(expr->execute(ctx, &value));
ASSERT_EQ(value, QValue::Integer(345));
delete expr;
delete stm;
}
TEST(VMachine, Fields)
{
ContextPtr ctx(new SimpleContext());
QValue obj = QValue::Object(new QColor(1.f, 0.3f, 0.4f, 1.f));
QValue value;
VExpression* expr = new RetrieveFieldExpr(new ConstantExpr(obj, { 0, 0 }), "foo", { 0, 0 });
ASSERT_FALSE(expr->execute(ctx, &value));
delete expr;
expr = new RetrieveFieldExpr(new ConstantExpr(obj, { 0, 0 }), "g", { 0, 0 });
ASSERT_TRUE(expr->execute(ctx, &value));
ASSERT_EQ(value, QValue::Float(0.3f));
VStatement* stm = new SetFieldStm(new ConstantExpr(obj, { 0, 0 }), "green", new ConstantExpr(QValue::Float(0.89f), { 0,0 }), { 0, 0 });
ASSERT_FALSE(stm->execute(ctx));
ASSERT_TRUE(expr->execute(ctx, &value));
ASSERT_EQ(value, QValue::Float(0.3f));
delete expr;
delete stm;
}
TEST(VMachine, Indices)
{
ContextPtr ctx(new SimpleContext());
QValue obj = QValue::Object(new QColor(1.f, 0.3f, 0.4f, 1.f));
QValue value;
VExpression* expr = new RetrieveIndexExpr(new ConstantExpr(obj, { 0,0 }), new ConstantExpr(QValue::Integer(-1), { 0,0 }), { 0, 0 });
ASSERT_FALSE(expr->execute(ctx, &value));
delete expr;
expr = new RetrieveIndexExpr(new ConstantExpr(obj, { 0,0 }), new ConstantExpr(QValue::Integer(2), { 0,0 }), { 0, 0 });
ASSERT_TRUE(expr->execute(ctx, &value));
ASSERT_EQ(value, QValue::Float(0.4f));
VStatement* stm = new SetIndexStm(new ConstantExpr(obj, { 0, 0 }), new ConstantExpr(QValue::Integer(2), { 0,0 }), new ConstantExpr(QValue::Float(0.132f), { 0,0 }), { 0,0 });
ASSERT_FALSE(stm->execute(ctx));
ASSERT_TRUE(expr->execute(ctx, &value));
ASSERT_EQ(value, QValue::Float(0.4f));
delete expr;
delete stm;
}
TEST(VMachine, Select)
{
ContextPtr ctx(new SimpleContext());
std::shared_ptr<QImage> imageA(new QImage(100, 100, QColor(1.f, 1.f, 1.f, 1.f)));
std::shared_ptr<QImage> imageB(new QImage(100, 100, QColor(0.f, 0.f, 0.f, 0.f)));
VStatement* stm = new SelectStm(
new ConstantExpr(QValue::Object(imageB), { 0, 0 }),
new ConstantExpr(QValue::Object(imageA), { 0, 0 }),
new RetrieveVariableExpr("color", { 0, 0 }),
nullptr,
nullptr,
0,
nullptr,
{ 0, 0 }
);
ASSERT_TRUE(stm->execute(ctx));
QColor color;
for (int32_t y = 0; y < 100; ++y)
{
for (int32_t x = 0; x < 100; ++x)
{
ASSERT_TRUE(imageB->getPixel(x, y, &color));
ASSERT_EQ(color, QColor(1.f, 1.f, 1.f, 1.f));
}
}
delete stm;
}
TEST(VMachine, MathExpressions)
{
ContextPtr ctx(new SimpleContext());
// (8 + (5 - 3)) / 2 * 4
VExpression* expr = new MulExpr(
new DivExpr(
new AddExpr(
new ConstantExpr(QValue::Integer(8), { 0,0 }),
new SubExpr(
new ConstantExpr(QValue::Integer(5), { 0,0 }),
new ConstantExpr(QValue::Integer(3), { 0,0 }),
{ 0,0 }
),
{ 0,0 }
),
new ConstantExpr(QValue::Integer(2), { 0,0 }),
{ 0,0 }
),
new ConstantExpr(QValue::Integer(4), { 0,0 }),
{ 0,0 }
);
QValue value;
int32_t i;
ASSERT_TRUE(expr->execute(ctx, &value));
ASSERT_TRUE(value.getInteger(&i));
ASSERT_EQ(i, 20);
delete expr;
// 25.8 / 2
expr = new DivExpr(
new ConstantExpr(QValue::Float(25.8f), { 0,0 }),
new ConstantExpr(QValue::Integer(2), { 0,0 }),
{ 0,0 }
);
float f;
ASSERT_TRUE(expr->execute(ctx, &value));
ASSERT_TRUE(value.getFloat(&f));
ASSERT_FLOAT_EQ(f, 12.9f);
delete expr;
// true || (false && !(5 == 5))
expr = new OrExpr(
new ConstantExpr(QValue::Bool(true), { 0,0 }),
new AndExpr(
new ConstantExpr(QValue::Bool(false), { 0,0 }),
new NotExpr(
new EqualExpr(
new ConstantExpr(QValue::Integer(5), { 0,0 }),
new ConstantExpr(QValue::Integer(5), { 0,0 }),
{ 0,0 }
),
{ 0,0 }
),
{ 0,0 }
),
{ 0,0 }
);
bool b;
ASSERT_TRUE(expr->execute(ctx, &value));
ASSERT_TRUE(value.getBool(&b));
ASSERT_TRUE(b);
delete expr;
}
TEST(VMachine, DefineInput)
{
ContextPtr ctx(new SimpleContext());
VStatement* stm = new DefineInputStm("foo", new ConstantExpr(QValue::Nil(), { 0,0 }), { 0,0 });
Result res = stm->execute(ctx);
ASSERT_FALSE(res);
ASSERT_EQ(res.getErr(), "line 0:0: Inputs/outputs must be defined in the root context.");
delete stm;
std::shared_ptr<RootContext> rootCtx(new RootContext());
stm = new DefineInputStm("foo", new ConstantExpr(QValue::Nil(), { 0,0 }), { 0,0 });
ASSERT_TRUE(stm->execute(rootCtx));
ASSERT_TRUE(rootCtx->hasValue("foo"));
QValue value;
ASSERT_TRUE(rootCtx->getValue("foo", &value));
ASSERT_EQ(value, QValue::Nil());
rootCtx->setInput("foo", QValue::Integer(123));
ASSERT_TRUE(rootCtx->getValue("foo", &value));
ASSERT_EQ(value, QValue::Integer(123));
res = stm->execute(rootCtx);
ASSERT_FALSE(res);
ASSERT_EQ(res.getErr(), "line 0:0: Input foo has the wrong type.");
delete stm;
stm = new DefineInputStm("bar", new ConstantExpr(QValue::Float(1.34f), { 0,0 }), { 0,0 });
ASSERT_TRUE(stm->execute(rootCtx));
ASSERT_TRUE(rootCtx->hasValue("bar"));
ASSERT_TRUE(rootCtx->getValue("bar", &value));
ASSERT_EQ(value, QValue::Float(1.34f));
delete stm;
}
TEST(VMachine, DefineOutput)
{
ContextPtr ctx(new SimpleContext());
VStatement* stm = new DefineOutputStm("foo", nullptr, { 0,0 });
Result res = stm->execute(ctx);
ASSERT_FALSE(res);
ASSERT_EQ(res.getErr(), "line 0:0: Inputs/outputs must be defined in the root context.");
delete stm;
std::shared_ptr<RootContext> rootCtx(new RootContext());
stm = new DefineOutputStm("foo", nullptr, { 0,0 });
ASSERT_TRUE(stm->execute(rootCtx));
ASSERT_TRUE(rootCtx->hasValue("foo"));
QValue value;
ASSERT_TRUE(rootCtx->getValue("foo", &value));
ASSERT_EQ(value, QValue::Nil());
rootCtx->setOutput("foo", QValue::Integer(123));
ASSERT_TRUE(rootCtx->getValue("foo", &value));
ASSERT_EQ(value, QValue::Integer(123));
res = stm->execute(rootCtx);
ASSERT_FALSE(res);
ASSERT_EQ(res.getErr(), "line 0:0: Outputs may not be redefined.");
delete stm;
stm = new DefineOutputStm("bar", new ConstantExpr(QValue::Float(1.34f), { 0,0 }), { 0,0 });
ASSERT_TRUE(stm->execute(rootCtx));
ASSERT_TRUE(rootCtx->hasValue("bar"));
ASSERT_TRUE(rootCtx->getValue("bar", &value));
ASSERT_EQ(value, QValue::Float(1.34f));
delete stm;
}
TEST(VMachine, Branch)
{
ContextPtr ctx(new SimpleContext());
bool trueCalled = false;
bool falseCalled = false;
QValue trueFunc = QValue::Function([&](int32_t argCount, QValue* args, QValue* result) -> Result {
trueCalled = true;
*result = QValue::Nil();
return true;
});
QValue falseFunc = QValue::Function([&](int32_t argCount, QValue* args, QValue* result) -> Result {
falseCalled = true;
*result = QValue::Nil();
return true;
});
VStatement* stm = new BranchStm(new ConstantExpr(QValue::Integer(123), { 0,0 }), nullptr, nullptr, { 0,0 });
Result res = stm->execute(ctx);
ASSERT_FALSE(res);
ASSERT_EQ(res.getErr(), "line 0:0: Subexpression must return a boolean within a Branch");
delete stm;
stm = new BranchStm(
new ConstantExpr(QValue::Bool(false), { 0,0 }),
new VExpressionAsStatement(new CallFunctionExpr(new ConstantExpr(trueFunc, { 0,0 }), 0, nullptr, { 0,0 }), { 0,0 }),
new VExpressionAsStatement(new CallFunctionExpr(new ConstantExpr(falseFunc, { 0,0 }), 0, nullptr, { 0,0 }), { 0,0 }),
{ 0,0 }
);
ASSERT_TRUE(stm->execute(ctx));
EXPECT_FALSE(trueCalled);
EXPECT_TRUE(falseCalled);
trueCalled = false;
falseCalled = false;
delete stm;
stm = new BranchStm(
new ConstantExpr(QValue::Bool(true), { 0,0 }),
new VExpressionAsStatement(new CallFunctionExpr(new ConstantExpr(trueFunc, { 0,0 }), 0, nullptr, { 0,0 }), { 0,0 }),
new VExpressionAsStatement(new CallFunctionExpr(new ConstantExpr(falseFunc, { 0,0 }), 0, nullptr, { 0,0 }), { 0,0 }),
{ 0,0 }
);
ASSERT_TRUE(stm->execute(ctx));
EXPECT_TRUE(trueCalled);
EXPECT_FALSE(falseCalled);
delete stm;
}<|endoftext|> |
<commit_before>#include "typegenerator.h"
#include <fstream>
TypeGenerator::TypeGenerator(string outputPath)
{
mOutputPath = outputPath;
mNamespace = "";
}
TypeGenerator::TypeGenerator(string outputPath, string ns)
{
mOutputPath = outputPath;
mNamespace = ns;
}
TypeGenerator::TypeGenerator(const TypeGenerator &source)
{
*this = source;
}
TypeGenerator::~TypeGenerator()
{
}
TypeGenerator &TypeGenerator::operator=(const TypeGenerator &source)
{
mOutputPath = source.mOutputPath;
mNamespace = source.mNamespace;
return *this;
}
void TypeGenerator::Generate(const XSDElement &element)
{
string typeName = element.get_Name();
ofstream header(mOutputPath +
#ifdef _WIN32
"\\"
#else
"/"
#endif
+ typeName + ".h", ios::out);
header << "#ifndef __" << typeName << "__" << endl;
header << "#define __" << typeName << "__" << endl << endl;
if (mNamespace.length() > 0) header << "namespace " << mNamespace << endl << "{" << endl;
header << "class " << typeName << " : public foo" << endl;
header << "{" << endl;
header << "public:" << endl;
header << typeName << "();" << endl;
header << typeName << "(const " << typeName << " &source);" << endl;
header << "~" << typeName << "();" << endl << endl;
header << typeName << " &operator=(const " << typeName << " &source);" << endl;
header << "protected:" << endl;
header << "private:" << endl;
header << "};" << endl;
if (mNamespace.length() > 0) header << "};" << endl;
header.close();
}
<commit_msg>Added flag<commit_after>#include "typegenerator.h"
#include <fstream>
#include "gflags/gflags.h"
DEFINE_string(output_postfix, "", "Postfix for all generated filenames (i.e. \"generated\" makes type.cpp become type.generated.cpp");
TypeGenerator::TypeGenerator(string outputPath)
{
mOutputPath = outputPath;
mNamespace = "";
}
TypeGenerator::TypeGenerator(string outputPath, string ns)
{
mOutputPath = outputPath;
mNamespace = ns;
}
TypeGenerator::TypeGenerator(const TypeGenerator &source)
{
*this = source;
}
TypeGenerator::~TypeGenerator()
{
}
TypeGenerator &TypeGenerator::operator=(const TypeGenerator &source)
{
mOutputPath = source.mOutputPath;
mNamespace = source.mNamespace;
return *this;
}
void TypeGenerator::Generate(const XSDElement &element)
{
string typeName = element.get_Name();
ofstream header(mOutputPath +
#ifdef _WIN32
"\\"
#else
"/"
#endif
+ typeName + (FLAGS_output_postfix.length() > 0 ? string(".") : "") + FLAGS_output_postfix + ".h", ios::out);
header << "#ifndef __" << typeName << "__" << endl;
header << "#define __" << typeName << "__" << endl << endl;
if (mNamespace.length() > 0) header << "namespace " << mNamespace << endl << "{" << endl;
header << "class " << typeName << " : public foo" << endl;
header << "{" << endl;
header << "public:" << endl;
header << typeName << "();" << endl;
header << typeName << "(const " << typeName << " &source);" << endl;
header << "~" << typeName << "();" << endl << endl;
header << typeName << " &operator=(const " << typeName << " &source);" << endl;
header << "protected:" << endl;
header << "private:" << endl;
header << "};" << endl;
if (mNamespace.length() > 0) header << "};" << endl;
header.close();
}
<|endoftext|> |
<commit_before>#include "base.h"
#include "window.h"
#include "math.h"
#include "input.h"
#include "image.h"
#include "gameobject.h"
#include "tilebar.h"
#include "debugger.h"
TileBar::TileBar() : mSelectedTile(0){
}
TileBar::~TileBar(){
}
void TileBar::Update(){
}
void TileBar::Move(float deltaT){
}
void TileBar::Draw(Camera *cam){
//Draw background
Window::Draw(&mImage, mPhysics.Box(), &(SDL_Rect)mImage.Clip(0));
//Draw the tiles
for (int i = 0; i < mTiles.size(); ++i){
Window::Draw(&mTileImage, mTiles.at(i).Box() + mPhysics.Box().Pos(),
&(SDL_Rect)mTileImage.Clip(mTiles.at(i).Type()));
}
//Draw the selector
//Need a better way to save these offsets?
Window::Draw(&mSelector, Recti((mTiles.at(mSelectedTile).Box().Pos()
+ mPhysics.Box().Pos() - Vector2i(2, 2)), 36, 36));
}
void TileBar::OnMouseUp(){
Vector2f mousePos = Input::MousePos();
//On mouse up select the tile that's highlighted
for (int i = 0; i < mTiles.size(); ++i){
if (Math::CheckCollision(mousePos, (mTiles.at(i).Box() + mPhysics.Box().Pos()))){
mSelectedTile = i;
return;
}
}
}
Tile TileBar::GetSelection(){
return mTiles.at(mSelectedTile);
}
Json::Value TileBar::Save(){
Json::Value val = GameObject::Save();
val["selector"] = mSelector.Save();
val["tiles"]["image"] = mTileImage.Save();
val["type"] = "tilebar";
//Save the tiles
for (int i = 0; i < mTiles.size(); ++i){
val["tiles"]["list"][i] = mTiles.at(i).Save();
}
return val;
}
void TileBar::Load(Json::Value val){
GameObject::Load(val);
mSelector.Load(val["selector"]);
mTileImage.Load(val["tiles"]["image"]);
//Load up the tile positions
for (int i = 0; i < val["tiles"]["list"].size(); ++i){
Tile tempTile;
tempTile.Load(val["tiles"]["list"][i]);
mTiles.push_back(tempTile);
}
}
<commit_msg>remove debugger header from tilebar<commit_after>#include "base.h"
#include "window.h"
#include "math.h"
#include "input.h"
#include "image.h"
#include "gameobject.h"
#include "tilebar.h"
TileBar::TileBar() : mSelectedTile(0){
}
TileBar::~TileBar(){
}
void TileBar::Update(){
}
void TileBar::Move(float deltaT){
}
void TileBar::Draw(Camera *cam){
//Draw background
Window::Draw(&mImage, mPhysics.Box(), &(SDL_Rect)mImage.Clip(0));
//Draw the tiles
for (int i = 0; i < mTiles.size(); ++i){
Window::Draw(&mTileImage, mTiles.at(i).Box() + mPhysics.Box().Pos(),
&(SDL_Rect)mTileImage.Clip(mTiles.at(i).Type()));
}
//Draw the selector
//Need a better way to save these offsets?
Window::Draw(&mSelector, Recti((mTiles.at(mSelectedTile).Box().Pos()
+ mPhysics.Box().Pos() - Vector2i(2, 2)), 36, 36));
}
void TileBar::OnMouseUp(){
Vector2f mousePos = Input::MousePos();
//On mouse up select the tile that's highlighted
for (int i = 0; i < mTiles.size(); ++i){
if (Math::CheckCollision(mousePos, (mTiles.at(i).Box() + mPhysics.Box().Pos()))){
mSelectedTile = i;
return;
}
}
}
Tile TileBar::GetSelection(){
return mTiles.at(mSelectedTile);
}
Json::Value TileBar::Save(){
Json::Value val = GameObject::Save();
val["selector"] = mSelector.Save();
val["tiles"]["image"] = mTileImage.Save();
val["type"] = "tilebar";
//Save the tiles
for (int i = 0; i < mTiles.size(); ++i){
val["tiles"]["list"][i] = mTiles.at(i).Save();
}
return val;
}
void TileBar::Load(Json::Value val){
GameObject::Load(val);
mSelector.Load(val["selector"]);
mTileImage.Load(val["tiles"]["image"]);
//Load up the tile positions
for (int i = 0; i < val["tiles"]["list"].size(); ++i){
Tile tempTile;
tempTile.Load(val["tiles"]["list"][i]);
mTiles.push_back(tempTile);
}
}
<|endoftext|> |
<commit_before>/*****************************************************************/
/* NAME: M.Benjamin, H.Schmidt, J. Leonard */
/* ORGN: NAVSEA Newport RI and MIT Cambridge MA */
/* FILE: BHV_SimpleWaypoint.cpp */
/* DATE: July 1st 2008 (For purposes of simple illustration) */
/* */
/* 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 <cstdlib>
#include <math.h>
#include "BHV_SimpleWaypoint.h"
#include "MBUtils.h"
#include "AngleUtils.h"
#include "BuildUtils.h"
#include "ZAIC_PEAK.h"
#include "OF_Coupler.h"
#include "OF_Reflector.h"
#include "AOF_SimpleWaypoint.h"
using namespace std;
//-----------------------------------------------------------
// Procedure: Constructor
BHV_SimpleWaypoint::BHV_SimpleWaypoint(IvPDomain gdomain) :
IvPBehavior(gdomain)
{
IvPBehavior::setParam("name", "simple_waypoint");
m_domain = subDomain(m_domain, "course,speed");
// All distances are in meters, all speed in meters per second
// Default values for configuration parameters
m_desired_speed = 0;
m_arrival_radius = 10;
m_ipf_type = "zaic";
// Default values for behavior state variables
m_osx = 0;
m_osy = 0;
addInfoVars("NAV_X, NAV_Y");
}
//---------------------------------------------------------------
// Procedure: setParam - handle behavior configuration parameters
bool BHV_SimpleWaypoint::setParam(string param, string val)
{
// Convert the parameter to lower case for more general matching
param = tolower(param);
double double_val = atof(val.c_str());
if((param == "ptx") && (isNumber(val))) {
m_nextpt.set_vx(double_val);
return(true);
}
else if((param == "pty") && (isNumber(val))) {
m_nextpt.set_vy(double_val);
return(true);
}
else if((param == "speed") && (double_val > 0) && (isNumber(val))) {
m_desired_speed = double_val;
return(true);
}
else if((param == "radius") && (double_val > 0) && (isNumber(val))) {
m_arrival_radius = double_val;
return(true);
}
else if(param == "ipf_type") {
val = tolower(val);
if((val == "zaic") || (val == "reflector")) {
m_ipf_type = val;
return(true);
}
}
return(false);
}
//-----------------------------------------------------------
// Procedure: onIdleState
void BHV_SimpleWaypoint::onIdleState()
{
postViewPoint(false);
}
//-----------------------------------------------------------
// Procedure: postViewPoint
void BHV_SimpleWaypoint::postViewPoint(bool viewable)
{
m_nextpt.set_label(m_us_name + "'s next waypoint");
m_nextpt.set_type("waypoint");
m_nextpt.set_source(m_descriptor);
string point_spec;
if(viewable)
point_spec = m_nextpt.get_spec("active=true");
else
point_spec = m_nextpt.get_spec("active=false");
postMessage("VIEW_POINT", point_spec);
}
//-----------------------------------------------------------
// Procedure: onRunState
IvPFunction *BHV_SimpleWaypoint::onRunState()
{
// Part 1: Get vehicle position from InfoBuffer and post a
// warning if problem is encountered
bool ok1, ok2;
m_osx = getBufferDoubleVal("NAV_X", ok1);
m_osy = getBufferDoubleVal("NAV_Y", ok2);
if(!ok1 || !ok2) {
postWMessage("No ownship X/Y info in info_buffer.");
return(0);
}
// Part 2: Determine if the vehicle has reached the destination
// point and if so, declare completion.
#ifdef WIN32
double dist = _hypot((m_nextpt.x()-m_osx), (m_nextpt.y()-m_osy));
#else
double dist = hypot((m_nextpt.x()-m_osx), (m_nextpt.y()-m_osy));
#endif
if(dist <= m_arrival_radius) {
setComplete();
postViewPoint(false);
return(0);
}
// Part 3: Post the waypoint as a string for consumption by
// a viewer application.
postViewPoint(true);
// Part 4: Build the IvP function with either the ZAIC tool
// or the Reflector tool.
IvPFunction *ipf = 0;
if(m_ipf_type == "zaic")
ipf = buildFunctionWithZAIC();
else
ipf = buildFunctionWithReflector();
if(ipf == 0)
postWMessage("Problem Creating the IvP Function");
return(ipf);
}
//-----------------------------------------------------------
// Procedure: buildFunctionWithZAIC
IvPFunction *BHV_SimpleWaypoint::buildFunctionWithZAIC()
{
ZAIC_PEAK spd_zaic(m_domain, "speed");
spd_zaic.setSummit(m_desired_speed);
spd_zaic.setPeakWidth(0.5);
spd_zaic.setBaseWidth(1.0);
spd_zaic.setSummitDelta(0.8);
if(spd_zaic.stateOK() == false) {
string warnings = "Speed ZAIC problems " + spd_zaic.getWarnings();
postWMessage(warnings);
return(0);
}
double rel_ang_to_wpt = relAng(m_osx, m_osy, m_nextpt.x(), m_nextpt.y());
ZAIC_PEAK crs_zaic(m_domain, "course");
crs_zaic.setSummit(rel_ang_to_wpt);
crs_zaic.setPeakWidth(0);
crs_zaic.setBaseWidth(180.0);
crs_zaic.setSummitDelta(0);
crs_zaic.setValueWrap(true);
if(crs_zaic.stateOK() == false) {
string warnings = "Course ZAIC problems " + crs_zaic.getWarnings();
postWMessage(warnings);
return(0);
}
IvPFunction *spd_ipf = spd_zaic.extractIvPFunction();
IvPFunction *crs_ipf = crs_zaic.extractIvPFunction();
OF_Coupler coupler;
IvPFunction *ivp_function = coupler.couple(crs_ipf, spd_ipf, 50, 50);
return(ivp_function);
}
//-----------------------------------------------------------
// Procedure: buildFunctionWithReflector
IvPFunction *BHV_SimpleWaypoint::buildFunctionWithReflector()
{
IvPFunction *ivp_function;
bool ok = true;
AOF_SimpleWaypoint aof_wpt(m_domain);
ok = ok && aof_wpt.setParam("desired_speed", m_desired_speed);
ok = ok && aof_wpt.setParam("osx", m_osx);
ok = ok && aof_wpt.setParam("osy", m_osy);
ok = ok && aof_wpt.setParam("ptx", m_nextpt.x());
ok = ok && aof_wpt.setParam("pty", m_nextpt.y());
ok = ok && aof_wpt.initialize();
if(ok) {
OF_Reflector reflector(&aof_wpt);
reflector.create(600, 500);
ivp_function = reflector.extractIvPFunction();
}
return(ivp_function);
}
<commit_msg><commit_after>/*****************************************************************/
/* NAME: M.Benjamin, H.Schmidt, J. Leonard */
/* ORGN: NAVSEA Newport RI and MIT Cambridge MA */
/* FILE: BHV_SimpleWaypoint.cpp */
/* DATE: July 1st 2008 (For purposes of simple illustration) */
/* */
/* 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 <cstdlib>
#include <math.h>
#include "BHV_SimpleWaypoint.h"
#include "MBUtils.h"
#include "AngleUtils.h"
#include "BuildUtils.h"
#include "ZAIC_PEAK.h"
#include "OF_Coupler.h"
#include "OF_Reflector.h"
#include "AOF_SimpleWaypoint.h"
using namespace std;
//-----------------------------------------------------------
// Procedure: Constructor
BHV_SimpleWaypoint::BHV_SimpleWaypoint(IvPDomain gdomain) :
IvPBehavior(gdomain)
{
IvPBehavior::setParam("name", "simple_waypoint");
m_domain = subDomain(m_domain, "course,speed");
// All distances are in meters, all speed in meters per second
// Default values for configuration parameters
m_desired_speed = 0;
m_arrival_radius = 10;
m_ipf_type = "zaic";
// Default values for behavior state variables
m_osx = 0;
m_osy = 0;
addInfoVars("NAV_X, NAV_Y");
}
//---------------------------------------------------------------
// Procedure: setParam - handle behavior configuration parameters
bool BHV_SimpleWaypoint::setParam(string param, string val)
{
// Convert the parameter to lower case for more general matching
param = tolower(param);
double double_val = atof(val.c_str());
if((param == "ptx") && (isNumber(val))) {
m_nextpt.set_vx(double_val);
return(true);
}
else if((param == "pty") && (isNumber(val))) {
m_nextpt.set_vy(double_val);
return(true);
}
else if((param == "speed") && (double_val > 0) && (isNumber(val))) {
m_desired_speed = double_val;
return(true);
}
else if((param == "radius") && (double_val > 0) && (isNumber(val))) {
m_arrival_radius = double_val;
return(true);
}
else if(param == "ipf_type") {
val = tolower(val);
if((val == "zaic") || (val == "reflector")) {
m_ipf_type = val;
return(true);
}
}
return(false);
}
//-----------------------------------------------------------
// Procedure: onIdleState
void BHV_SimpleWaypoint::onIdleState()
{
postViewPoint(false);
}
//-----------------------------------------------------------
// Procedure: postViewPoint
void BHV_SimpleWaypoint::postViewPoint(bool viewable)
{
m_nextpt.set_label(m_us_name + "'s next waypoint");
string point_spec;
if(viewable)
point_spec = m_nextpt.get_spec("active=true");
else
point_spec = m_nextpt.get_spec("active=false");
postMessage("VIEW_POINT", point_spec);
}
//-----------------------------------------------------------
// Procedure: onRunState
IvPFunction *BHV_SimpleWaypoint::onRunState()
{
// Part 1: Get vehicle position from InfoBuffer and post a
// warning if problem is encountered
bool ok1, ok2;
m_osx = getBufferDoubleVal("NAV_X", ok1);
m_osy = getBufferDoubleVal("NAV_Y", ok2);
if(!ok1 || !ok2) {
postWMessage("No ownship X/Y info in info_buffer.");
return(0);
}
// Part 2: Determine if the vehicle has reached the destination
// point and if so, declare completion.
#ifdef WIN32
double dist = _hypot((m_nextpt.x()-m_osx), (m_nextpt.y()-m_osy));
#else
double dist = hypot((m_nextpt.x()-m_osx), (m_nextpt.y()-m_osy));
#endif
if(dist <= m_arrival_radius) {
setComplete();
postViewPoint(false);
return(0);
}
// Part 3: Post the waypoint as a string for consumption by
// a viewer application.
postViewPoint(true);
// Part 4: Build the IvP function with either the ZAIC tool
// or the Reflector tool.
IvPFunction *ipf = 0;
if(m_ipf_type == "zaic")
ipf = buildFunctionWithZAIC();
else
ipf = buildFunctionWithReflector();
if(ipf == 0)
postWMessage("Problem Creating the IvP Function");
return(ipf);
}
//-----------------------------------------------------------
// Procedure: buildFunctionWithZAIC
IvPFunction *BHV_SimpleWaypoint::buildFunctionWithZAIC()
{
ZAIC_PEAK spd_zaic(m_domain, "speed");
spd_zaic.setSummit(m_desired_speed);
spd_zaic.setPeakWidth(0.5);
spd_zaic.setBaseWidth(1.0);
spd_zaic.setSummitDelta(0.8);
if(spd_zaic.stateOK() == false) {
string warnings = "Speed ZAIC problems " + spd_zaic.getWarnings();
postWMessage(warnings);
return(0);
}
double rel_ang_to_wpt = relAng(m_osx, m_osy, m_nextpt.x(), m_nextpt.y());
ZAIC_PEAK crs_zaic(m_domain, "course");
crs_zaic.setSummit(rel_ang_to_wpt);
crs_zaic.setPeakWidth(0);
crs_zaic.setBaseWidth(180.0);
crs_zaic.setSummitDelta(0);
crs_zaic.setValueWrap(true);
if(crs_zaic.stateOK() == false) {
string warnings = "Course ZAIC problems " + crs_zaic.getWarnings();
postWMessage(warnings);
return(0);
}
IvPFunction *spd_ipf = spd_zaic.extractIvPFunction();
IvPFunction *crs_ipf = crs_zaic.extractIvPFunction();
OF_Coupler coupler;
IvPFunction *ivp_function = coupler.couple(crs_ipf, spd_ipf, 50, 50);
return(ivp_function);
}
//-----------------------------------------------------------
// Procedure: buildFunctionWithReflector
IvPFunction *BHV_SimpleWaypoint::buildFunctionWithReflector()
{
IvPFunction *ivp_function;
bool ok = true;
AOF_SimpleWaypoint aof_wpt(m_domain);
ok = ok && aof_wpt.setParam("desired_speed", m_desired_speed);
ok = ok && aof_wpt.setParam("osx", m_osx);
ok = ok && aof_wpt.setParam("osy", m_osy);
ok = ok && aof_wpt.setParam("ptx", m_nextpt.x());
ok = ok && aof_wpt.setParam("pty", m_nextpt.y());
ok = ok && aof_wpt.initialize();
if(ok) {
OF_Reflector reflector(&aof_wpt);
reflector.create(600, 500);
ivp_function = reflector.extractIvPFunction();
}
return(ivp_function);
}
<|endoftext|> |
<commit_before>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2019 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#include "caf/detail/fnv_hash.hpp"
#include <cstdint>
namespace caf::detail {
namespace {
#if SIZE_MAX == 0xFFFFFFFF
constexpr size_t basis = 2166136261u;
constexpr size_t prime = 16777619u;
#elif SIZE_MAX == 0xFFFFFFFFFFFFFFFF
constexpr size_t basis = 14695981039346656037u;
constexpr size_t prime = 1099511628211u;
#else
# error Platform and/or compiler not supported
#endif
} // namespace
size_t fnv_hash(const unsigned char* first, const unsigned char* last) {
return fnv_hash_append(basis, first, last);
}
size_t fnv_hash_append(size_t intermediate, const unsigned char* first,
const unsigned char* last) {
auto result = intermediate;
for (; first != last; ++first) {
result *= prime;
result ^= *first;
}
return result;
}
} // namespace caf::detail
<commit_msg>Remove stale file<commit_after><|endoftext|> |
<commit_before>#include <libdariadb/storage/lock_manager.h>
#include <libdariadb/utils/exception.h>
#include <libdariadb/utils/logger.h>
#include <sstream>
using namespace dariadb;
using namespace dariadb::storage;
void lock_mutex(LOCK_KIND kind, const RWMutex_Ptr &mtx) {
switch (kind) {
case LOCK_KIND::EXCLUSIVE: {
mtx->mutex.lock();
break;
}
case LOCK_KIND::READ: {
mtx->mutex.lock_shared();
break;
}
case LOCK_KIND::UNKNOW: {
THROW_EXCEPTION("try to lock unknow state");
}
};
}
bool try_lock_mutex(LOCK_KIND kind, const RWMutex_Ptr &mtx) {
switch (kind) {
case LOCK_KIND::EXCLUSIVE: {
return mtx->mutex.try_lock();
}
case LOCK_KIND::READ: {
return mtx->mutex.try_lock_shared();
}
case LOCK_KIND::UNKNOW: {
THROW_EXCEPTION("try to try-lock unknow state");
}
};
return false;
}
void unlock_mutex(const RWMutex_Ptr &mtx) {
switch (mtx->kind) {
case LOCK_KIND::EXCLUSIVE: {
mtx->mutex.unlock();
break;
}
case LOCK_KIND::READ: {
mtx->mutex.unlock_shared();
break;
}
case LOCK_KIND::UNKNOW: {
THROW_EXCEPTION("try to unlock unknow state");
}
};
}
LockManager::~LockManager() {}
LockManager::LockManager(const LockManager::Params ¶m) {}
RWMutex_Ptr LockManager::get_or_create_lock_object(const LOCK_OBJECTS &lo) {
std::lock_guard<std::mutex> lg(_mutex);
auto lock_target_it = _lockers.find(lo);
if (lock_target_it != _lockers.end()) {
return lock_target_it->second;
} else {
RWMutex_Ptr lock_target{new MutexWrap{}};
_lockers.emplace(std::make_pair(lo, lock_target));
return lock_target;
}
}
RWMutex_Ptr LockManager::get_lock_object(const LOCK_OBJECTS &lo) {
std::lock_guard<std::mutex> lg(_mutex);
auto lock_target_it = _lockers.find(lo);
if (lock_target_it != _lockers.end()) {
return lock_target_it->second;
} else {
throw MAKE_EXCEPTION("unlock unknow object.");
}
}
void LockManager::lock(const LOCK_KIND &lk, const LOCK_OBJECTS &lo) {
switch (lo) {
case LOCK_OBJECTS::AOF:
case LOCK_OBJECTS::PAGE:
lock_by_kind(lk, lo);
break;
case LOCK_OBJECTS::DROP_AOF: {
lock_drop_aof();
break;
}
default: {
THROW_EXCEPTION("Unknow LockObject:", (uint8_t)lo);
}
}
}
bool LockManager::try_lock(const LOCK_KIND &lk, const std::vector<LOCK_OBJECTS> &los) {
// TODO refact.
auto mtx_vec_size = los.size();
if (std::find(los.begin(), los.end(), LOCK_OBJECTS::DROP_AOF) != los.end()) {
++mtx_vec_size;
}
std::vector<RWMutex_Ptr> rw_mtx;
rw_mtx.resize(mtx_vec_size);
size_t insert_pos = 0;
for (size_t i = 0; i < los.size(); ++i) {
if (los[i] == LOCK_OBJECTS::DROP_AOF) {
rw_mtx[insert_pos] = get_or_create_lock_object(LOCK_OBJECTS::AOF);
++insert_pos;
rw_mtx[insert_pos] = get_or_create_lock_object(LOCK_OBJECTS::PAGE);
++insert_pos;
} else {
rw_mtx[insert_pos] = get_or_create_lock_object(los[i]);
++insert_pos;
}
}
for (size_t i = 0; i < mtx_vec_size; ++i) {
bool local_status = try_lock_mutex(lk, rw_mtx[i]);
if (!local_status) {
for (size_t j = 0; j < i; ++j) {
unlock_mutex(rw_mtx[j]);
}
return false;
} else {
rw_mtx[i]->kind = lk;
}
}
return true;
}
void LockManager::lock(const LOCK_KIND &lk, const std::vector<LOCK_OBJECTS> &los) {
while (!try_lock(lk, los)) {
std::this_thread::yield();
}
}
void LockManager::unlock(const LOCK_OBJECTS &lo) {
switch (lo) {
case LOCK_OBJECTS::AOF:
case LOCK_OBJECTS::PAGE: {
auto lock_target = get_lock_object(lo);
unlock_mutex(lock_target);
break;
}
case LOCK_OBJECTS::DROP_AOF: {
auto aof_locker = get_lock_object(LOCK_OBJECTS::AOF);
auto pg_locker = get_lock_object(LOCK_OBJECTS::PAGE);
aof_locker->mutex.unlock();
pg_locker->mutex.unlock();
break;
}
}
}
void LockManager::unlock(const std::vector<LOCK_OBJECTS> &los) {
for (auto lo : los) {
this->unlock(lo);
}
}
void LockManager::lock_by_kind(const LOCK_KIND &lk, const LOCK_OBJECTS &lo) {
auto lock_target = get_or_create_lock_object(lo);
lock_mutex(lk, lock_target);
lock_target->kind = lk;
}
void LockManager::lock_drop_aof() {
lock(LOCK_KIND::EXCLUSIVE, {LOCK_OBJECTS::AOF, LOCK_OBJECTS::PAGE});
}
void LockManager::lock_drop_cap() {
lock(LOCK_KIND::EXCLUSIVE, {LOCK_OBJECTS::PAGE, LOCK_OBJECTS::PAGE});
}
<commit_msg>build.<commit_after>#include <libdariadb/storage/lock_manager.h>
#include <libdariadb/utils/exception.h>
#include <libdariadb/utils/logger.h>
#include <sstream>
#include <algorithm>
using namespace dariadb;
using namespace dariadb::storage;
void lock_mutex(LOCK_KIND kind, const RWMutex_Ptr &mtx) {
switch (kind) {
case LOCK_KIND::EXCLUSIVE: {
mtx->mutex.lock();
break;
}
case LOCK_KIND::READ: {
mtx->mutex.lock_shared();
break;
}
case LOCK_KIND::UNKNOW: {
THROW_EXCEPTION("try to lock unknow state");
}
};
}
bool try_lock_mutex(LOCK_KIND kind, const RWMutex_Ptr &mtx) {
switch (kind) {
case LOCK_KIND::EXCLUSIVE: {
return mtx->mutex.try_lock();
}
case LOCK_KIND::READ: {
return mtx->mutex.try_lock_shared();
}
case LOCK_KIND::UNKNOW: {
THROW_EXCEPTION("try to try-lock unknow state");
}
};
return false;
}
void unlock_mutex(const RWMutex_Ptr &mtx) {
switch (mtx->kind) {
case LOCK_KIND::EXCLUSIVE: {
mtx->mutex.unlock();
break;
}
case LOCK_KIND::READ: {
mtx->mutex.unlock_shared();
break;
}
case LOCK_KIND::UNKNOW: {
THROW_EXCEPTION("try to unlock unknow state");
}
};
}
LockManager::~LockManager() {}
LockManager::LockManager(const LockManager::Params ¶m) {}
RWMutex_Ptr LockManager::get_or_create_lock_object(const LOCK_OBJECTS &lo) {
std::lock_guard<std::mutex> lg(_mutex);
auto lock_target_it = _lockers.find(lo);
if (lock_target_it != _lockers.end()) {
return lock_target_it->second;
} else {
RWMutex_Ptr lock_target{new MutexWrap{}};
_lockers.emplace(std::make_pair(lo, lock_target));
return lock_target;
}
}
RWMutex_Ptr LockManager::get_lock_object(const LOCK_OBJECTS &lo) {
std::lock_guard<std::mutex> lg(_mutex);
auto lock_target_it = _lockers.find(lo);
if (lock_target_it != _lockers.end()) {
return lock_target_it->second;
} else {
throw MAKE_EXCEPTION("unlock unknow object.");
}
}
void LockManager::lock(const LOCK_KIND &lk, const LOCK_OBJECTS &lo) {
switch (lo) {
case LOCK_OBJECTS::AOF:
case LOCK_OBJECTS::PAGE:
lock_by_kind(lk, lo);
break;
case LOCK_OBJECTS::DROP_AOF: {
lock_drop_aof();
break;
}
default: {
THROW_EXCEPTION("Unknow LockObject:", (uint8_t)lo);
}
}
}
bool LockManager::try_lock(const LOCK_KIND &lk, const std::vector<LOCK_OBJECTS> &los) {
// TODO refact.
auto mtx_vec_size = los.size();
if (std::find(los.begin(), los.end(), LOCK_OBJECTS::DROP_AOF) != los.end()) {
++mtx_vec_size;
}
std::vector<RWMutex_Ptr> rw_mtx;
rw_mtx.resize(mtx_vec_size);
size_t insert_pos = 0;
for (size_t i = 0; i < los.size(); ++i) {
if (los[i] == LOCK_OBJECTS::DROP_AOF) {
rw_mtx[insert_pos] = get_or_create_lock_object(LOCK_OBJECTS::AOF);
++insert_pos;
rw_mtx[insert_pos] = get_or_create_lock_object(LOCK_OBJECTS::PAGE);
++insert_pos;
} else {
rw_mtx[insert_pos] = get_or_create_lock_object(los[i]);
++insert_pos;
}
}
for (size_t i = 0; i < mtx_vec_size; ++i) {
bool local_status = try_lock_mutex(lk, rw_mtx[i]);
if (!local_status) {
for (size_t j = 0; j < i; ++j) {
unlock_mutex(rw_mtx[j]);
}
return false;
} else {
rw_mtx[i]->kind = lk;
}
}
return true;
}
void LockManager::lock(const LOCK_KIND &lk, const std::vector<LOCK_OBJECTS> &los) {
while (!try_lock(lk, los)) {
std::this_thread::yield();
}
}
void LockManager::unlock(const LOCK_OBJECTS &lo) {
switch (lo) {
case LOCK_OBJECTS::AOF:
case LOCK_OBJECTS::PAGE: {
auto lock_target = get_lock_object(lo);
unlock_mutex(lock_target);
break;
}
case LOCK_OBJECTS::DROP_AOF: {
auto aof_locker = get_lock_object(LOCK_OBJECTS::AOF);
auto pg_locker = get_lock_object(LOCK_OBJECTS::PAGE);
aof_locker->mutex.unlock();
pg_locker->mutex.unlock();
break;
}
}
}
void LockManager::unlock(const std::vector<LOCK_OBJECTS> &los) {
for (auto lo : los) {
this->unlock(lo);
}
}
void LockManager::lock_by_kind(const LOCK_KIND &lk, const LOCK_OBJECTS &lo) {
auto lock_target = get_or_create_lock_object(lo);
lock_mutex(lk, lock_target);
lock_target->kind = lk;
}
void LockManager::lock_drop_aof() {
lock(LOCK_KIND::EXCLUSIVE, {LOCK_OBJECTS::AOF, LOCK_OBJECTS::PAGE});
}
void LockManager::lock_drop_cap() {
lock(LOCK_KIND::EXCLUSIVE, {LOCK_OBJECTS::PAGE, LOCK_OBJECTS::PAGE});
}
<|endoftext|> |
<commit_before>/* -*- C++ -*-; c-basic-offset: 4; indent-tabs-mode: nil */
/*
* Test suite for Processor class.
*
* Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
#include <boost/test/unit_test.hpp>
#include <opflex/comms/comms-internal.hpp>
#include <opflex/logging/internal/logging.hpp>
#include <cstdlib>
#include <boost/test/unit_test_log.hpp>
#include <dlfcn.h>
using opflex::comms::comms_passive_listener;
using opflex::comms::comms_active_connection;
using namespace opflex::comms::internal;
BOOST_AUTO_TEST_SUITE(asynchronous_sockets)
struct CommsTests {
CommsTests() {
LOG(INFO) << "global setup\n";
boost::unit_test::unit_test_log_t::instance().set_threshold_level(::boost::unit_test::log_successful_tests);
}
~CommsTests() {
LOG(INFO) << "global teardown\n";
}
};
BOOST_GLOBAL_FIXTURE( CommsTests );
/**
* A fixture for communications tests
*/
class CommsFixture {
private:
uv_idle_t * idler;
uv_timer_t * timer;
protected:
CommsFixture()
:
idler((typeof(idler))malloc(sizeof(*idler))),
timer((typeof(timer))malloc(sizeof(*timer))) {
LOG(INFO) << "\n\n\n\n\n\n\n\n";
LOG(DEBUG) << "idler = " << idler;
LOG(DEBUG) << "timer = " << timer;
idler->data = timer->data = this;
int rc = opflex::comms::initCommunicationLoop(uv_default_loop());
BOOST_CHECK(!rc);
for (size_t i=0; i < Peer::LoopData::TOTAL_STATES; ++i) {
BOOST_CHECK_EQUAL(Peer::LoopData::getPeerList(uv_default_loop(),
Peer::LoopData::PeerState(i))
->size(), 0);
}
uv_idle_init(uv_default_loop(), idler);
uv_idle_start(idler, check_peer_db_cb);
uv_timer_init(uv_default_loop(), timer);
uv_timer_start(timer, timeout_cb, 1800, 0);
uv_unref((uv_handle_t*) timer);
}
struct PeerDisposer {
void operator()(Peer *peer)
{
LOG(DEBUG) << peer << " destroy() with intent of deleting";
peer->destroy();
}
};
void cleanup() {
LOG(DEBUG);
uv_timer_stop(timer);
uv_idle_stop(idler);
for (size_t i=0; i < Peer::LoopData::TOTAL_STATES; ++i) {
Peer::LoopData::getPeerList(uv_default_loop(),
Peer::LoopData::PeerState(i))
->clear_and_dispose(PeerDisposer());
}
uv_idle_start(idler, wait_for_zero_peers_cb);
}
~CommsFixture() {
uv_close((uv_handle_t *)timer, (uv_close_cb)free);
uv_close((uv_handle_t *)idler, (uv_close_cb)free);
opflex::comms::finiCommunicationLoop(uv_default_loop());
LOG(INFO) << "\n\n\n\n\n\n\n\n";
}
typedef void (*pc)(void);
static size_t required_final_peers;
static pc required_post_conditions;
static bool expect_timeout;
static size_t count_final_peers() {
static std::string oldDbgLog;
std::stringstream dbgLog;
std::string newDbgLog;
size_t final_peers = 0;
size_t m;
if((m=Peer::LoopData::getPeerList(
uv_default_loop(),
internal::Peer::LoopData::ONLINE)->size())) {
final_peers += m;
dbgLog << " online: " << m;
}
if((m=Peer::LoopData::getPeerList(
uv_default_loop(),
internal::Peer::LoopData::RETRY_TO_CONNECT)->size())) {
final_peers += m;
dbgLog << " retry-connecting: " << m;
}
if((m=Peer::LoopData::getPeerList(
uv_default_loop(),
internal::Peer::LoopData::ATTEMPTING_TO_CONNECT)->size())) {
/* this is not a "final" state, from a test's perspective */
dbgLog << " attempting: " << m;
}
if((m=Peer::LoopData::getPeerList(
uv_default_loop(),
internal::Peer::LoopData::RETRY_TO_LISTEN)->size())) {
final_peers += m;
dbgLog << " retry-listening: " << m;
}
if((m=Peer::LoopData::getPeerList(
uv_default_loop(),
internal::Peer::LoopData::LISTENING)->size())) {
final_peers += m;
dbgLog << " listening: " << m;
}
dbgLog << " TOTAL FINAL: " << final_peers << "\0";
newDbgLog = dbgLog.str();
if (oldDbgLog != newDbgLog) {
oldDbgLog = newDbgLog;
LOG(DEBUG) << newDbgLog;
}
return final_peers;
}
static void wait_for_zero_peers_cb(uv_idle_t * handle) {
static size_t old_count;
size_t count = Peer::getCounter();
if (count) {
if (old_count != count) {
LOG(DEBUG) << count << " peers left";
}
old_count = count;
return;
}
LOG(DEBUG) << "no peers left";
uv_idle_stop(handle);
uv_stop(uv_default_loop());
}
static void check_peer_db_cb(uv_idle_t * handle) {
/* check all easily reachable peers' invariants */
for (size_t i=0; i < Peer::LoopData::TOTAL_STATES; ++i) {
Peer::List * pL = Peer::LoopData::getPeerList(uv_default_loop(),
Peer::LoopData::PeerState(i));
for(Peer::List::iterator it = pL->begin(); it != pL->end(); ++it) {
it->__checkInvariants();
}
}
if (count_final_peers() < required_final_peers) {
return;
}
(*required_post_conditions)();
reinterpret_cast<CommsFixture*>(handle->data)->cleanup();
}
static void timeout_cb(uv_timer_t * handle) {
LOG(DEBUG);
if (!expect_timeout) {
BOOST_CHECK(!"the test has timed out");
}
(*required_post_conditions)();
reinterpret_cast<CommsFixture*>(handle->data)->cleanup();
}
void loop_until_final(size_t final_peers, pc post_conditions, bool timeout = false) {
LOG(DEBUG);
required_final_peers = final_peers;
required_post_conditions = post_conditions;
expect_timeout = timeout;
uv_run(uv_default_loop(), UV_RUN_DEFAULT);
}
};
size_t CommsFixture::required_final_peers;
CommsFixture::pc CommsFixture::required_post_conditions;
bool CommsFixture::expect_timeout;
BOOST_FIXTURE_TEST_CASE( test_initialization, CommsFixture ) {
LOG(DEBUG);
}
void pc_successful_connect(void) {
LOG(DEBUG);
/* empty */
BOOST_CHECK_EQUAL(Peer::LoopData::getPeerList(uv_default_loop(),
Peer::LoopData::RETRY_TO_CONNECT)
->size(), 0);
BOOST_CHECK_EQUAL(Peer::LoopData::getPeerList(uv_default_loop(),
Peer::LoopData::RETRY_TO_LISTEN)
->size(), 0);
BOOST_CHECK_EQUAL(Peer::LoopData::getPeerList(uv_default_loop(),
Peer::LoopData::ATTEMPTING_TO_CONNECT)
->size(), 0);
/* non-empty */
BOOST_CHECK_EQUAL(Peer::LoopData::getPeerList(uv_default_loop(),
Peer::LoopData::ONLINE)
->size(), 2);
BOOST_CHECK_EQUAL(Peer::LoopData::getPeerList(uv_default_loop(),
Peer::LoopData::LISTENING)
->size(), 1);
}
class DoNothingOnConnect {
public:
void operator()(opflex::comms::internal::CommunicationPeer * p) {
LOG(INFO) << "chill out, we just had a" << (
p->passive_ ? " pass" : "n act"
) << "ive connection";
}
};
opflex::comms::internal::ConnectionHandler doNothingOnConnect = DoNothingOnConnect();
class StartPingingOnConnect {
public:
void operator()(opflex::comms::internal::CommunicationPeer * p) {
p->startKeepAlive();
}
};
opflex::comms::internal::ConnectionHandler startPingingOnConnect = StartPingingOnConnect();
BOOST_FIXTURE_TEST_CASE( test_ipv4, CommsFixture ) {
LOG(DEBUG);
int rc;
rc = comms_passive_listener(doNothingOnConnect, "127.0.0.1", 65535);
BOOST_CHECK_EQUAL(rc, 0);
rc = comms_active_connection(doNothingOnConnect, "localhost", "65535");
BOOST_CHECK_EQUAL(rc, 0);
loop_until_final(3, pc_successful_connect);
}
BOOST_FIXTURE_TEST_CASE( test_ipv6, CommsFixture ) {
LOG(DEBUG);
int rc;
rc = comms_passive_listener(doNothingOnConnect, "::1", 65534);
BOOST_CHECK_EQUAL(rc, 0);
rc = comms_active_connection(doNothingOnConnect, "localhost", "65534");
BOOST_CHECK_EQUAL(rc, 0);
loop_until_final(3, pc_successful_connect);
}
static void pc_non_existent(void) {
LOG(DEBUG);
/* non-empty */
BOOST_CHECK_EQUAL(Peer::LoopData::getPeerList(uv_default_loop(),
Peer::LoopData::RETRY_TO_CONNECT)
->size(), 1);
/* empty */
BOOST_CHECK_EQUAL(Peer::LoopData::getPeerList(uv_default_loop(),
Peer::LoopData::RETRY_TO_LISTEN)
->size(), 0);
BOOST_CHECK_EQUAL(Peer::LoopData::getPeerList(uv_default_loop(),
Peer::LoopData::ATTEMPTING_TO_CONNECT)
->size(), 0);
BOOST_CHECK_EQUAL(Peer::LoopData::getPeerList(uv_default_loop(),
Peer::LoopData::ONLINE)
->size(), 0);
BOOST_CHECK_EQUAL(Peer::LoopData::getPeerList(uv_default_loop(),
Peer::LoopData::LISTENING)
->size(), 0);
}
BOOST_FIXTURE_TEST_CASE( test_non_existent_host, CommsFixture ) {
LOG(DEBUG);
int rc = comms_active_connection(doNothingOnConnect, "non_existent_host.", "65533");
BOOST_CHECK_EQUAL(rc, 0);
loop_until_final(1, pc_non_existent);
}
BOOST_FIXTURE_TEST_CASE( test_non_existent_service, CommsFixture ) {
LOG(DEBUG);
int rc = comms_active_connection(doNothingOnConnect, "127.0.0.1", "65533");
BOOST_CHECK_EQUAL(rc, 0);
loop_until_final(1, pc_non_existent);
}
BOOST_FIXTURE_TEST_CASE( test_keepalive, CommsFixture ) {
LOG(DEBUG);
int rc;
rc = comms_passive_listener(startPingingOnConnect, "::1", 65532);
BOOST_CHECK_EQUAL(rc, 0);
rc = comms_active_connection(startPingingOnConnect, "::1", "65532");
BOOST_CHECK_EQUAL(rc, 0);
loop_until_final(4, pc_successful_connect, true); // 4 is to cause a timeout
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>verbose logging of peer DB checks<commit_after>/* -*- C++ -*-; c-basic-offset: 4; indent-tabs-mode: nil */
/*
* Test suite for Processor class.
*
* Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
#include <boost/test/unit_test.hpp>
#include <opflex/comms/comms-internal.hpp>
#include <opflex/logging/internal/logging.hpp>
#include <cstdlib>
#include <boost/test/unit_test_log.hpp>
#include <dlfcn.h>
using opflex::comms::comms_passive_listener;
using opflex::comms::comms_active_connection;
using namespace opflex::comms::internal;
BOOST_AUTO_TEST_SUITE(asynchronous_sockets)
struct CommsTests {
CommsTests() {
LOG(INFO) << "global setup\n";
boost::unit_test::unit_test_log_t::instance().set_threshold_level(::boost::unit_test::log_successful_tests);
}
~CommsTests() {
LOG(INFO) << "global teardown\n";
}
};
BOOST_GLOBAL_FIXTURE( CommsTests );
/**
* A fixture for communications tests
*/
class CommsFixture {
private:
uv_idle_t * idler;
uv_timer_t * timer;
protected:
CommsFixture()
:
idler((typeof(idler))malloc(sizeof(*idler))),
timer((typeof(timer))malloc(sizeof(*timer))) {
LOG(INFO) << "\n\n\n\n\n\n\n\n";
LOG(DEBUG) << "idler = " << idler;
LOG(DEBUG) << "timer = " << timer;
idler->data = timer->data = this;
int rc = opflex::comms::initCommunicationLoop(uv_default_loop());
BOOST_CHECK(!rc);
for (size_t i=0; i < Peer::LoopData::TOTAL_STATES; ++i) {
BOOST_CHECK_EQUAL(Peer::LoopData::getPeerList(uv_default_loop(),
Peer::LoopData::PeerState(i))
->size(), 0);
}
uv_idle_init(uv_default_loop(), idler);
uv_idle_start(idler, check_peer_db_cb);
uv_timer_init(uv_default_loop(), timer);
uv_timer_start(timer, timeout_cb, 1800, 0);
uv_unref((uv_handle_t*) timer);
}
struct PeerDisposer {
void operator()(Peer *peer)
{
LOG(DEBUG) << peer << " destroy() with intent of deleting";
peer->destroy();
}
};
void cleanup() {
LOG(DEBUG);
uv_timer_stop(timer);
uv_idle_stop(idler);
for (size_t i=0; i < Peer::LoopData::TOTAL_STATES; ++i) {
Peer::LoopData::getPeerList(uv_default_loop(),
Peer::LoopData::PeerState(i))
->clear_and_dispose(PeerDisposer());
}
uv_idle_start(idler, wait_for_zero_peers_cb);
}
~CommsFixture() {
uv_close((uv_handle_t *)timer, (uv_close_cb)free);
uv_close((uv_handle_t *)idler, (uv_close_cb)free);
opflex::comms::finiCommunicationLoop(uv_default_loop());
LOG(INFO) << "\n\n\n\n\n\n\n\n";
}
typedef void (*pc)(void);
static size_t required_final_peers;
static pc required_post_conditions;
static bool expect_timeout;
static size_t count_final_peers() {
static std::string oldDbgLog;
std::stringstream dbgLog;
std::string newDbgLog;
size_t final_peers = 0;
size_t m;
if((m=Peer::LoopData::getPeerList(
uv_default_loop(),
internal::Peer::LoopData::ONLINE)->size())) {
final_peers += m;
dbgLog << " online: " << m;
}
if((m=Peer::LoopData::getPeerList(
uv_default_loop(),
internal::Peer::LoopData::RETRY_TO_CONNECT)->size())) {
final_peers += m;
dbgLog << " retry-connecting: " << m;
}
if((m=Peer::LoopData::getPeerList(
uv_default_loop(),
internal::Peer::LoopData::ATTEMPTING_TO_CONNECT)->size())) {
/* this is not a "final" state, from a test's perspective */
dbgLog << " attempting: " << m;
}
if((m=Peer::LoopData::getPeerList(
uv_default_loop(),
internal::Peer::LoopData::RETRY_TO_LISTEN)->size())) {
final_peers += m;
dbgLog << " retry-listening: " << m;
}
if((m=Peer::LoopData::getPeerList(
uv_default_loop(),
internal::Peer::LoopData::LISTENING)->size())) {
final_peers += m;
dbgLog << " listening: " << m;
}
dbgLog << " TOTAL FINAL: " << final_peers << "\0";
newDbgLog = dbgLog.str();
if (oldDbgLog != newDbgLog) {
oldDbgLog = newDbgLog;
LOG(DEBUG) << newDbgLog;
}
return final_peers;
}
static void wait_for_zero_peers_cb(uv_idle_t * handle) {
static size_t old_count;
size_t count = Peer::getCounter();
if (count) {
if (old_count != count) {
LOG(DEBUG) << count << " peers left";
}
old_count = count;
return;
}
LOG(DEBUG) << "no peers left";
uv_idle_stop(handle);
uv_stop(uv_default_loop());
}
static void check_peer_db_cb(uv_idle_t * handle) {
static std::string oldDbgLog;
std::stringstream dbgLog;
std::string newDbgLog;
/* check all easily reachable peers' invariants */
for (size_t i=0; i < Peer::LoopData::TOTAL_STATES; ++i) {
Peer::List * pL = Peer::LoopData::getPeerList(uv_default_loop(),
Peer::LoopData::PeerState(i));
dbgLog << " pL #" << i << " @" << pL;
for(Peer::List::iterator it = pL->begin(); it != pL->end(); ++it) {
dbgLog << " peer " << &*it;
it->__checkInvariants();
}
}
newDbgLog = dbgLog.str();
if (oldDbgLog != newDbgLog) {
oldDbgLog = newDbgLog;
LOG(DEBUG) << newDbgLog;
}
if (count_final_peers() < required_final_peers) {
return;
}
(*required_post_conditions)();
reinterpret_cast<CommsFixture*>(handle->data)->cleanup();
}
static void timeout_cb(uv_timer_t * handle) {
LOG(DEBUG);
if (!expect_timeout) {
BOOST_CHECK(!"the test has timed out");
}
(*required_post_conditions)();
reinterpret_cast<CommsFixture*>(handle->data)->cleanup();
}
void loop_until_final(size_t final_peers, pc post_conditions, bool timeout = false) {
LOG(DEBUG);
required_final_peers = final_peers;
required_post_conditions = post_conditions;
expect_timeout = timeout;
uv_run(uv_default_loop(), UV_RUN_DEFAULT);
}
};
size_t CommsFixture::required_final_peers;
CommsFixture::pc CommsFixture::required_post_conditions;
bool CommsFixture::expect_timeout;
BOOST_FIXTURE_TEST_CASE( test_initialization, CommsFixture ) {
LOG(DEBUG);
}
void pc_successful_connect(void) {
LOG(DEBUG);
/* empty */
BOOST_CHECK_EQUAL(Peer::LoopData::getPeerList(uv_default_loop(),
Peer::LoopData::RETRY_TO_CONNECT)
->size(), 0);
BOOST_CHECK_EQUAL(Peer::LoopData::getPeerList(uv_default_loop(),
Peer::LoopData::RETRY_TO_LISTEN)
->size(), 0);
BOOST_CHECK_EQUAL(Peer::LoopData::getPeerList(uv_default_loop(),
Peer::LoopData::ATTEMPTING_TO_CONNECT)
->size(), 0);
/* non-empty */
BOOST_CHECK_EQUAL(Peer::LoopData::getPeerList(uv_default_loop(),
Peer::LoopData::ONLINE)
->size(), 2);
BOOST_CHECK_EQUAL(Peer::LoopData::getPeerList(uv_default_loop(),
Peer::LoopData::LISTENING)
->size(), 1);
}
class DoNothingOnConnect {
public:
void operator()(opflex::comms::internal::CommunicationPeer * p) {
LOG(INFO) << "chill out, we just had a" << (
p->passive_ ? " pass" : "n act"
) << "ive connection";
}
};
opflex::comms::internal::ConnectionHandler doNothingOnConnect = DoNothingOnConnect();
class StartPingingOnConnect {
public:
void operator()(opflex::comms::internal::CommunicationPeer * p) {
p->startKeepAlive();
}
};
opflex::comms::internal::ConnectionHandler startPingingOnConnect = StartPingingOnConnect();
BOOST_FIXTURE_TEST_CASE( test_ipv4, CommsFixture ) {
LOG(DEBUG);
int rc;
rc = comms_passive_listener(doNothingOnConnect, "127.0.0.1", 65535);
BOOST_CHECK_EQUAL(rc, 0);
rc = comms_active_connection(doNothingOnConnect, "localhost", "65535");
BOOST_CHECK_EQUAL(rc, 0);
loop_until_final(3, pc_successful_connect);
}
BOOST_FIXTURE_TEST_CASE( test_ipv6, CommsFixture ) {
LOG(DEBUG);
int rc;
rc = comms_passive_listener(doNothingOnConnect, "::1", 65534);
BOOST_CHECK_EQUAL(rc, 0);
rc = comms_active_connection(doNothingOnConnect, "localhost", "65534");
BOOST_CHECK_EQUAL(rc, 0);
loop_until_final(3, pc_successful_connect);
}
static void pc_non_existent(void) {
LOG(DEBUG);
/* non-empty */
BOOST_CHECK_EQUAL(Peer::LoopData::getPeerList(uv_default_loop(),
Peer::LoopData::RETRY_TO_CONNECT)
->size(), 1);
/* empty */
BOOST_CHECK_EQUAL(Peer::LoopData::getPeerList(uv_default_loop(),
Peer::LoopData::RETRY_TO_LISTEN)
->size(), 0);
BOOST_CHECK_EQUAL(Peer::LoopData::getPeerList(uv_default_loop(),
Peer::LoopData::ATTEMPTING_TO_CONNECT)
->size(), 0);
BOOST_CHECK_EQUAL(Peer::LoopData::getPeerList(uv_default_loop(),
Peer::LoopData::ONLINE)
->size(), 0);
BOOST_CHECK_EQUAL(Peer::LoopData::getPeerList(uv_default_loop(),
Peer::LoopData::LISTENING)
->size(), 0);
}
BOOST_FIXTURE_TEST_CASE( test_non_existent_host, CommsFixture ) {
LOG(DEBUG);
int rc = comms_active_connection(doNothingOnConnect, "non_existent_host.", "65533");
BOOST_CHECK_EQUAL(rc, 0);
loop_until_final(1, pc_non_existent);
}
BOOST_FIXTURE_TEST_CASE( test_non_existent_service, CommsFixture ) {
LOG(DEBUG);
int rc = comms_active_connection(doNothingOnConnect, "127.0.0.1", "65533");
BOOST_CHECK_EQUAL(rc, 0);
loop_until_final(1, pc_non_existent);
}
BOOST_FIXTURE_TEST_CASE( test_keepalive, CommsFixture ) {
LOG(DEBUG);
int rc;
rc = comms_passive_listener(startPingingOnConnect, "::1", 65532);
BOOST_CHECK_EQUAL(rc, 0);
rc = comms_active_connection(startPingingOnConnect, "::1", "65532");
BOOST_CHECK_EQUAL(rc, 0);
loop_until_final(4, pc_successful_connect, true); // 4 is to cause a timeout
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>/*
Copyright (C) 2008 by Jorrit Tyberghein
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csqsqrt.h"
#include "csutil/cscolor.h"
#include "csutil/cscolor.h"
#include "csgeom/math3d.h"
#include "cstool/simplestaticlighter.h"
#include "csgfx/renderbuffer.h"
#include "imesh/genmesh.h"
#include "iengine/mesh.h"
#include "iengine/light.h"
#include "iengine/movable.h"
#include "iengine/sector.h"
#include "iengine/engine.h"
#include "imesh/object.h"
namespace CS
{
namespace Lighting
{
void SimpleStaticLighter::ConstantColor (iMeshWrapper* mesh, const csColor4& color)
{
iMeshFactoryWrapper* meshfact = mesh->GetFactory ();
if (!meshfact) return;
csRef<iGeneralFactoryState> fact_state = scfQueryInterface<
iGeneralFactoryState> (meshfact->GetMeshObjectFactory ());
if (!fact_state) return; // Not a mesh we recognize.
size_t count = fact_state->GetVertexCount ();
csRef<iRenderBuffer> rbuf = csRenderBuffer::CreateRenderBuffer (
count, CS_BUF_STATIC, CS_BUFCOMP_FLOAT, 4);
CS_ALLOC_STACK_ARRAY (csColor4, colors, count);
size_t i;
for (i = 0 ; i < count ; i++)
colors[i] = color;
rbuf->CopyInto (colors, count);
csRef<iGeneralMeshState> state = scfQueryInterface<iGeneralMeshState> (mesh->GetMeshObject ());
state->AddRenderBuffer ("static color", rbuf);
}
void SimpleStaticLighter::CalculateLighting (iMeshWrapper* mesh,
iGeneralFactoryState* fact_state, iLight* light,
ShadowType shadow_type, csColor4* colors, bool init)
{
size_t count = fact_state->GetVertexCount ();
size_t i;
csVector3 center = light->GetMovable ()->GetFullTransform ().GetOrigin ();
iSector* light_sector = light->GetMovable ()->GetSectors ()->Get (0);
csReversibleTransform mesh_trans = mesh->GetMovable ()->GetFullTransform ();
if (shadow_type == CS_SHADOW_CENTER)
{
csSectorHitBeamResult rc = light_sector->HitBeamPortals (center,
mesh_trans.GetOrigin ());
if (rc.mesh != 0 && rc.mesh != mesh)
{
// Shadow.
if (init)
for (i = 0 ; i < count ; i++)
colors[i] = csColor4 (0, 0, 0, 0);
return;
}
}
else if (shadow_type == CS_SHADOW_BOUNDINGBOX)
{
const csBox3& world_box = mesh->GetWorldBoundingBox ();
bool shadowed = true;
for (i = 0 ; shadowed && i < 8 ; i++)
{
csSectorHitBeamResult rc = light_sector->HitBeamPortals (center,
world_box.GetCorner (i));
if (rc.mesh == 0 || rc.mesh == mesh) shadowed = false;
}
if (shadowed)
{
// Shadow.
if (init)
for (i = 0 ; i < count ; i++)
colors[i] = csColor4 (0, 0, 0, 0);
return;
}
}
// Shaders multiply by 2. So we need to divide by 2 here.
csColor color = 0.5f * light->GetColor ();
float sqcutoff = light->GetCutoffDistance ();
sqcutoff *= sqcutoff;
csVector3* verts = fact_state->GetVertices ();
csVector3* normals = fact_state->GetNormals ();
if (shadow_type != CS_SHADOW_FULL)
{
// Transform light to object space here since we don't have to do
// full accurate shadows anyway.
center = mesh_trans.Other2This (center);
for (i = 0 ; i < count ; i++)
{
csVector3 relpos = center-verts[i];
float dist = relpos * relpos;
bool dark = init;
if (dist < sqcutoff)
{
dist = sqrt (dist);
float bright = light->GetBrightnessAtDistance (dist);
bright *= normals[i] * relpos;
if (bright > SMALL_EPSILON)
{
if (init)
colors[i] = color * bright;
else
colors[i] += color * bright;
colors[i].Clamp (1.0, 1.0, 1.0);
dark = false;
}
}
if (dark) colors[i].Set (0, 0, 0, 0);
}
}
else
{
// With full shadows we need world space coordinates to be
// able to check the shadow beams.
bool mesh_trans_identity = mesh_trans.IsIdentity ();
for (i = 0 ; i < count ; i++)
{
csVector3 vworld;
if (mesh_trans_identity)
vworld = verts[i];
else
vworld = mesh_trans.This2Other (verts[i]);
csVector3 relpos = center-vworld;
float dist = relpos * relpos;
bool dark = init;
if (dist < sqcutoff)
{
dist = sqrt (dist);
float bright = light->GetBrightnessAtDistance (dist);
bright *= normals[i] * relpos;
if (bright > SMALL_EPSILON)
{
csSectorHitBeamResult rc = light_sector->HitBeamPortals (center, vworld);
if (rc.mesh == 0 || rc.mesh == mesh)
{
if (init)
colors[i] = color * bright;
else
colors[i] += color * bright;
colors[i].Clamp (1.0, 1.0, 1.0);
dark = false;
}
}
}
if (dark) colors[i].Set (0, 0, 0, 0);
}
}
}
void SimpleStaticLighter::ShineLight (iMeshWrapper* mesh, iLight* light,
ShadowType shadow_type)
{
iMeshFactoryWrapper* meshfact = mesh->GetFactory ();
if (!meshfact) return;
csRef<iGeneralFactoryState> fact_state = scfQueryInterface<
iGeneralFactoryState> (meshfact->GetMeshObjectFactory ());
if (!fact_state) return; // Not a mesh we recognize.
size_t count = fact_state->GetVertexCount ();
csRef<iRenderBuffer> rbuf = csRenderBuffer::CreateRenderBuffer (
count, CS_BUF_STATIC, CS_BUFCOMP_FLOAT, 4);
CS_ALLOC_STACK_ARRAY (csColor4, colors, count);
CalculateLighting (mesh, fact_state, light, shadow_type, colors, true);
rbuf->CopyInto (colors, count);
csRef<iGeneralMeshState> state = scfQueryInterface<iGeneralMeshState> (mesh->GetMeshObject ());
state->AddRenderBuffer ("static color", rbuf);
}
void SimpleStaticLighter::ShineLights (iMeshWrapper* mesh, iEngine* engine, int maxlights,
ShadowType shadow_type)
{
iMovable* movable = mesh->GetMovable ();
if (!movable->InSector ()) return; // No movable, do nothing.
const csBox3& world_box = mesh->GetWorldBoundingBox ();
CS_ALLOC_STACK_ARRAY (iLight*, lights, maxlights);
size_t num = engine->GetNearbyLights (movable->GetSectors ()->Get (0),
world_box, lights, maxlights);
if (num == 0)
{
ConstantColor (mesh, csColor4 (0, 0, 0, 0));
return;
}
if (num == 1)
{
ShineLight (mesh, lights[0], shadow_type);
return;
}
iMeshFactoryWrapper* meshfact = mesh->GetFactory ();
if (!meshfact) return;
csRef<iGeneralFactoryState> fact_state = scfQueryInterface<
iGeneralFactoryState> (meshfact->GetMeshObjectFactory ());
if (!fact_state) return; // Not a mesh we recognize.
size_t count = fact_state->GetVertexCount ();
csRef<iRenderBuffer> rbuf = csRenderBuffer::CreateRenderBuffer (
count, CS_BUF_STATIC, CS_BUFCOMP_FLOAT, 4);
CS_ALLOC_STACK_ARRAY (csColor4, colors, count);
size_t l;
for (l = 0 ; l < num ; l++)
{
iLight* light = lights[l];
CalculateLighting (mesh, fact_state, light, shadow_type, colors, l == 0);
}
rbuf->CopyInto (colors, count);
csRef<iGeneralMeshState> state = scfQueryInterface<iGeneralMeshState> (mesh->GetMeshObject ());
state->AddRenderBuffer ("static color", rbuf);
}
void SimpleStaticLighter::ShineLights (iSector* sector, iEngine* engine, int maxlights,
ShadowType shadow_type)
{
iMeshList* meshes = sector->GetMeshes ();
size_t i;
for (i = 0 ; i < (size_t)meshes->GetCount () ; i++)
{
iMeshWrapper* mesh = meshes->Get (i);
ShineLights (mesh, engine, maxlights, shadow_type);
}
}
} // namespace Lighting
} // namespace CS
//---------------------------------------------------------------------------
<commit_msg>Fixed simple static lighting. Everything is a lot darker now.<commit_after>/*
Copyright (C) 2008 by Jorrit Tyberghein
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csqsqrt.h"
#include "csutil/cscolor.h"
#include "csutil/cscolor.h"
#include "csgeom/math3d.h"
#include "cstool/simplestaticlighter.h"
#include "csgfx/renderbuffer.h"
#include "imesh/genmesh.h"
#include "iengine/mesh.h"
#include "iengine/light.h"
#include "iengine/movable.h"
#include "iengine/sector.h"
#include "iengine/engine.h"
#include "imesh/object.h"
namespace CS
{
namespace Lighting
{
void SimpleStaticLighter::ConstantColor (iMeshWrapper* mesh, const csColor4& color)
{
iMeshFactoryWrapper* meshfact = mesh->GetFactory ();
if (!meshfact) return;
csRef<iGeneralFactoryState> fact_state = scfQueryInterface<
iGeneralFactoryState> (meshfact->GetMeshObjectFactory ());
if (!fact_state) return; // Not a mesh we recognize.
size_t count = fact_state->GetVertexCount ();
csRef<iRenderBuffer> rbuf = csRenderBuffer::CreateRenderBuffer (
count, CS_BUF_STATIC, CS_BUFCOMP_FLOAT, 4);
CS_ALLOC_STACK_ARRAY (csColor4, colors, count);
size_t i;
for (i = 0 ; i < count ; i++)
colors[i] = color;
rbuf->CopyInto (colors, count);
csRef<iGeneralMeshState> state = scfQueryInterface<iGeneralMeshState> (mesh->GetMeshObject ());
state->AddRenderBuffer ("static color", rbuf);
}
void SimpleStaticLighter::CalculateLighting (iMeshWrapper* mesh,
iGeneralFactoryState* fact_state, iLight* light,
ShadowType shadow_type, csColor4* colors, bool init)
{
size_t count = fact_state->GetVertexCount ();
size_t i;
csVector3 center = light->GetMovable ()->GetFullTransform ().GetOrigin ();
iSector* light_sector = light->GetMovable ()->GetSectors ()->Get (0);
csReversibleTransform mesh_trans = mesh->GetMovable ()->GetFullTransform ();
if (shadow_type == CS_SHADOW_CENTER)
{
csSectorHitBeamResult rc = light_sector->HitBeamPortals (center,
mesh_trans.GetOrigin ());
if (rc.mesh != 0 && rc.mesh != mesh)
{
// Shadow.
if (init)
for (i = 0 ; i < count ; i++)
colors[i] = csColor4 (0, 0, 0, 0);
return;
}
}
else if (shadow_type == CS_SHADOW_BOUNDINGBOX)
{
const csBox3& world_box = mesh->GetWorldBoundingBox ();
bool shadowed = true;
for (i = 0 ; shadowed && i < 8 ; i++)
{
csSectorHitBeamResult rc = light_sector->HitBeamPortals (center,
world_box.GetCorner (i));
if (rc.mesh == 0 || rc.mesh == mesh) shadowed = false;
}
if (shadowed)
{
// Shadow.
if (init)
for (i = 0 ; i < count ; i++)
colors[i] = csColor4 (0, 0, 0, 0);
return;
}
}
// Shaders multiply by 2. So we need to divide by 2 here.
csColor color = 0.5f * light->GetColor ();
float sqcutoff = light->GetCutoffDistance ();
sqcutoff *= sqcutoff;
csVector3* verts = fact_state->GetVertices ();
csVector3* normals = fact_state->GetNormals ();
if (shadow_type != CS_SHADOW_FULL)
{
// Transform light to object space here since we don't have to do
// full accurate shadows anyway.
center = mesh_trans.Other2This (center);
for (i = 0 ; i < count ; i++)
{
csVector3 relpos = center-verts[i];
float dist = relpos * relpos;
bool dark = init;
if (dist < sqcutoff)
{
dist = sqrt (dist);
float bright = light->GetBrightnessAtDistance (dist);
bright *= (normals[i] * relpos) / relpos.Norm ();
if (bright > SMALL_EPSILON)
{
if (init)
colors[i] = color * bright;
else
colors[i] += color * bright;
colors[i].Clamp (1.0, 1.0, 1.0);
dark = false;
}
}
if (dark) colors[i].Set (0, 0, 0, 0);
}
}
else
{
// With full shadows we need world space coordinates to be
// able to check the shadow beams.
bool mesh_trans_identity = mesh_trans.IsIdentity ();
for (i = 0 ; i < count ; i++)
{
csVector3 vworld;
if (mesh_trans_identity)
vworld = verts[i];
else
vworld = mesh_trans.This2Other (verts[i]);
csVector3 relpos = center-vworld;
float dist = relpos * relpos;
bool dark = init;
if (dist < sqcutoff)
{
dist = sqrt (dist);
float bright = light->GetBrightnessAtDistance (dist);
bright *= (normals[i] * relpos) / relpos.Norm ();
if (bright > SMALL_EPSILON)
{
csSectorHitBeamResult rc = light_sector->HitBeamPortals (center, vworld);
if (rc.mesh == 0 || rc.mesh == mesh)
{
if (init)
colors[i] = color * bright;
else
colors[i] += color * bright;
colors[i].Clamp (1.0, 1.0, 1.0);
dark = false;
}
}
}
if (dark) colors[i].Set (0, 0, 0, 0);
}
}
}
void SimpleStaticLighter::ShineLight (iMeshWrapper* mesh, iLight* light,
ShadowType shadow_type)
{
iMeshFactoryWrapper* meshfact = mesh->GetFactory ();
if (!meshfact) return;
csRef<iGeneralFactoryState> fact_state = scfQueryInterface<
iGeneralFactoryState> (meshfact->GetMeshObjectFactory ());
if (!fact_state) return; // Not a mesh we recognize.
size_t count = fact_state->GetVertexCount ();
csRef<iRenderBuffer> rbuf = csRenderBuffer::CreateRenderBuffer (
count, CS_BUF_STATIC, CS_BUFCOMP_FLOAT, 4);
CS_ALLOC_STACK_ARRAY (csColor4, colors, count);
CalculateLighting (mesh, fact_state, light, shadow_type, colors, true);
rbuf->CopyInto (colors, count);
csRef<iGeneralMeshState> state = scfQueryInterface<iGeneralMeshState> (mesh->GetMeshObject ());
state->AddRenderBuffer ("static color", rbuf);
}
void SimpleStaticLighter::ShineLights (iMeshWrapper* mesh, iEngine* engine, int maxlights,
ShadowType shadow_type)
{
iMovable* movable = mesh->GetMovable ();
if (!movable->InSector ()) return; // No movable, do nothing.
const csBox3& world_box = mesh->GetWorldBoundingBox ();
CS_ALLOC_STACK_ARRAY (iLight*, lights, maxlights);
size_t num = engine->GetNearbyLights (movable->GetSectors ()->Get (0),
world_box, lights, maxlights);
if (num == 0)
{
ConstantColor (mesh, csColor4 (0, 0, 0, 0));
return;
}
if (num == 1)
{
ShineLight (mesh, lights[0], shadow_type);
return;
}
iMeshFactoryWrapper* meshfact = mesh->GetFactory ();
if (!meshfact) return;
csRef<iGeneralFactoryState> fact_state = scfQueryInterface<
iGeneralFactoryState> (meshfact->GetMeshObjectFactory ());
if (!fact_state) return; // Not a mesh we recognize.
size_t count = fact_state->GetVertexCount ();
csRef<iRenderBuffer> rbuf = csRenderBuffer::CreateRenderBuffer (
count, CS_BUF_STATIC, CS_BUFCOMP_FLOAT, 4);
CS_ALLOC_STACK_ARRAY (csColor4, colors, count);
size_t l;
for (l = 0 ; l < num ; l++)
{
iLight* light = lights[l];
CalculateLighting (mesh, fact_state, light, shadow_type, colors, l == 0);
}
rbuf->CopyInto (colors, count);
csRef<iGeneralMeshState> state = scfQueryInterface<iGeneralMeshState> (mesh->GetMeshObject ());
state->AddRenderBuffer ("static color", rbuf);
}
void SimpleStaticLighter::ShineLights (iSector* sector, iEngine* engine, int maxlights,
ShadowType shadow_type)
{
iMeshList* meshes = sector->GetMeshes ();
size_t i;
for (i = 0 ; i < (size_t)meshes->GetCount () ; i++)
{
iMeshWrapper* mesh = meshes->Get (i);
ShineLights (mesh, engine, maxlights, shadow_type);
}
}
} // namespace Lighting
} // namespace CS
//---------------------------------------------------------------------------
<|endoftext|> |
<commit_before>#include "utils.hpp"
#include <dlfcn.h>
#include <blobs-ipmid/manager.hpp>
#include <experimental/filesystem>
#include <memory>
#include <phosphor-logging/log.hpp>
#include <regex>
namespace blobs
{
namespace fs = std::experimental::filesystem;
using namespace phosphor::logging;
using HandlerFactory = std::unique_ptr<GenericBlobInterface> (*)();
void loadLibraries(const std::string& path)
{
void* libHandle = NULL;
HandlerFactory factory;
auto* manager = getBlobManager();
for (const auto& p : fs::recursive_directory_iterator(path))
{
auto ps = p.path().string();
/* The bitbake recipe symlinks the library lib*.so.? into the folder
* only, and not the other names, .so, .so.?.?, .so.?.?.?
*
* Therefore only care if it's lib*.so.?
*/
if (!std::regex_match(ps, std::regex(".+\\.so\\.\\d+$")))
{
continue;
}
libHandle = dlopen(ps.c_str(), RTLD_NOW | RTLD_GLOBAL);
if (!libHandle)
{
log<level::ERR>("ERROR opening", entry("HANDLER=%s", ps.c_str()),
entry("ERROR=%s", dlerror()));
continue;
}
dlerror(); /* Clear any previous error. */
factory =
reinterpret_cast<HandlerFactory>(dlsym(libHandle, "createHandler"));
const char* error = dlerror();
if (error)
{
log<level::ERR>("ERROR loading symbol",
entry("HANDLER=%s", ps.c_str()),
entry("ERROR=%s", error));
continue;
}
std::unique_ptr<GenericBlobInterface> result = factory();
if (!result)
{
log<level::ERR>("Unable to create handler",
entry("HANDLER=%s", ps.c_str()));
continue;
}
manager->registerHandler(std::move(result));
}
}
} // namespace blobs
<commit_msg>copyright: add missing copyright headers<commit_after>/*
* Copyright 2018 Google 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 "utils.hpp"
#include <dlfcn.h>
#include <blobs-ipmid/manager.hpp>
#include <experimental/filesystem>
#include <memory>
#include <phosphor-logging/log.hpp>
#include <regex>
namespace blobs
{
namespace fs = std::experimental::filesystem;
using namespace phosphor::logging;
using HandlerFactory = std::unique_ptr<GenericBlobInterface> (*)();
void loadLibraries(const std::string& path)
{
void* libHandle = NULL;
HandlerFactory factory;
auto* manager = getBlobManager();
for (const auto& p : fs::recursive_directory_iterator(path))
{
auto ps = p.path().string();
/* The bitbake recipe symlinks the library lib*.so.? into the folder
* only, and not the other names, .so, .so.?.?, .so.?.?.?
*
* Therefore only care if it's lib*.so.?
*/
if (!std::regex_match(ps, std::regex(".+\\.so\\.\\d+$")))
{
continue;
}
libHandle = dlopen(ps.c_str(), RTLD_NOW | RTLD_GLOBAL);
if (!libHandle)
{
log<level::ERR>("ERROR opening", entry("HANDLER=%s", ps.c_str()),
entry("ERROR=%s", dlerror()));
continue;
}
dlerror(); /* Clear any previous error. */
factory =
reinterpret_cast<HandlerFactory>(dlsym(libHandle, "createHandler"));
const char* error = dlerror();
if (error)
{
log<level::ERR>("ERROR loading symbol",
entry("HANDLER=%s", ps.c_str()),
entry("ERROR=%s", error));
continue;
}
std::unique_ptr<GenericBlobInterface> result = factory();
if (!result)
{
log<level::ERR>("Unable to create handler",
entry("HANDLER=%s", ps.c_str()));
continue;
}
manager->registerHandler(std::move(result));
}
}
} // namespace blobs
<|endoftext|> |
<commit_before>#include <iostream>
#include <set>
#include <string>
#include <sstream>
#include <stdlib.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>
#include "llvm/IR/Constants.h"
#include "llvm/Assembly/Writer.h"
#include "llvm/Support/InstIterator.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Support/CFG.h"
#include "functions.h"
#include "InstructionVisitor.h"
#include "PredicateNames.h"
#include "DirInfo.h"
using namespace llvm;
using namespace std;
int main(int argc, char *argv[]) {
if (argc < 2) {
errs() << "Expected an LLVM IR file or directory.\n";
exit(1);
}
if(mkdir(DirInfo::factsDir, 0777) != 0) {
if(errno == EEXIST) {
//delete all previous contents
clearFactsDir(DirInfo::factsDir);
}
else {
perror("mkdir()");
exit(1);
}
}
else {
if(mkdir(DirInfo::entitiesDir, 0777) != 0) {
perror("mkdir()");
exit(1);
}
if(mkdir(DirInfo::predicatesDir, 0777) != 0) {
perror("mkdir()");
exit(1);
}
}
char *path = realpath(argv[1], NULL);
vector<string> IRFiles;
if(isDir(path)) {
getIRFilesfromDir(path, IRFiles);
}
else {
IRFiles.push_back(path);
}
LLVMContext &Context = getGlobalContext();
SMDiagnostic Err;
// Type sets and maps
set<const Type *> types;
set<const Type *> componentTypes;
map<string, const Type *> variable;
map<string, const Type *> immediate;
for(int i = 0; i < IRFiles.size(); ++i) {
Module *Mod = ParseIRFile(IRFiles[i], Err, Context);
char *real_path = realpath(IRFiles[i].c_str(), NULL);
string varId;
string value_str;
raw_string_ostream rso(value_str);
InstructionVisitor IV(variable, immediate, Mod);
// iterating over global variables in a module
for (Module::const_global_iterator gi = Mod->global_begin(), E = Mod->global_end(); gi != E; ++gi) {
value_str.clear();
WriteAsOperand(rso, gi, 0, Mod);
string globName = "<" + string(real_path) + ">:" + rso.str();
writeGlobalVar(gi, globName);
types.insert(gi->getType());
}
// iterating over global alias in a module
for (Module::const_alias_iterator ga = Mod->alias_begin(), E = Mod->alias_end(); ga != E; ++ga) {
value_str.clear();
WriteAsOperand(rso, ga, 0, Mod);
string gal = "<" + string(real_path) + ">:" + rso.str();
writeGlobalAlias(ga, gal);
types.insert(ga->getType());
}
// iterating over functions in a module
for (Module::iterator fi = Mod->begin(), fi_end = Mod->end(); fi != fi_end; ++fi) {
string funcId = "<" + string(real_path) + ">:" + string(fi->getName());
string instrId = funcId + ":";
IV.setInstrId(instrId);
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::Func).c_str(), "%s\n", funcId);
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::FuncType).c_str(),
"%s\t%t\n", funcId, printType(fi->getFunctionType()));
types.insert(fi->getFunctionType());
if(strlen(writeLinkage(fi->getLinkage()))) {
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::FuncLink).c_str(),
"%s\t%s\n", funcId, writeLinkage(fi->getLinkage()));
}
if(strlen(writeVisibility(fi->getVisibility()))) {
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::FuncVis).c_str(),
"%s\t%s\n", funcId, writeVisibility(fi->getVisibility()));
}
if(fi->getCallingConv() != CallingConv::C) {
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::FuncCallConv).c_str(),
"%s\t%s\n", funcId, writeCallingConv(fi->getCallingConv()));
}
if(fi->getAlignment()) {
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::FuncAlign).c_str(),
"%s\t%s\n", funcId, fi->getAlignment());
}
if(fi->hasGC()) {
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::FuncGc).c_str(),
"%s\t%s\n", funcId, fi->getGC());
}
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::FuncName).c_str(),
"%s\t%@s\n", funcId, fi->getName().str());
if(fi->hasUnnamedAddr()) {
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::FuncUnnamedAddr).c_str(),
"%s\n", funcId);
}
const AttributeSet &Attrs = fi->getAttributes();
if (Attrs.hasAttributes(AttributeSet::ReturnIndex)) {
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::FuncRetAttr).c_str(),
"%s\t%s\n", funcId, Attrs.getAsString(AttributeSet::ReturnIndex));
}
vector<string> FuncnAttr;
writeFnAttributes(Attrs, FuncnAttr);
for (int i = 0; i < FuncnAttr.size(); ++i) {
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::FuncAttr).c_str(),
"%s\t%s\n", funcId, FuncnAttr[i]);
}
if (!fi->isDeclaration()) {
if(fi->hasSection()) {
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::FuncSect).c_str(),
"%s\t%s\n", funcId, fi->getSection());
}
int index = 0;
for (Function::arg_iterator arg = fi->arg_begin(), arg_end = fi->arg_end(); arg != arg_end; ++arg) {
value_str.clear();
WriteAsOperand(rso, arg, 0, Mod);
varId = instrId + rso.str();
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::FuncParam).c_str(),
"%s\t%d\t%s\n", funcId, index, varId);
variable[varId] = arg->getType();
index++;
}
}
int counter = 0;
//iterating over basic blocks in a function
for (Function::iterator bi = fi->begin(), bi_end = fi->end(); bi != bi_end; ++bi) {
string bbId = funcId + ":";
value_str.clear();
WriteAsOperand(rso, bi, 0, Mod);
varId = bbId + rso.str();
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::variable).c_str(),
"%s\n", varId);
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::variableType).c_str(),
"%s\t%s\n", varId, "label");
for(pred_iterator pi = pred_begin(bi), pi_end = pred_end(bi); pi != pi_end; ++pi) {
value_str.clear();
WriteAsOperand(rso, *pi, 0, Mod);
string predBB = bbId + rso.str();
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::basicBlockPred).c_str(),
"%s\t%s\n", varId, predBB);
}
//iterating over instructions in a basic block
for (BasicBlock::iterator i = bi->begin(), i_end = bi->end(); i != i_end; ++i) {
Instruction *ii = dyn_cast<Instruction>(&*i);
string instrNum = instrId + static_cast<ostringstream*>(&(ostringstream()<< counter))->str();
counter++;
if(!ii->getType()->isVoidTy()) {
value_str.clear();
WriteAsOperand(rso, ii, 0, Mod);
varId = instrId + rso.str();
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::insnTo).c_str(),
"%s\t%s\n", instrNum, varId);
variable[varId] = ii->getType();
}
if(++i != i_end){
if(Instruction* next = dyn_cast<Instruction>(ii->getNextNode())) {
string instrNext = instrId + static_cast<ostringstream*>(&(ostringstream()<< counter))->str();
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::insnNext).c_str(),
"%s\t%s\n", instrNum, instrNext);
}
}
i--;
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::insnFunc).c_str(),
"%s\t%s\n", instrNum, funcId);
value_str.clear();
WriteAsOperand(rso, ii->getParent(), 0, Mod);
varId = instrId + rso.str();
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::insnBBEntry).c_str(),
"%s\t%s\n", instrNum, varId);
// Instruction Visitor
IV.setInstrNum(instrNum);
IV.visit(*i);
}
}
}
free(real_path);
delete Mod;
}
// Immediate
for (map<string, const Type *>::iterator it = immediate.begin(); it != immediate.end(); ++it) {
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::immediate).c_str(), "%s\n", it->first);
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::immediateType).c_str(),
"%s\t%t\n", it->first, printType(it->second));
types.insert(it->second);
}
// Variable
for (map<string, const Type *>::iterator it = variable.begin(); it != variable.end(); ++it) {
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::variable).c_str(), "%s\n", it->first);
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::variableType).c_str(),
"%s\t%t\n", it->first, printType(it->second));
types.insert(it->second);
}
// Types
for (set<const Type *>::iterator it = types.begin(); it != types.end(); ++it) {
const Type *type = dyn_cast<Type>(*it);
identifyType(type, componentTypes);
}
//TODO: Do we need to write other primitives manually?
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::primitiveType).c_str(),
"%s\n", "void");
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::primitiveType).c_str(),
"%s\n", "label");
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::primitiveType).c_str(),
"%s\n", "metadata");
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::primitiveType).c_str(),
"%s\n", "x86mmx");
for (set<const Type *>::iterator it = componentTypes.begin(); it != componentTypes.end(); ++it) {
const Type *type = dyn_cast<Type>(*it);
if (type->isIntegerTy()) {
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::intType).c_str(),
"%t\n", printType(type));
}
else if (type->isPrimitiveType()) {
if(type->isFloatingPointTy()) {
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::fpType).c_str(),
"%t\n", printType(type));
}
else {
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::primitiveType).c_str(),
"%t\n", printType(type));
}
}
else if(type->isPointerTy()) {
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::ptrType).c_str(),
"%t\n", printType(type));
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::ptrTypeComp).c_str(),
"%t\t\%t\n", printType(type), printType(type->getPointerElementType()));
if(unsigned AddressSpace = type->getPointerAddressSpace()) {
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::ptrTypeAddrSpace).c_str(),
"%t\t\%d\n", printType(type), AddressSpace);
}
}
else if(type->isArrayTy()) {
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::arrayType).c_str(),
"%t\n", printType(type));
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::arrayTypeSize).c_str(),
"%t\t%d\n", printType(type), (int)type->getArrayNumElements());
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::arrayTypeComp).c_str(),
"%t\t\%t\n", printType(type), printType(type->getArrayElementType()));
}
else if(type->isStructTy()) {
const StructType *strTy = cast<StructType>(type);
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::structType).c_str(),
"%t\n", printType(strTy));
if(strTy->isOpaque()) {
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::opaqueStructType).c_str(),
"%t\n", printType(strTy));
}
else {
for (unsigned int i = 0; i < strTy->getStructNumElements(); ++i) {
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::structTypeField).c_str(),
"%t\t%d\t%t\n", printType(strTy), i, printType(strTy->getStructElementType(i)));
}
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::structTypeNFields).c_str(),
"%t\t%d\n", printType(strTy), strTy->getStructNumElements());
}
}
else if(type->isVectorTy()) {
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::vectorType).c_str(),
"%t\n", printType(type));
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::vectorTypeComp).c_str(),
"%t\t\%t\n", printType(type), printType(type->getVectorElementType()));
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::vectorTypeSize).c_str(),
"%t\t%d\n", printType(type), type->getVectorNumElements());
}
else if(type->isFunctionTy()) {
const FunctionType *funcType = cast<FunctionType>(type);
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::funcType).c_str(),
"%t\n", printType(funcType));
//TODO: which predicate/entity do we need to update for varagrs?
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::funcTypeReturn).c_str(),
"%t\t%t\n", printType(funcType), printType(funcType->getReturnType()));
for (unsigned int par = 0; par < funcType->getFunctionNumParams(); ++par) {
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::funcTypeParam).c_str(),
"%t\t%d\t%t\n", printType(funcType), par, printType(funcType->getFunctionParamType(par)));
}
printFactsToFile(PredicateNames::predNameToFilename(PredicateNames::funcTypeNParams).c_str(),
"%t\t%d\n", printType(funcType), funcType->getFunctionNumParams());
}
else {
type->dump();
errs() << ": invalid type in componentTypes set.\n";
}
}
return 0;
}
//g++ -g *.cpp -std=c++0x `llvm-config --cxxflags --ldflags | sed s/-fno-rtti//` -lLLVM-3.3 -o th
<commit_msg>Removing module processing from main and adding command line argumets handling<commit_after>#include <iostream>
#include <set>
#include <string>
#include <sstream>
#include <stdlib.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <boost/program_options.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/filesystem.hpp>
#include "llvm/IR/Constants.h"
#include "llvm/Assembly/Writer.h"
#include "llvm/Support/InstIterator.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Support/CFG.h"
#include "InstructionVisitor.h"
#include "PredicateNames.h"
#include "DirInfo.h"
using namespace llvm;
using namespace std;
using namespace boost::program_options;
using namespace boost::filesystem;
DirInfo *DirInfo::INSTANCE = NULL;
options_description desc("Usage");
variables_map optionVals;
bool isDir(const char *path) {
bool dir = false;
struct stat buf;
if(stat(path, &buf) == -1)
{
perror("stat()");
exit(1);
}
if((buf.st_mode & S_IFMT ) == S_IFDIR) {
dir = true;
}
else if((buf.st_mode & S_IFMT ) == S_IFREG) {
dir = false;
}
else {
errs() << path << ":Unknown File Format\n";
exit(1);
}
return dir;
}
void getIRFilesfromDir(const char * dirName, vector<string> &files) {
//TODO: use boost
DIR *dir;
struct dirent *entry;
string path;
if((dir = opendir(dirName)) == NULL) {
perror ("opendir()");
exit(1);
}
while((entry = readdir(dir)) != NULL) {
if(strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..")) {
path = string(dirName) + "/" + string(entry->d_name);
if(isDir(path.c_str())) {
getIRFilesfromDir(path.c_str(), files);
}
else {
files.push_back(path.c_str());
}
}
}
closedir(dir);
}
void registerOptions(){
//TODO: add positional argument for in-dir
desc.add_options()
("help,h", "show help message")
("in-dir,i", value<string>(), "directory that contains llvm bitcode files")
("out-dir,o", value<string>(), "facts output directory")
("delim,d", value<char>(), "delimiter for csv files (default \\t)")
;
}
void parseOptions(int argc, char *argv[]){
store(parse_command_line(argc, argv, desc), optionVals);
notify(optionVals);
if(optionVals.count("help")){
cout << desc << "\n";
exit(EXIT_SUCCESS);
}
if(!optionVals.count("in-dir")){
cerr << "Missing input directory" << endl;
cerr << desc << "\n";
exit(EXIT_FAILURE);
}
if(!optionVals.count("out-dir")){
cerr << "Missing output directory" << endl;
cerr << desc << "\n";
exit(EXIT_FAILURE);
}
DirInfo *dirs = DirInfo::getInstance();
if(!dirs->setFactsDir(optionVals["out-dir"].as<string>())){
cerr << "Unable to create output directories, exiting..." << endl;
exit(EXIT_FAILURE);
}
if(!dirs->setInputDir(optionVals["in-dir"].as<string>())){
cerr << "Error while opening input direcotry, exiting..." << endl;
exit(EXIT_FAILURE);
}
}
int main(int argc, char *argv[]) {
registerOptions();
parseOptions(argc, argv);
vector<string> IRFiles;
DirInfo * dirs = DirInfo::getInstance();
getIRFilesfromDir(dirs->getInputDir().c_str(), IRFiles);
LLVMContext &Context = getGlobalContext();
SMDiagnostic Err;
CsvGenerator *csvGen = CsvGenerator::getInstance();
for(int i = 0; i < IRFiles.size(); ++i) {
Module *Mod = ParseIRFile(IRFiles[i], Err, Context);
//TODO: check if parsing .ll file fails
string realPath = string(realpath(IRFiles[i].c_str(), NULL));
csvGen->processModule(Mod, realPath);
delete Mod;
}
csvGen->writeVarsTypesAndImmediates();
csvGen->destroy();
exit(EXIT_SUCCESS);
}
<|endoftext|> |
<commit_before>#include <errno.h>
#include <nan.h>
#include <sys/ioctl.h>
#include <linux/spi/spidev.h>
#include "spidevice.h"
#include "transfer.h"
#include "util.h"
// TODO Make sure it works when the message array is empty
static int Transfer(
int fd,
spi_ioc_transfer *spiTransfers,
uint32_t transferCount
) {
return ioctl(fd, SPI_IOC_MESSAGE(transferCount), spiTransfers);
}
class TransferWorker : public SpiAsyncWorker {
public:
TransferWorker(
Nan::Callback *callback,
int fd,
v8::Local<v8::Array> &message,
spi_ioc_transfer *spiTransfers,
uint32_t transferCount
) : SpiAsyncWorker(callback),
fd_(fd),
spiTransfers_(spiTransfers),
transferCount_(transferCount) {
SaveToPersistent("message", message);
}
~TransferWorker() {
}
void Execute() {
int ret = Transfer(fd_, spiTransfers_, transferCount_);
free(spiTransfers_);
if (ret == -1) {
SetErrorNo(errno);
SetErrorSyscall("transfer");
}
}
void HandleOKCallback() {
Nan::HandleScope scope;
v8::Local<v8::Value> message = GetFromPersistent("message");
v8::Local<v8::Value> argv[] = {
Nan::Null(),
message
};
callback->Call(2, argv);
}
private:
int fd_;
spi_ioc_transfer *spiTransfers_;
uint32_t transferCount_;
};
static int32_t ToSpiTransfers(
v8::Local<v8::Array> &message,
spi_ioc_transfer *spiTransfers
) {
for (unsigned i = 0; i < message->Length(); ++i) {
// Transfer
v8::Local<v8::Value> transfer = message->Get(i);
if (!transfer->IsObject()) {
Nan::ThrowError(
Nan::ErrnoException(
EINVAL, "toSpiTransfers", "a transfer should be an object"
)
);
return -1;
}
v8::Local<v8::Object> msg = v8::Local<v8::Object>::Cast(transfer);
// byteLength
v8::Local<v8::Value> byteLength =
Nan::Get(msg, Nan::New<v8::String>("byteLength").ToLocalChecked()).
ToLocalChecked();
if (byteLength->IsUndefined()) {
Nan::ThrowError(
Nan::ErrnoException(
EINVAL, "toSpiTransfers", "transfer byteLength not specified"
)
);
return -1;
} else if (!byteLength->IsUint32()) {
Nan::ThrowError(
Nan::ErrnoException(
EINVAL,
"toSpiTransfers",
"transfer byteLength should be an unsigned integer"
)
);
return -1;
}
uint32_t length = byteLength->Uint32Value();
spiTransfers[i].len = length;
// sendBuffer
v8::Local<v8::Value> sendBuffer =
Nan::Get(msg, Nan::New<v8::String>("sendBuffer").ToLocalChecked()).
ToLocalChecked();
if (sendBuffer->IsNull() || sendBuffer->IsUndefined()) {
// No sendBuffer so tx_buf should be NULL. This is already the case.
} else if (node::Buffer::HasInstance(sendBuffer)) {
if (node::Buffer::Length(sendBuffer) < length) {
Nan::ThrowError(
Nan::ErrnoException(
EINVAL,
"toSpiTransfers",
"transfer sendBuffer contains less than byteLength bytes"
)
);
return -1;
}
spiTransfers[i].tx_buf = (__u64) node::Buffer::Data(sendBuffer);
} else {
Nan::ThrowError(
Nan::ErrnoException(
EINVAL,
"toSpiTransfers",
"transfer sendBuffer should be null, undefined, or a Buffer object"
)
);
return -1;
}
// receiveBuffer
v8::Local<v8::Value> receiveBuffer =
Nan::Get(msg, Nan::New<v8::String>("receiveBuffer").ToLocalChecked()).
ToLocalChecked();
if (receiveBuffer->IsNull() || receiveBuffer->IsUndefined()) {
// No receiveBuffer so rx_buf should be NULL. This is already the case.
} else if (node::Buffer::HasInstance(receiveBuffer)) {
if (node::Buffer::Length(receiveBuffer) < length) {
Nan::ThrowError(
Nan::ErrnoException(
EINVAL,
"toSpiTransfers",
"transfer receiveBuffer contains less than byteLength bytes"
)
);
return -1;
}
spiTransfers[i].rx_buf = (__u64) node::Buffer::Data(receiveBuffer);
} else {
Nan::ThrowError(
Nan::ErrnoException(
EINVAL,
"toSpiTransfers",
"transfer receiveBuffer should be null, undefined, or a Buffer object"
)
);
return -1;
}
// sendBuffer and receiveBuffer
if ((sendBuffer->IsNull() || sendBuffer->IsUndefined()) &&
(receiveBuffer->IsNull() || receiveBuffer->IsUndefined())) {
Nan::ThrowError(
Nan::ErrnoException(
EINVAL,
"toSpiTransfers",
"transfer contains neither a sendBuffer nor a receiveBuffer"
)
);
return -1;
}
// speed
v8::Local<v8::Value> speed = Nan::Get(msg,
Nan::New<v8::String>("speed").ToLocalChecked()).ToLocalChecked();
if (speed->IsUndefined()) {
// No speed defined, nothing to do.
} else if (!speed->IsUint32()) {
Nan::ThrowError(
Nan::ErrnoException(
EINVAL,
"toSpiTransfers",
"transfer speed should be an unsigned integer"
)
);
return -1;
} else {
spiTransfers[i].speed_hz = speed->Uint32Value();
}
// chipSelectChange
v8::Local<v8::Value> chipSelectChange =
Nan::Get(msg, Nan::New<v8::String>("chipSelectChange").ToLocalChecked()).
ToLocalChecked();
if (chipSelectChange->IsUndefined()) {
// No chipSelectChange defined, nothing to do.
} else if (!chipSelectChange->IsBoolean()) {
Nan::ThrowError(
Nan::ErrnoException(
EINVAL,
"toSpiTransfers",
"transfer chipSelectChange should be a boolean"
)
);
return -1;
} else {
spiTransfers[i].cs_change = chipSelectChange->BooleanValue() ? 1 : 0;
}
}
return 0;
}
void Transfer(Nan::NAN_METHOD_ARGS_TYPE info) {
SpiDevice *device = Nan::ObjectWrap::Unwrap<SpiDevice>(info.This());
int fd = device->Fd();
if (fd == -1) {
return Nan::ThrowError(
Nan::ErrnoException(
EPERM, "transfer", "device closed, operation not permitted"
)
);
}
if (info.Length() < 2 ||
!info[0]->IsArray() ||
!info[1]->IsFunction()) {
return Nan::ThrowError(
Nan::ErrnoException(
EINVAL,
"transfer",
"incorrect arguments passed to transfer(message, cb)"
)
);
}
v8::Local<v8::Array> message = info[0].As<v8::Array>();
Nan::Callback *callback = new Nan::Callback(info[1].As<v8::Function>());
spi_ioc_transfer *spiTransfers = (spi_ioc_transfer *)
malloc(message->Length() * sizeof(spi_ioc_transfer));
memset(spiTransfers, 0, message->Length() * sizeof(spi_ioc_transfer));
if (ToSpiTransfers(message, spiTransfers) == -1) {
free(spiTransfers);
return;
}
Nan::AsyncQueueWorker(new TransferWorker(
callback,
fd,
message,
spiTransfers,
message->Length()
));
info.GetReturnValue().Set(info.This());
}
void TransferSync(Nan::NAN_METHOD_ARGS_TYPE info) {
SpiDevice *device = Nan::ObjectWrap::Unwrap<SpiDevice>(info.This());
int fd = device->Fd();
if (fd == -1) {
return Nan::ThrowError(
Nan::ErrnoException(
EPERM, "transferSync", "device closed, operation not permitted"
)
);
}
if (info.Length() < 1 || !info[0]->IsArray()) {
return Nan::ThrowError(
Nan::ErrnoException(
EINVAL,
"transfer",
"incorrect arguments passed to transferSync(message)"
)
);
}
v8::Local<v8::Array> message = info[0].As<v8::Array>();
spi_ioc_transfer *spiTransfers = (spi_ioc_transfer *)
malloc(message->Length() * sizeof(spi_ioc_transfer));
memset(spiTransfers, 0, message->Length() * sizeof(spi_ioc_transfer));
if (ToSpiTransfers(message, spiTransfers) == 0) {
if (Transfer(fd, spiTransfers, message->Length()) == -1) {
Nan::ThrowError(Nan::ErrnoException(errno, "transferSync", ""));
}
}
free(spiTransfers);
info.GetReturnValue().Set(info.This());
}
<commit_msg>use the word must rather than should in error messages<commit_after>#include <errno.h>
#include <nan.h>
#include <sys/ioctl.h>
#include <linux/spi/spidev.h>
#include "spidevice.h"
#include "transfer.h"
#include "util.h"
// TODO Make sure it works when the message array is empty
static int Transfer(
int fd,
spi_ioc_transfer *spiTransfers,
uint32_t transferCount
) {
return ioctl(fd, SPI_IOC_MESSAGE(transferCount), spiTransfers);
}
class TransferWorker : public SpiAsyncWorker {
public:
TransferWorker(
Nan::Callback *callback,
int fd,
v8::Local<v8::Array> &message,
spi_ioc_transfer *spiTransfers,
uint32_t transferCount
) : SpiAsyncWorker(callback),
fd_(fd),
spiTransfers_(spiTransfers),
transferCount_(transferCount) {
SaveToPersistent("message", message);
}
~TransferWorker() {
}
void Execute() {
int ret = Transfer(fd_, spiTransfers_, transferCount_);
free(spiTransfers_);
if (ret == -1) {
SetErrorNo(errno);
SetErrorSyscall("transfer");
}
}
void HandleOKCallback() {
Nan::HandleScope scope;
v8::Local<v8::Value> message = GetFromPersistent("message");
v8::Local<v8::Value> argv[] = {
Nan::Null(),
message
};
callback->Call(2, argv);
}
private:
int fd_;
spi_ioc_transfer *spiTransfers_;
uint32_t transferCount_;
};
static int32_t ToSpiTransfers(
v8::Local<v8::Array> &message,
spi_ioc_transfer *spiTransfers
) {
for (unsigned i = 0; i < message->Length(); ++i) {
// Transfer
v8::Local<v8::Value> transfer = message->Get(i);
if (!transfer->IsObject()) {
Nan::ThrowError(
Nan::ErrnoException(
EINVAL, "toSpiTransfers", "a transfer must be an object"
)
);
return -1;
}
v8::Local<v8::Object> msg = v8::Local<v8::Object>::Cast(transfer);
// byteLength
v8::Local<v8::Value> byteLength =
Nan::Get(msg, Nan::New<v8::String>("byteLength").ToLocalChecked()).
ToLocalChecked();
if (byteLength->IsUndefined()) {
Nan::ThrowError(
Nan::ErrnoException(
EINVAL, "toSpiTransfers", "transfer byteLength not specified"
)
);
return -1;
} else if (!byteLength->IsUint32()) {
Nan::ThrowError(
Nan::ErrnoException(
EINVAL,
"toSpiTransfers",
"transfer byteLength must be an unsigned integer"
)
);
return -1;
}
uint32_t length = byteLength->Uint32Value();
spiTransfers[i].len = length;
// sendBuffer
v8::Local<v8::Value> sendBuffer =
Nan::Get(msg, Nan::New<v8::String>("sendBuffer").ToLocalChecked()).
ToLocalChecked();
if (sendBuffer->IsNull() || sendBuffer->IsUndefined()) {
// No sendBuffer so tx_buf must be NULL. This is already the case.
} else if (node::Buffer::HasInstance(sendBuffer)) {
if (node::Buffer::Length(sendBuffer) < length) {
Nan::ThrowError(
Nan::ErrnoException(
EINVAL,
"toSpiTransfers",
"transfer sendBuffer contains less than byteLength bytes"
)
);
return -1;
}
spiTransfers[i].tx_buf = (__u64) node::Buffer::Data(sendBuffer);
} else {
Nan::ThrowError(
Nan::ErrnoException(
EINVAL,
"toSpiTransfers",
"transfer sendBuffer must be null, undefined, or a Buffer object"
)
);
return -1;
}
// receiveBuffer
v8::Local<v8::Value> receiveBuffer =
Nan::Get(msg, Nan::New<v8::String>("receiveBuffer").ToLocalChecked()).
ToLocalChecked();
if (receiveBuffer->IsNull() || receiveBuffer->IsUndefined()) {
// No receiveBuffer so rx_buf must be NULL. This is already the case.
} else if (node::Buffer::HasInstance(receiveBuffer)) {
if (node::Buffer::Length(receiveBuffer) < length) {
Nan::ThrowError(
Nan::ErrnoException(
EINVAL,
"toSpiTransfers",
"transfer receiveBuffer contains less than byteLength bytes"
)
);
return -1;
}
spiTransfers[i].rx_buf = (__u64) node::Buffer::Data(receiveBuffer);
} else {
Nan::ThrowError(
Nan::ErrnoException(
EINVAL,
"toSpiTransfers",
"transfer receiveBuffer must be null, undefined, or a Buffer object"
)
);
return -1;
}
// sendBuffer and receiveBuffer
if ((sendBuffer->IsNull() || sendBuffer->IsUndefined()) &&
(receiveBuffer->IsNull() || receiveBuffer->IsUndefined())) {
Nan::ThrowError(
Nan::ErrnoException(
EINVAL,
"toSpiTransfers",
"transfer contains neither a sendBuffer nor a receiveBuffer"
)
);
return -1;
}
// speed
v8::Local<v8::Value> speed = Nan::Get(msg,
Nan::New<v8::String>("speed").ToLocalChecked()).ToLocalChecked();
if (speed->IsUndefined()) {
// No speed defined, nothing to do.
} else if (!speed->IsUint32()) {
Nan::ThrowError(
Nan::ErrnoException(
EINVAL,
"toSpiTransfers",
"transfer speed must be an unsigned integer"
)
);
return -1;
} else {
spiTransfers[i].speed_hz = speed->Uint32Value();
}
// chipSelectChange
v8::Local<v8::Value> chipSelectChange =
Nan::Get(msg, Nan::New<v8::String>("chipSelectChange").ToLocalChecked()).
ToLocalChecked();
if (chipSelectChange->IsUndefined()) {
// No chipSelectChange defined, nothing to do.
} else if (!chipSelectChange->IsBoolean()) {
Nan::ThrowError(
Nan::ErrnoException(
EINVAL,
"toSpiTransfers",
"transfer chipSelectChange must be a boolean"
)
);
return -1;
} else {
spiTransfers[i].cs_change = chipSelectChange->BooleanValue() ? 1 : 0;
}
}
return 0;
}
void Transfer(Nan::NAN_METHOD_ARGS_TYPE info) {
SpiDevice *device = Nan::ObjectWrap::Unwrap<SpiDevice>(info.This());
int fd = device->Fd();
if (fd == -1) {
return Nan::ThrowError(
Nan::ErrnoException(
EPERM, "transfer", "device closed, operation not permitted"
)
);
}
if (info.Length() < 2 ||
!info[0]->IsArray() ||
!info[1]->IsFunction()) {
return Nan::ThrowError(
Nan::ErrnoException(
EINVAL,
"transfer",
"incorrect arguments passed to transfer(message, cb)"
)
);
}
v8::Local<v8::Array> message = info[0].As<v8::Array>();
Nan::Callback *callback = new Nan::Callback(info[1].As<v8::Function>());
spi_ioc_transfer *spiTransfers = (spi_ioc_transfer *)
malloc(message->Length() * sizeof(spi_ioc_transfer));
memset(spiTransfers, 0, message->Length() * sizeof(spi_ioc_transfer));
if (ToSpiTransfers(message, spiTransfers) == -1) {
free(spiTransfers);
return;
}
Nan::AsyncQueueWorker(new TransferWorker(
callback,
fd,
message,
spiTransfers,
message->Length()
));
info.GetReturnValue().Set(info.This());
}
void TransferSync(Nan::NAN_METHOD_ARGS_TYPE info) {
SpiDevice *device = Nan::ObjectWrap::Unwrap<SpiDevice>(info.This());
int fd = device->Fd();
if (fd == -1) {
return Nan::ThrowError(
Nan::ErrnoException(
EPERM, "transferSync", "device closed, operation not permitted"
)
);
}
if (info.Length() < 1 || !info[0]->IsArray()) {
return Nan::ThrowError(
Nan::ErrnoException(
EINVAL,
"transfer",
"incorrect arguments passed to transferSync(message)"
)
);
}
v8::Local<v8::Array> message = info[0].As<v8::Array>();
spi_ioc_transfer *spiTransfers = (spi_ioc_transfer *)
malloc(message->Length() * sizeof(spi_ioc_transfer));
memset(spiTransfers, 0, message->Length() * sizeof(spi_ioc_transfer));
if (ToSpiTransfers(message, spiTransfers) == 0) {
if (Transfer(fd, spiTransfers, message->Length()) == -1) {
Nan::ThrowError(Nan::ErrnoException(errno, "transferSync", ""));
}
}
free(spiTransfers);
info.GetReturnValue().Set(info.This());
}
<|endoftext|> |
<commit_before>#include "tws_xml.h"
#include "debug.h"
#include "twsUtil.h"
#include "ibtws/Contract.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
#define ADD_ATTR_LONG( _struct_, _attr_ ) \
snprintf(tmp, sizeof(tmp), "%ld",_struct_._attr_ ); \
xmlNewProp ( ne, (xmlChar*) #_attr_, (xmlChar*) tmp )
#define ADD_ATTR_DOUBLE( _struct_, _attr_ ) \
snprintf(tmp, sizeof(tmp), "%.10g", _struct_._attr_ ); \
xmlNewProp ( ne, (xmlChar*) #_attr_, (xmlChar*) tmp )
#define ADD_ATTR_BOOL( _struct_, _attr_ ) \
xmlNewProp ( ne, (xmlChar*) #_attr_, \
(xmlChar*) (_struct_._attr_ ? "1" : "0") )
#define ADD_ATTR_STRING( _struct_, _attr_ ) \
xmlNewProp ( ne, (xmlChar*) #_attr_, (xmlChar*) _struct_._attr_.c_str() );
void conv_ib2xml( xmlNodePtr parent, const IB::Contract& c )
{
char tmp[128];
xmlNodePtr ne = xmlNewChild( parent, NULL, (xmlChar*)"IBContract", NULL);
ADD_ATTR_LONG( c, conId );
ADD_ATTR_STRING( c, symbol );
ADD_ATTR_STRING( c, secType );
ADD_ATTR_STRING( c, expiry );
ADD_ATTR_DOUBLE( c, strike );
ADD_ATTR_STRING( c, right );
ADD_ATTR_STRING( c, multiplier );
ADD_ATTR_STRING( c, exchange );
ADD_ATTR_STRING( c, primaryExchange );
ADD_ATTR_STRING( c, currency );
ADD_ATTR_STRING( c, localSymbol );
ADD_ATTR_BOOL( c, includeExpired );
ADD_ATTR_STRING( c, secIdType );
ADD_ATTR_STRING( c, secId );
ADD_ATTR_STRING( c, comboLegsDescrip );
xmlAddChild(parent, ne);
}
void conv_ib2xml( xmlNodePtr parent, const IB::ContractDetails& cd )
{
char tmp[128];
xmlNodePtr ne = xmlNewChild( parent, NULL,
(xmlChar*)"IBContractDetails", NULL);
xmlAddChild(parent, ne);
}
#define GET_ATTR_LONG( _struct_, _attr_ ) \
tmp = (char*) xmlGetProp( node, (xmlChar*) #_attr_ ); \
_struct_->_attr_ = tmp ? atol( tmp ) : dfltContract.conId; \
free(tmp)
#define GET_ATTR_DOUBLE( _struct_, _attr_ ) \
tmp = (char*) xmlGetProp( node, (xmlChar*) #_attr_ ); \
_struct_->_attr_ = tmp ? atof( tmp ) : dfltContract.conId; \
free(tmp)
#define GET_ATTR_BOOL( _struct_, _attr_ ) \
tmp = (char*) xmlGetProp( node, (xmlChar*) #_attr_ ); \
_struct_->_attr_ = tmp ? atof( tmp ) : dfltContract.conId; \
free(tmp)
#define GET_ATTR_STRING( _struct_, _attr_ ) \
tmp = (char*) xmlGetProp( node, (xmlChar*) #_attr_ ); \
_struct_->_attr_ = tmp ? std::string(tmp) : dfltContract._attr_; \
free(tmp)
void conv_xml2ib( IB::Contract* c, const xmlNodePtr node )
{
char* tmp;
static const IB::Contract dfltContract;
GET_ATTR_LONG( c, conId );
GET_ATTR_STRING( c, symbol );
GET_ATTR_STRING( c, secType );
GET_ATTR_STRING( c, expiry );
GET_ATTR_DOUBLE( c, strike );
GET_ATTR_STRING( c, right );
GET_ATTR_STRING( c, multiplier );
GET_ATTR_STRING( c, exchange );
GET_ATTR_STRING( c, primaryExchange );
GET_ATTR_STRING( c, currency );
GET_ATTR_STRING( c, localSymbol );
GET_ATTR_BOOL( c, includeExpired );
GET_ATTR_STRING( c, secIdType );
GET_ATTR_STRING( c, secId );
GET_ATTR_STRING( c, comboLegsDescrip );
// TODO comboLegs
// TODO underComp
}
void conv_xml2ib( IB::ContractDetails* cd, const xmlNodePtr node )
{
char* tmp;
static const IB::ContractDetails dfltCntrctDtls;
}
IbXml::IbXml()
{
doc = xmlNewDoc( (const xmlChar*) "1.0");
root = xmlNewDocNode( doc, NULL, (xmlChar*)"root", NULL );
xmlDocSetRootElement( doc, root );
}
IbXml::~IbXml()
{
xmlFreeDoc(doc);
}
void IbXml::dump() const
{
xmlDocFormatDump(stdout, doc, 1);
}
void IbXml::add( const IB::Contract& c )
{
conv_ib2xml( root, c );
}
void IbXml::add( const IB::ContractDetails& cd )
{
conv_ib2xml( root, cd );
}
xmlDocPtr IbXml::getDoc() const
{
return doc;
}
xmlNodePtr IbXml::getRoot() const
{
return root;
}
#ifdef TWS_XML_MAIN
int main(int argc, char *argv[])
{
IbXml ibXml;
IB::Contract ic_orig, ic_conv;
ic_orig.strike = 25.0;
ibXml.add( ic_orig );
ibXml.dump();
xmlNodePtr xml_contract2 = xmlFirstElementChild( ibXml.getRoot() );
conv_xml2ib( &ic_conv, xml_contract2 );
ic_conv.strike = 27.0;
#define DBG_EQUAL_FIELD( _attr_ ) \
qDebug() << #_attr_ << ( ic_orig._attr_ == ic_conv._attr_ );
DBG_EQUAL_FIELD( conId );
DBG_EQUAL_FIELD( symbol );
DBG_EQUAL_FIELD( secType );
DBG_EQUAL_FIELD( expiry );
DBG_EQUAL_FIELD( strike );
DBG_EQUAL_FIELD( right );
DBG_EQUAL_FIELD( multiplier );
DBG_EQUAL_FIELD( exchange );
DBG_EQUAL_FIELD( primaryExchange );
DBG_EQUAL_FIELD( currency );
DBG_EQUAL_FIELD( localSymbol );
DBG_EQUAL_FIELD( includeExpired );
DBG_EQUAL_FIELD( secIdType );
DBG_EQUAL_FIELD( secId );
DBG_EQUAL_FIELD( comboLegsDescrip );
return 0;
}
#endif
<commit_msg>tws-xml, implement conv_ib2xml() for ContractDetails<commit_after>#include "tws_xml.h"
#include "debug.h"
#include "twsUtil.h"
#include "ibtws/Contract.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
#define ADD_ATTR_INT( _struct_, _attr_ ) \
snprintf(tmp, sizeof(tmp), "%d",_struct_._attr_ ); \
xmlNewProp ( ne, (xmlChar*) #_attr_, (xmlChar*) tmp )
#define ADD_ATTR_LONG( _struct_, _attr_ ) \
snprintf(tmp, sizeof(tmp), "%ld",_struct_._attr_ ); \
xmlNewProp ( ne, (xmlChar*) #_attr_, (xmlChar*) tmp )
#define ADD_ATTR_DOUBLE( _struct_, _attr_ ) \
snprintf(tmp, sizeof(tmp), "%.10g", _struct_._attr_ ); \
xmlNewProp ( ne, (xmlChar*) #_attr_, (xmlChar*) tmp )
#define ADD_ATTR_BOOL( _struct_, _attr_ ) \
xmlNewProp ( ne, (xmlChar*) #_attr_, \
(xmlChar*) (_struct_._attr_ ? "1" : "0") )
#define ADD_ATTR_STRING( _struct_, _attr_ ) \
xmlNewProp ( ne, (xmlChar*) #_attr_, (xmlChar*) _struct_._attr_.c_str() );
void conv_ib2xml( xmlNodePtr parent, const IB::Contract& c )
{
char tmp[128];
xmlNodePtr ne = xmlNewChild( parent, NULL, (xmlChar*)"IBContract", NULL);
ADD_ATTR_LONG( c, conId );
ADD_ATTR_STRING( c, symbol );
ADD_ATTR_STRING( c, secType );
ADD_ATTR_STRING( c, expiry );
ADD_ATTR_DOUBLE( c, strike );
ADD_ATTR_STRING( c, right );
ADD_ATTR_STRING( c, multiplier );
ADD_ATTR_STRING( c, exchange );
ADD_ATTR_STRING( c, primaryExchange );
ADD_ATTR_STRING( c, currency );
ADD_ATTR_STRING( c, localSymbol );
ADD_ATTR_BOOL( c, includeExpired );
ADD_ATTR_STRING( c, secIdType );
ADD_ATTR_STRING( c, secId );
ADD_ATTR_STRING( c, comboLegsDescrip );
xmlAddChild(parent, ne);
}
void conv_ib2xml( xmlNodePtr parent, const IB::ContractDetails& cd )
{
char tmp[128];
xmlNodePtr ne = xmlNewChild( parent, NULL,
(xmlChar*)"IBContractDetails", NULL);
conv_ib2xml( ne, cd.summary );
ADD_ATTR_STRING( cd, marketName );
ADD_ATTR_STRING( cd, tradingClass );
ADD_ATTR_DOUBLE( cd, minTick );
ADD_ATTR_STRING( cd, orderTypes );
ADD_ATTR_STRING( cd, validExchanges );
ADD_ATTR_LONG( cd, priceMagnifier );
ADD_ATTR_INT( cd, underConId );
ADD_ATTR_STRING( cd, longName );
ADD_ATTR_STRING( cd, contractMonth );
ADD_ATTR_STRING( cd, industry );
ADD_ATTR_STRING( cd, category );
ADD_ATTR_STRING( cd, subcategory );
ADD_ATTR_STRING( cd, timeZoneId );
ADD_ATTR_STRING( cd, tradingHours );
ADD_ATTR_STRING( cd, liquidHours );
// BOND values
ADD_ATTR_STRING( cd, cusip );
ADD_ATTR_STRING( cd, ratings );
ADD_ATTR_STRING( cd, descAppend );
ADD_ATTR_STRING( cd, bondType );
ADD_ATTR_STRING( cd, couponType );
ADD_ATTR_BOOL( cd, callable );
ADD_ATTR_BOOL( cd, putable );
ADD_ATTR_DOUBLE( cd, coupon );
ADD_ATTR_BOOL( cd, convertible );
ADD_ATTR_STRING( cd, maturity );
ADD_ATTR_STRING( cd, issueDate );
ADD_ATTR_STRING( cd, nextOptionDate );
ADD_ATTR_STRING( cd, nextOptionType );
ADD_ATTR_BOOL( cd, nextOptionPartial );
ADD_ATTR_STRING( cd, notes );
xmlAddChild(parent, ne);
}
#define GET_ATTR_LONG( _struct_, _attr_ ) \
tmp = (char*) xmlGetProp( node, (xmlChar*) #_attr_ ); \
_struct_->_attr_ = tmp ? atol( tmp ) : dfltContract.conId; \
free(tmp)
#define GET_ATTR_DOUBLE( _struct_, _attr_ ) \
tmp = (char*) xmlGetProp( node, (xmlChar*) #_attr_ ); \
_struct_->_attr_ = tmp ? atof( tmp ) : dfltContract.conId; \
free(tmp)
#define GET_ATTR_BOOL( _struct_, _attr_ ) \
tmp = (char*) xmlGetProp( node, (xmlChar*) #_attr_ ); \
_struct_->_attr_ = tmp ? atof( tmp ) : dfltContract.conId; \
free(tmp)
#define GET_ATTR_STRING( _struct_, _attr_ ) \
tmp = (char*) xmlGetProp( node, (xmlChar*) #_attr_ ); \
_struct_->_attr_ = tmp ? std::string(tmp) : dfltContract._attr_; \
free(tmp)
void conv_xml2ib( IB::Contract* c, const xmlNodePtr node )
{
char* tmp;
static const IB::Contract dfltContract;
GET_ATTR_LONG( c, conId );
GET_ATTR_STRING( c, symbol );
GET_ATTR_STRING( c, secType );
GET_ATTR_STRING( c, expiry );
GET_ATTR_DOUBLE( c, strike );
GET_ATTR_STRING( c, right );
GET_ATTR_STRING( c, multiplier );
GET_ATTR_STRING( c, exchange );
GET_ATTR_STRING( c, primaryExchange );
GET_ATTR_STRING( c, currency );
GET_ATTR_STRING( c, localSymbol );
GET_ATTR_BOOL( c, includeExpired );
GET_ATTR_STRING( c, secIdType );
GET_ATTR_STRING( c, secId );
GET_ATTR_STRING( c, comboLegsDescrip );
// TODO comboLegs
// TODO underComp
}
void conv_xml2ib( IB::ContractDetails* cd, const xmlNodePtr node )
{
char* tmp;
static const IB::ContractDetails dfltCntrctDtls;
}
IbXml::IbXml()
{
doc = xmlNewDoc( (const xmlChar*) "1.0");
root = xmlNewDocNode( doc, NULL, (xmlChar*)"root", NULL );
xmlDocSetRootElement( doc, root );
}
IbXml::~IbXml()
{
xmlFreeDoc(doc);
}
void IbXml::dump() const
{
xmlDocFormatDump(stdout, doc, 1);
}
void IbXml::add( const IB::Contract& c )
{
conv_ib2xml( root, c );
}
void IbXml::add( const IB::ContractDetails& cd )
{
conv_ib2xml( root, cd );
}
xmlDocPtr IbXml::getDoc() const
{
return doc;
}
xmlNodePtr IbXml::getRoot() const
{
return root;
}
#ifdef TWS_XML_MAIN
int main(int argc, char *argv[])
{
IbXml ibXml;
IB::Contract ic_orig, ic_conv;
ic_orig.strike = 25.0;
ibXml.add( ic_orig );
ibXml.dump();
xmlNodePtr xml_contract2 = xmlFirstElementChild( ibXml.getRoot() );
conv_xml2ib( &ic_conv, xml_contract2 );
ic_conv.strike = 27.0;
#define DBG_EQUAL_FIELD( _attr_ ) \
qDebug() << #_attr_ << ( ic_orig._attr_ == ic_conv._attr_ );
DBG_EQUAL_FIELD( conId );
DBG_EQUAL_FIELD( symbol );
DBG_EQUAL_FIELD( secType );
DBG_EQUAL_FIELD( expiry );
DBG_EQUAL_FIELD( strike );
DBG_EQUAL_FIELD( right );
DBG_EQUAL_FIELD( multiplier );
DBG_EQUAL_FIELD( exchange );
DBG_EQUAL_FIELD( primaryExchange );
DBG_EQUAL_FIELD( currency );
DBG_EQUAL_FIELD( localSymbol );
DBG_EQUAL_FIELD( includeExpired );
DBG_EQUAL_FIELD( secIdType );
DBG_EQUAL_FIELD( secId );
DBG_EQUAL_FIELD( comboLegsDescrip );
return 0;
}
#endif
<|endoftext|> |
<commit_before>// For segment fault tracing
#include <iostream>
#include <execinfo.h>
#include <unistd.h>
#include <signal.h>
#include <QApplication>
#include "med/MedException.hpp"
#include "ui/Ui.hpp"
using namespace std;
// https://stackoverflow.com/questions/77005/how-to-automatically-generate-a-stacktrace-when-my-gcc-c-program-crashes
void handler(int sig) {
void* array[10];
size_t size;
size = backtrace(array, 10);
fprintf(stderr, "Error: signal %d:\n", sig);
backtrace_symbols_fd(array, size, STDERR_FILENO);
exit(1);
}
void print_exception(const std::exception& e, int level = 0) {
std::cerr << std::string(level, ' ') << "exception: " << e.what() << endl;
try {
std::rethrow_if_nested(e);
} catch (const std::exception& e) {
print_exception(e, level + 1);
} catch (...) {}
}
int main(int argc, char** argv) {
signal(SIGSEGV, handler);
try {
QApplication app(argc, argv);
new MedUi(&app);
return app.exec();
} catch(MedException &ex) {
cerr << ex.getMessage() << endl;
} catch(const std::exception& e) {
print_exception(e);
return 1;
}
}
<commit_msg>Fix shadow variable<commit_after>// For segment fault tracing
#include <iostream>
#include <execinfo.h>
#include <unistd.h>
#include <signal.h>
#include <QApplication>
#include "med/MedException.hpp"
#include "ui/Ui.hpp"
using namespace std;
// https://stackoverflow.com/questions/77005/how-to-automatically-generate-a-stacktrace-when-my-gcc-c-program-crashes
void handler(int sig) {
void* array[10];
size_t size;
size = backtrace(array, 10);
fprintf(stderr, "Error: signal %d:\n", sig);
backtrace_symbols_fd(array, size, STDERR_FILENO);
exit(1);
}
void print_exception(const std::exception& e, int level = 0) {
std::cerr << std::string(level, ' ') << "exception: " << e.what() << endl;
try {
std::rethrow_if_nested(e);
} catch (const std::exception& ex) {
print_exception(ex, level + 1);
} catch (...) {}
}
int main(int argc, char** argv) {
signal(SIGSEGV, handler);
try {
QApplication app(argc, argv);
new MedUi(&app);
return app.exec();
} catch(MedException &ex) {
cerr << ex.getMessage() << endl;
} catch(const std::exception& e) {
print_exception(e);
return 1;
}
}
<|endoftext|> |
<commit_before>{
GeFiCa::PointContactRZ *detector2 = new GeFiCa::PointContactRZ(690,506);
detector2->Radius=3.45;
detector2->ZUpperBound=5.05;
detector2->PointR=0.14;
detector2->PointDepth=0.21;
//TF2 *im=new TF2("f","-0.19175e10-0.025e10*y");
//TF2 *im=new TF2("f","-0.318e10+0.025e10*y");
//TF1 *im1=new TF1("f","-0.318e10+0.025e10*x",0,6.9);
detector2->MaxIterations=1e5;
detector2->Precision=1e-8;
detector2->Csor=1.9965;
detector2->V0=2500*GeFiCa::volt;
detector2->V1=0*GeFiCa::volt;
//TF1 *im=new TF1("","pol1",-0.318e10,0.025e10)
detector2->Impurity="-0.318e10+0.025e10*y";//-0.01e10/GeFiCa::cm3);
//detector2->SetImpurity(0e10/GeFiCa::cm3);
detector2->CalculateField(GeFiCa::kSOR2);
detector2->SaveField("point2dSOR2.root");
//detector2->LoadField("point21dSOR23.root");
/*
// calculate fields
GeFiCa::Planar1D *detector = new GeFiCa::Planar1D(505);
detector->UpperBound=5.05;
detector->V1=2500*GeFiCa::volt;
detector->V0=0*GeFiCa::volt;
detector->SetImpurity(-0.01e10/GeFiCa::cm3);
detector->CalculateField(GeFiCa::kAnalytic);
detector->SaveField("planar1dTrue.root");
TCanvas * cvs=new TCanvas();
gStyle->SetOptTitle(kTRUE);
gStyle->SetPadTopMargin(0.02);
gStyle->SetPadRightMargin(0.01);
gStyle->SetPadLeftMargin(0.0999999999);
gStyle->SetLabelFont(22,"XY");
gStyle->SetLabelSize(0.05,"XY");
gStyle->SetTitleSize(0.05,"XY");
gStyle->SetTitleFont(22,"XY");
gStyle->SetLegendFont(22);
gStyle->SetCanvasColor(kBlack);
//cvs->SetFillColor(kBlack);
TChain *ta = new TChain("t");
ta->Add("planar1dTrue.root");
ta->Draw("e1:c1");
TGraph *ga = new TGraph(ta->GetSelectedRows(), ta->GetV2(), ta->GetV1());
// generate graphics
TChain *tn = new TChain("t");
//tn->Add("point2dSOR2.root");
//tn->Draw("c2*10:p","c1<0.00&&c1>-0.05");
// TGraph *gn = new TGraph(tn->GetSelectedRows(), tn->GetV2(), tn->GetV1());
TChain *ta = new TChain("t");
// ta->Add("point2dSOR2.root");
//ta->Draw("c2:c1:p","","colz");
//TGraph *gn = new TGraph(ta->GetSelectedRows(), ta->GetV2(), ta->GetV1());
TTree *t = new TTree("t","t");
t->ReadFile("/home/byron/mjd_siggen/fields/p1/ev.new", "r:z:v");
//t->AddFriend("t2=t","point2dSOR2.root");
//t->Draw("z:(t2.p-v)","z!=1&r!=1&z<1&r>34.&r<34.5","");
//TCanvas *can = new TCanvas;
//t->Draw("r:(t2.p-v)","z>=0&z<0.2","");
t->Draw("z:r:v","","colz");
// TGraph *gn = new TGraph(t->GetSelectedRows(), t->GetV2(), t->GetV1());
// make final plot
//gn->SetMarkerColor(kBlue);
//gn->SetMarkerStyle(8);
//gn->SetMarkerSize(0.3);
//ga->SetLineColor(kRed);
//gn->GetXaxis()->SetTitle("Thickness [cm]");
//gn->GetYaxis()->SetTitle("Potential [V]");
//gn->SetTitle("");
//gn->Draw("ap");
//ga->Draw("l");
TLegend *leg = new TLegend(0.2,0.6,0.5,0.8);
leg->SetBorderSize(0);
//leg->AddEntry(gn,"GeFiCa","p");
//leg->AddEntry(ga,"mjd","l");
leg->SetTextSize(0.05);
leg->Draw();
// cvs->SaveAs("pointContact2d.png");
*/
}
<commit_msg>moved ppc upper bound<commit_after>{
GeFiCa::PointContactRZ *detector2 = new GeFiCa::PointContactRZ(690,506);
detector2->Radius=3.45;
detector2->ZUpperBound=5.05;
detector2->PointR=0.14;
detector2->PointDepth=0.215;
//TF2 *im=new TF2("f","-0.19175e10-0.025e10*y");
//TF2 *im=new TF2("f","-0.318e10+0.025e10*y");
//TF1 *im1=new TF1("f","-0.318e10+0.025e10*x",0,6.9);
detector2->MaxIterations=1e5;
detector2->Precision=1e-8;
detector2->Csor=1.9965;
detector2->V0=2500*GeFiCa::volt;
detector2->V1=0*GeFiCa::volt;
//TF1 *im=new TF1("","pol1",-0.318e10,0.025e10)
detector2->Impurity="-0.318e10+0.025e10*y";//-0.01e10/GeFiCa::cm3);
//detector2->SetImpurity(0e10/GeFiCa::cm3);
detector2->CalculateField(GeFiCa::kSOR2);
detector2->SaveField("point2dSOR2.root");
//detector2->LoadField("point21dSOR23.root");
/*
// calculate fields
GeFiCa::Planar1D *detector = new GeFiCa::Planar1D(505);
detector->UpperBound=5.05;
detector->V1=2500*GeFiCa::volt;
detector->V0=0*GeFiCa::volt;
detector->SetImpurity(-0.01e10/GeFiCa::cm3);
detector->CalculateField(GeFiCa::kAnalytic);
detector->SaveField("planar1dTrue.root");
TCanvas * cvs=new TCanvas();
gStyle->SetOptTitle(kTRUE);
gStyle->SetPadTopMargin(0.02);
gStyle->SetPadRightMargin(0.01);
gStyle->SetPadLeftMargin(0.0999999999);
gStyle->SetLabelFont(22,"XY");
gStyle->SetLabelSize(0.05,"XY");
gStyle->SetTitleSize(0.05,"XY");
gStyle->SetTitleFont(22,"XY");
gStyle->SetLegendFont(22);
gStyle->SetCanvasColor(kBlack);
//cvs->SetFillColor(kBlack);
TChain *ta = new TChain("t");
ta->Add("planar1dTrue.root");
ta->Draw("e1:c1");
TGraph *ga = new TGraph(ta->GetSelectedRows(), ta->GetV2(), ta->GetV1());
// generate graphics
TChain *tn = new TChain("t");
//tn->Add("point2dSOR2.root");
//tn->Draw("c2*10:p","c1<0.00&&c1>-0.05");
// TGraph *gn = new TGraph(tn->GetSelectedRows(), tn->GetV2(), tn->GetV1());
TChain *ta = new TChain("t");
// ta->Add("point2dSOR2.root");
//ta->Draw("c2:c1:p","","colz");
//TGraph *gn = new TGraph(ta->GetSelectedRows(), ta->GetV2(), ta->GetV1());
TTree *t = new TTree("t","t");
t->ReadFile("/home/byron/mjd_siggen/fields/p1/ev.new", "r:z:v");
//t->AddFriend("t2=t","point2dSOR2.root");
//t->Draw("z:(t2.p-v)","z!=1&r!=1&z<1&r>34.&r<34.5","");
//TCanvas *can = new TCanvas;
//t->Draw("r:(t2.p-v)","z>=0&z<0.2","");
t->Draw("z:r:v","","colz");
// TGraph *gn = new TGraph(t->GetSelectedRows(), t->GetV2(), t->GetV1());
// make final plot
//gn->SetMarkerColor(kBlue);
//gn->SetMarkerStyle(8);
//gn->SetMarkerSize(0.3);
//ga->SetLineColor(kRed);
//gn->GetXaxis()->SetTitle("Thickness [cm]");
//gn->GetYaxis()->SetTitle("Potential [V]");
//gn->SetTitle("");
//gn->Draw("ap");
//ga->Draw("l");
TLegend *leg = new TLegend(0.2,0.6,0.5,0.8);
leg->SetBorderSize(0);
//leg->AddEntry(gn,"GeFiCa","p");
//leg->AddEntry(ga,"mjd","l");
leg->SetTextSize(0.05);
leg->Draw();
// cvs->SaveAs("pointContact2d.png");
*/
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "version.h"
#include <string>
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");
// Client version number
#define CLIENT_VERSION_SUFFIX "-Standard"
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID "it"
# define GIT_COMMIT_DATE "Fri, 12 September 2014 16:29:30 -0400"
#endif
#define BUILD_DESC_WITH_SUFFIX(maj,min,rev,build,suffix) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix)
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-ftc" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
# ifdef BUILD_SUFFIX
# define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX)
# elif defined(GIT_COMMIT_ID)
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>changed client string from Satoshi to Feathercoin<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "version.h"
#include <string>
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Feathercoin");
// Client version number
#define CLIENT_VERSION_SUFFIX "-Standard"
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID "it"
# define GIT_COMMIT_DATE "Fri, 12 September 2014 16:29:30 -0400"
#endif
#define BUILD_DESC_WITH_SUFFIX(maj,min,rev,build,suffix) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix)
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-ftc" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
# ifdef BUILD_SUFFIX
# define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX)
# elif defined(GIT_COMMIT_ID)
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|> |
<commit_before>#include <buildsys.h>
std::list<Package *>::iterator World::packagesStart()
{
return this->packages.begin();
}
std::list<Package *>::iterator World::packagesEnd()
{
return this->packages.end();
}
void World::setName(std::string n)
{
this->name = n;
#ifdef UNDERSCORE_MONITOR
sendTarget(this->name.c_str());
#endif
}
bool World::setFeature(std::string key, std::string value, bool override)
{
// look for this key
if(features->find(key) != features->end())
{
if(override)
{
// only over-write the value if we are explicitly told to
(*features)[key] = value;
}
return true;
}
features->insert(std::pair<std::string, std::string>(key, value));
return true;
}
bool World::setFeature(char *kv)
{
char *eq = strchr(kv, '=');
if(eq == NULL)
{
error("Features must be described as feature=value\n");
return false;
}
char *temp = (char *)calloc(1, (eq - kv) + 1);
if(temp == NULL) return false;
strncpy(temp, kv, (eq-kv));
std::string key(temp);
free(temp);
eq++;
temp = strdup(eq);
if(temp == NULL) return false;
std::string value(temp);
free(temp);
this->setFeature(key, value, true);
return true;
}
std::string World::getFeature(std::string key)
{
if(features->find(key) != features->end())
{
return (*features)[key];
}
throw NoKeyException();
}
#ifdef UNDERSCORE
static us_condition *t_cond = NULL;
static void *build_thread(us_thread *t)
{
Package *p = (Package *)t->priv;
log(p->getName().c_str(), "Build Thread");
bool skip = false;
if(p->isBuilding())
{
skip = true;
}
if(!skip)
p->setBuilding();
us_cond_lock(t_cond);
us_cond_signal(t_cond, true);
us_cond_unlock(t_cond);
if(!skip)
{
if(!p->build()) WORLD->setFailed();
}
WORLD->condTrigger();
return NULL;
}
#endif
bool World::basePackage(char *filename)
{
this->p = findPackage(filename, filename);
try {
// Load all the lua files
this->p->process();
// Extract all the source code
this->p->extract();
} catch (Exception &E)
{
error(E.error_msg().c_str());
return false;
}
this->graph = new Internal_Graph();
this->topo_graph = new Internal_Graph();
this->topo_graph->topological();
#ifdef UNDERSCORE
t_cond = us_cond_create();
while(!this->isFailed() && !this->p->isBuilt())
{
us_cond_lock(this->cond);
Package *toBuild = this->topo_graph->topoNext();
if(toBuild != NULL)
{
us_cond_unlock(this->cond);
us_cond_lock(t_cond);
us_thread_create(build_thread, 0, toBuild);
us_cond_wait(t_cond);
us_cond_unlock(t_cond);
} else {
us_cond_wait(this->cond);
us_cond_unlock(this->cond);
}
}
#else
this->p->build();
#endif
return !this->failed;
}
Package *World::findPackage(std::string name, std::string file)
{
std::list<Package *>::iterator iter = this->packagesStart();
std::list<Package *>::iterator iterEnd = this->packagesEnd();
for(; iter != iterEnd; iter++)
{
if((*iter)->getName().compare(name) == 0)
return (*iter);
}
Package *p = new Package(name, file);
this->packages.push_back(p);
return p;
}
bool World::isForced(std::string name)
{
string_list::iterator fIt = this->forcedDeps->begin();
string_list::iterator fEnd = this->forcedDeps->end();
for(; fIt != fEnd; fIt++)
{
if((*fIt).compare(name)==0) return true;
}
return false;
}
bool World::packageFinished(Package *p)
{
#ifdef UNDERSCORE
us_cond_lock(this->cond);
#endif
this->topo_graph->deleteNode(p);
this->topo_graph->topological();
#ifdef UNDERSCORE
us_cond_signal(this->cond, true);
us_cond_unlock(this->cond);
#endif
return true;
}
<commit_msg>MAINT: Make buildsys correctly error out to make when not-parallized<commit_after>#include <buildsys.h>
std::list<Package *>::iterator World::packagesStart()
{
return this->packages.begin();
}
std::list<Package *>::iterator World::packagesEnd()
{
return this->packages.end();
}
void World::setName(std::string n)
{
this->name = n;
#ifdef UNDERSCORE_MONITOR
sendTarget(this->name.c_str());
#endif
}
bool World::setFeature(std::string key, std::string value, bool override)
{
// look for this key
if(features->find(key) != features->end())
{
if(override)
{
// only over-write the value if we are explicitly told to
(*features)[key] = value;
}
return true;
}
features->insert(std::pair<std::string, std::string>(key, value));
return true;
}
bool World::setFeature(char *kv)
{
char *eq = strchr(kv, '=');
if(eq == NULL)
{
error("Features must be described as feature=value\n");
return false;
}
char *temp = (char *)calloc(1, (eq - kv) + 1);
if(temp == NULL) return false;
strncpy(temp, kv, (eq-kv));
std::string key(temp);
free(temp);
eq++;
temp = strdup(eq);
if(temp == NULL) return false;
std::string value(temp);
free(temp);
this->setFeature(key, value, true);
return true;
}
std::string World::getFeature(std::string key)
{
if(features->find(key) != features->end())
{
return (*features)[key];
}
throw NoKeyException();
}
#ifdef UNDERSCORE
static us_condition *t_cond = NULL;
static void *build_thread(us_thread *t)
{
Package *p = (Package *)t->priv;
log(p->getName().c_str(), "Build Thread");
bool skip = false;
if(p->isBuilding())
{
skip = true;
}
if(!skip)
p->setBuilding();
us_cond_lock(t_cond);
us_cond_signal(t_cond, true);
us_cond_unlock(t_cond);
if(!skip)
{
if(!p->build()) WORLD->setFailed();
}
WORLD->condTrigger();
return NULL;
}
#endif
bool World::basePackage(char *filename)
{
this->p = findPackage(filename, filename);
try {
// Load all the lua files
this->p->process();
// Extract all the source code
this->p->extract();
} catch (Exception &E)
{
error(E.error_msg().c_str());
return false;
}
this->graph = new Internal_Graph();
this->topo_graph = new Internal_Graph();
this->topo_graph->topological();
#ifdef UNDERSCORE
t_cond = us_cond_create();
while(!this->isFailed() && !this->p->isBuilt())
{
us_cond_lock(this->cond);
Package *toBuild = this->topo_graph->topoNext();
if(toBuild != NULL)
{
us_cond_unlock(this->cond);
us_cond_lock(t_cond);
us_thread_create(build_thread, 0, toBuild);
us_cond_wait(t_cond);
us_cond_unlock(t_cond);
} else {
us_cond_wait(this->cond);
us_cond_unlock(this->cond);
}
}
#else
if(!this->p->build())
return false;
#endif
return !this->failed;
}
Package *World::findPackage(std::string name, std::string file)
{
std::list<Package *>::iterator iter = this->packagesStart();
std::list<Package *>::iterator iterEnd = this->packagesEnd();
for(; iter != iterEnd; iter++)
{
if((*iter)->getName().compare(name) == 0)
return (*iter);
}
Package *p = new Package(name, file);
this->packages.push_back(p);
return p;
}
bool World::isForced(std::string name)
{
string_list::iterator fIt = this->forcedDeps->begin();
string_list::iterator fEnd = this->forcedDeps->end();
for(; fIt != fEnd; fIt++)
{
if((*fIt).compare(name)==0) return true;
}
return false;
}
bool World::packageFinished(Package *p)
{
#ifdef UNDERSCORE
us_cond_lock(this->cond);
#endif
this->topo_graph->deleteNode(p);
this->topo_graph->topological();
#ifdef UNDERSCORE
us_cond_signal(this->cond, true);
us_cond_unlock(this->cond);
#endif
return true;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015, Joseph Mirabel
// Authors: Joseph Mirabel (joseph.mirabel@laas.fr)
//
// This file is part of hpp-core.
// hpp-core 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
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core. If not, see <http://www.gnu.org/licenses/>.
#include <hpp/core/interpolated-path.hh>
#include <hpp/util/debug.hh>
#include <hpp/pinocchio/device.hh>
#include <hpp/pinocchio/liegroup.hh>
#include <hpp/pinocchio/configuration.hh>
#include <hpp/core/config-projector.hh>
#include <hpp/core/projection-error.hh>
namespace hpp {
namespace core {
InterpolatedPath::InterpolatedPath (const DevicePtr_t& device,
ConfigurationIn_t init,
ConfigurationIn_t end,
value_type length) :
parent_t (interval_t (0, length), device->configSize (),
device->numberDof ()),
device_ (device)
{
assert (init.size() == device_->configSize ());
insert (0, init);
insert (length, end);
assert (device);
assert (length >= 0);
assert (!constraints ());
}
InterpolatedPath::InterpolatedPath (const DevicePtr_t& device,
ConfigurationIn_t init,
ConfigurationIn_t end,
value_type length,
ConstraintSetPtr_t constraints) :
parent_t (interval_t (0, length), device->configSize (),
device->numberDof (), constraints),
device_ (device)
{
assert (init.size() == device_->configSize ());
insert (0, init);
insert (length, end);
assert (device);
assert (length >= 0);
}
InterpolatedPath::InterpolatedPath (const InterpolatedPath& path) :
parent_t (path), device_ (path.device_), configs_ (path.configs_)
{
assert (initial().size() == device_->configSize ());
}
InterpolatedPath::InterpolatedPath (const InterpolatedPath& path,
const ConstraintSetPtr_t& constraints) :
parent_t (path, constraints), device_ (path.device_),
configs_ (path.configs_)
{
}
InterpolatedPathPtr_t InterpolatedPath::create (const PathPtr_t& path,
const DevicePtr_t& device, const std::size_t& nbSamples)
{
// TODO: If it is a path vector, should we get the waypoints and build
// a interpolated path from those waypoints ?
InterpolatedPath* ptr = new InterpolatedPath (device,
path->initial (), path->end(), path->length(),
path->constraints ());
InterpolatedPathPtr_t shPtr (ptr);
ptr->init (shPtr);
const value_type dl = path->length () / (value_type) (nbSamples + 1);
Configuration_t q (device->configSize ());
for (std::size_t iS = 0; iS < nbSamples; ++iS) {
const value_type u = dl * (value_type) (iS + 1);
if (!(*path) (q, u))
throw projection_error ("could not build InterpolatedPath");
ptr->insert (u, q);
}
return shPtr;
}
void InterpolatedPath::init (InterpolatedPathPtr_t self)
{
parent_t::init (self);
weak_ = self;
checkPath ();
}
void InterpolatedPath::initCopy (InterpolatedPathPtr_t self)
{
parent_t::init (self);
weak_ = self;
checkPath ();
}
bool InterpolatedPath::impl_compute (ConfigurationOut_t result,
value_type param) const
{
assert (param >= paramRange().first);
if (param == paramRange ().first || paramLength() == 0) {
result.noalias () = initial();
return true;
}
if (param >= paramRange ().second) {
result.noalias () = end();
return true;
}
InterpolationPoints_t::const_iterator itA = configs_.lower_bound (param);
InterpolationPoints_t::const_iterator itB = itA; --itB;
const value_type T = itA->first - itB->first;
const value_type u = (param - itB->first) / T;
pinocchio::interpolate<hpp::pinocchio::LieGroupTpl> (device_, itB->second, itA->second, u, result);
return true;
}
void InterpolatedPath::impl_derivative
(vectorOut_t result, const value_type& s, size_type order) const
{
value_type param (s);
assert (param >= paramRange().first);
if (paramRange ().first == paramRange ().second) {
result.setZero ();
return;
}
InterpolationPoints_t::const_iterator itA;
InterpolationPoints_t::const_iterator itB;
assert (fabs (configs_.rbegin()->first - paramRange ().second)
< Eigen::NumTraits<value_type>::dummy_precision());
if (param >= configs_.rbegin()->first) {
param = configs_.rbegin()->first;
itA = configs_.end(); --itA;
itB = itA; --itB;
} else {
itA = configs_.upper_bound (param);
itB = configs_.lower_bound (param);
if (itB == itA) {
if (itB == configs_.begin ()) {
++itA;
} else {
--itB;
}
}
}
assert (itA != configs_.end ());
const value_type T = itA->first - itB->first;
if (order > 1) {
result.setZero ();
return;
}
if (order == 1) {
pinocchio::difference <hpp::pinocchio::LieGroupTpl>
(device_, itA->second, itB->second, result);
result = (1/T) * result;
}
}
void InterpolatedPath::impl_velocityBound (vectorOut_t result,
const value_type& t0, const value_type& t1) const
{
InterpolationPoints_t::const_iterator next = configs_.lower_bound (t0);
InterpolationPoints_t::const_iterator current = next; ++next;
result.setZero();
vector_t tmp (result.size());
while (t1 > current->first) {
pinocchio::difference <hpp::pinocchio::LieGroupTpl>
(device_, next->second, current->second, tmp);
const value_type T = next->first - current->first;
result.noalias() = result.cwiseMax(tmp.cwiseAbs() / T);
++current; ++next;
}
}
PathPtr_t InterpolatedPath::impl_extract (const interval_t& subInterval) const
throw (projection_error)
{
// Length is assumed to be proportional to interval range
const bool reverse = (subInterval.first > subInterval.second);
const value_type tmin = (reverse)?subInterval.second:subInterval.first ;
const value_type tmax = (reverse)?subInterval.first :subInterval.second;
const value_type l = tmax - tmin;
bool success;
Configuration_t q1 (configAtParam (subInterval.first, success));
if (!success) throw projection_error
("Failed to apply constraints in InterpolatedPath::extract");
Configuration_t q2 (configAtParam (subInterval.second, success));
if (!success) throw projection_error
("Failed to apply constraints in InterpolatedPath::extract");
InterpolatedPathPtr_t result = InterpolatedPath::create (device_, q1, q2, l,
constraints ());
InterpolationPoints_t::const_iterator it = configs_.upper_bound (tmin);
if (reverse)
for (; it->first < tmax; ++it)
result->insert (l - (it->first - tmin), it->second);
else
for (; it->first < tmax; ++it)
result->insert (it->first - tmin, it->second);
return result;
}
PathPtr_t InterpolatedPath::reverse () const
{
const value_type& l = paramLength();
InterpolatedPathPtr_t result =
InterpolatedPath::create (device_, end(), initial(), l, constraints ());
if (configs_.size () > 2) {
InterpolationPoints_t::const_reverse_iterator it = configs_.rbegin();
++it;
InterpolationPoints_t::const_reverse_iterator itEnd = configs_.rend();
--itEnd;
for (; it != itEnd; ++it)
result->insert (l - it->first, it->second);
}
return result;
}
DevicePtr_t InterpolatedPath::device () const
{
return device_;
}
} // namespace core
} // namespace hpp
<commit_msg>Fix bug in InterpolatedPath::impl_compute (numerical issue)<commit_after>// Copyright (c) 2015, Joseph Mirabel
// Authors: Joseph Mirabel (joseph.mirabel@laas.fr)
//
// This file is part of hpp-core.
// hpp-core 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
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core. If not, see <http://www.gnu.org/licenses/>.
#include <hpp/core/interpolated-path.hh>
#include <hpp/util/debug.hh>
#include <hpp/pinocchio/device.hh>
#include <hpp/pinocchio/liegroup.hh>
#include <hpp/pinocchio/configuration.hh>
#include <hpp/core/config-projector.hh>
#include <hpp/core/projection-error.hh>
namespace hpp {
namespace core {
InterpolatedPath::InterpolatedPath (const DevicePtr_t& device,
ConfigurationIn_t init,
ConfigurationIn_t end,
value_type length) :
parent_t (interval_t (0, length), device->configSize (),
device->numberDof ()),
device_ (device)
{
assert (init.size() == device_->configSize ());
insert (0, init);
insert (length, end);
assert (device);
assert (length >= 0);
assert (!constraints ());
}
InterpolatedPath::InterpolatedPath (const DevicePtr_t& device,
ConfigurationIn_t init,
ConfigurationIn_t end,
value_type length,
ConstraintSetPtr_t constraints) :
parent_t (interval_t (0, length), device->configSize (),
device->numberDof (), constraints),
device_ (device)
{
assert (init.size() == device_->configSize ());
insert (0, init);
insert (length, end);
assert (device);
assert (length >= 0);
}
InterpolatedPath::InterpolatedPath (const InterpolatedPath& path) :
parent_t (path), device_ (path.device_), configs_ (path.configs_)
{
assert (initial().size() == device_->configSize ());
}
InterpolatedPath::InterpolatedPath (const InterpolatedPath& path,
const ConstraintSetPtr_t& constraints) :
parent_t (path, constraints), device_ (path.device_),
configs_ (path.configs_)
{
}
InterpolatedPathPtr_t InterpolatedPath::create (const PathPtr_t& path,
const DevicePtr_t& device, const std::size_t& nbSamples)
{
// TODO: If it is a path vector, should we get the waypoints and build
// a interpolated path from those waypoints ?
InterpolatedPath* ptr = new InterpolatedPath (device,
path->initial (), path->end(), path->length(),
path->constraints ());
InterpolatedPathPtr_t shPtr (ptr);
ptr->init (shPtr);
const value_type dl = path->length () / (value_type) (nbSamples + 1);
Configuration_t q (device->configSize ());
for (std::size_t iS = 0; iS < nbSamples; ++iS) {
const value_type u = dl * (value_type) (iS + 1);
if (!(*path) (q, u))
throw projection_error ("could not build InterpolatedPath");
ptr->insert (u, q);
}
return shPtr;
}
void InterpolatedPath::init (InterpolatedPathPtr_t self)
{
parent_t::init (self);
weak_ = self;
checkPath ();
}
void InterpolatedPath::initCopy (InterpolatedPathPtr_t self)
{
parent_t::init (self);
weak_ = self;
checkPath ();
}
bool InterpolatedPath::impl_compute (ConfigurationOut_t result,
value_type param) const
{
assert (param >= paramRange().first);
if (param == paramRange ().first || paramLength() == 0) {
result.noalias () = initial();
return true;
}
assert (fabs (configs_.rbegin()->first - paramRange ().second)
< Eigen::NumTraits<value_type>::dummy_precision());
if (param >= configs_.rbegin()->first) {
param = configs_.rbegin()->first;
result.noalias () = end();
return true;
}
InterpolationPoints_t::const_iterator itA = configs_.lower_bound (param);
assert (itA != configs_.end());
InterpolationPoints_t::const_iterator itB = itA; --itB;
const value_type T = itA->first - itB->first;
const value_type u = (param - itB->first) / T;
pinocchio::interpolate<hpp::pinocchio::LieGroupTpl> (device_, itB->second, itA->second, u, result);
return true;
}
void InterpolatedPath::impl_derivative
(vectorOut_t result, const value_type& s, size_type order) const
{
value_type param (s);
assert (param >= paramRange().first);
if (paramRange ().first == paramRange ().second) {
result.setZero ();
return;
}
InterpolationPoints_t::const_iterator itA;
InterpolationPoints_t::const_iterator itB;
assert (fabs (configs_.rbegin()->first - paramRange ().second)
< Eigen::NumTraits<value_type>::dummy_precision());
if (param >= configs_.rbegin()->first) {
param = configs_.rbegin()->first;
itA = configs_.end(); --itA;
itB = itA; --itB;
} else {
itA = configs_.upper_bound (param);
itB = configs_.lower_bound (param);
if (itB == itA) {
if (itB == configs_.begin ()) {
++itA;
} else {
--itB;
}
}
}
assert (itA != configs_.end ());
const value_type T = itA->first - itB->first;
if (order > 1) {
result.setZero ();
return;
}
if (order == 1) {
pinocchio::difference <hpp::pinocchio::LieGroupTpl>
(device_, itA->second, itB->second, result);
result = (1/T) * result;
}
}
void InterpolatedPath::impl_velocityBound (vectorOut_t result,
const value_type& t0, const value_type& t1) const
{
InterpolationPoints_t::const_iterator next = configs_.lower_bound (t0);
InterpolationPoints_t::const_iterator current = next; ++next;
result.setZero();
vector_t tmp (result.size());
while (t1 > current->first) {
pinocchio::difference <hpp::pinocchio::LieGroupTpl>
(device_, next->second, current->second, tmp);
const value_type T = next->first - current->first;
result.noalias() = result.cwiseMax(tmp.cwiseAbs() / T);
++current; ++next;
}
}
PathPtr_t InterpolatedPath::impl_extract (const interval_t& subInterval) const
throw (projection_error)
{
// Length is assumed to be proportional to interval range
const bool reverse = (subInterval.first > subInterval.second);
const value_type tmin = (reverse)?subInterval.second:subInterval.first ;
const value_type tmax = (reverse)?subInterval.first :subInterval.second;
const value_type l = tmax - tmin;
bool success;
Configuration_t q1 (configAtParam (subInterval.first, success));
if (!success) throw projection_error
("Failed to apply constraints in InterpolatedPath::extract");
Configuration_t q2 (configAtParam (subInterval.second, success));
if (!success) throw projection_error
("Failed to apply constraints in InterpolatedPath::extract");
InterpolatedPathPtr_t result = InterpolatedPath::create (device_, q1, q2, l,
constraints ());
InterpolationPoints_t::const_iterator it = configs_.upper_bound (tmin);
if (reverse)
for (; it->first < tmax; ++it)
result->insert (l - (it->first - tmin), it->second);
else
for (; it->first < tmax; ++it)
result->insert (it->first - tmin, it->second);
return result;
}
PathPtr_t InterpolatedPath::reverse () const
{
const value_type& l = paramLength();
InterpolatedPathPtr_t result =
InterpolatedPath::create (device_, end(), initial(), l, constraints ());
if (configs_.size () > 2) {
InterpolationPoints_t::const_reverse_iterator it = configs_.rbegin();
++it;
InterpolationPoints_t::const_reverse_iterator itEnd = configs_.rend();
--itEnd;
for (; it != itEnd; ++it)
result->insert (l - it->first, it->second);
}
return result;
}
DevicePtr_t InterpolatedPath::device () const
{
return device_;
}
} // namespace core
} // namespace hpp
<|endoftext|> |
<commit_before>#include "ArgConverter.h"
#include "ObjectManager.h"
#include "JniLocalRef.h"
#include "Util.h"
#include "V8GlobalHelpers.h"
#include "V8StringConstants.h"
#include "NativeScriptAssert.h"
#include "JType.h"
#include <assert.h>
#include <sstream>
#include <cstdlib>
using namespace v8;
using namespace std;
using namespace tns;
void ArgConverter::Init(JavaVM *jvm)
{
ArgConverter::jvm = jvm;
auto isolate = Isolate::GetCurrent();
auto ft = FunctionTemplate::New(isolate, ArgConverter::NativeScriptLongFunctionCallback);
ft->SetClassName(V8StringConstants::GetLongNumber());
ft->InstanceTemplate()->Set(V8StringConstants::GetValueOf(), FunctionTemplate::New(isolate, ArgConverter::NativeScriptLongValueOfFunctionCallback));
ft->InstanceTemplate()->Set(V8StringConstants::GetToString(), FunctionTemplate::New(isolate, ArgConverter::NativeScriptLongToStringFunctionCallback));
NATIVESCRIPT_NUMERA_CTOR_FUNC = new Persistent<Function>(isolate, ft->GetFunction());
auto nanObject = Number::New(isolate, numeric_limits<double>::quiet_NaN()).As<NumberObject>();
NAN_NUMBER_OBJECT = new Persistent<NumberObject>(isolate, nanObject);
}
void ArgConverter::NativeScriptLongValueOfFunctionCallback(const v8::FunctionCallbackInfo<Value>& args)
{
auto isolate = Isolate::GetCurrent();
args.GetReturnValue().Set(Number::New(isolate, numeric_limits<double>::quiet_NaN()));
}
void ArgConverter::NativeScriptLongToStringFunctionCallback(const v8::FunctionCallbackInfo<Value>& args)
{
args.GetReturnValue().Set(args.This()->Get(V8StringConstants::GetValue()));
}
void ArgConverter::NativeScriptLongFunctionCallback(const v8::FunctionCallbackInfo<Value>& args)
{
auto isolate = Isolate::GetCurrent();
args.This()->SetHiddenValue(V8StringConstants::GetJavaLong(), Boolean::New(isolate, true));
args.This()->SetHiddenValue(V8StringConstants::GetMarkedAsLong(), args[0]);
args.This()->Set(V8StringConstants::GetValue(), args[0]);
args.This()->SetPrototype(Local<NumberObject>::New(Isolate::GetCurrent(), *NAN_NUMBER_OBJECT));
}
jstring ArgConverter::ObjectToString(jobject object)
{
return (jstring)object;
}
Local<Array> ArgConverter::ConvertJavaArgsToJsArgs(jobjectArray args)
{
JEnv env;
auto isolate = Isolate::GetCurrent();
int argc = env.GetArrayLength(args) / 3;
Local<Array> arr(Array::New(isolate, argc));
int jArrayIndex = 0;
for (int i = 0; i < argc; i++)
{
JniLocalRef argTypeIDObj(env.GetObjectArrayElement(args, jArrayIndex++));
JniLocalRef arg(env.GetObjectArrayElement(args, jArrayIndex++));
JniLocalRef argJavaClassPath(env.GetObjectArrayElement(args, jArrayIndex++));
jint length;
Type argTypeID = (Type)JType::IntValue(env, argTypeIDObj);
Local<Value> jsArg;
Local<String> v8String;
switch (argTypeID)
{
case Type::Boolean:
jsArg = Boolean::New(isolate, JType::BooleanValue(env, arg));
break;
case Type::Char:
v8String = jcharToV8String(JType::CharValue(env, arg));
jsArg = v8String;
break;
case Type::Byte:
jsArg = Number::New(isolate, JType::ByteValue(env, arg));
break;
case Type::Short:
jsArg = Number::New(isolate, JType::ShortValue(env, arg));
break;
case Type::Int:
jsArg = Number::New(isolate, JType::IntValue(env, arg));
break;
case Type::Long:
jsArg = Number::New(isolate, JType::LongValue(env, arg));
break;
case Type::Float:
jsArg = Number::New(isolate, JType::FloatValue(env, arg));
break;
case Type::Double:
jsArg = Number::New(isolate, JType::DoubleValue(env, arg));
break;
case Type::String:
jsArg = jstringToV8String((jstring)arg);
break;
case Type::JsObject:
{
jint javaObjectID = JType::IntValue(env, arg);
jsArg = ObjectManager::GetJsObjectByJavaObjectStatic(javaObjectID);
if (jsArg.IsEmpty())
{
string argClassName = jstringToString(ObjectToString(argJavaClassPath));
argClassName = Util::ConvertFromCanonicalToJniName(argClassName);
jsArg = ObjectManager::CreateJSWrapperStatic(javaObjectID, argClassName);
}
break;
}
case Type::Null:
jsArg = Null(isolate);
break;
}
arr->Set(i, jsArg);
}
return arr;
}
std::string ArgConverter::jstringToString(jstring value)
{
if (value == nullptr) {
return string();
}
jsize utfLength;
bool readInBuffer = ReadJStringInBuffer(value, utfLength);
if(readInBuffer) {
string s(charBuffer, utfLength);
return s;
}
JEnv env;
jboolean f = false;
const char* chars = env.GetStringUTFChars(value, &f);
string s(chars);
env.ReleaseStringUTFChars(value, chars);
return s;
}
Local<Value> ArgConverter::jstringToV8String(jstring value)
{
if (value == nullptr)
{
return Null(Isolate::GetCurrent());
}
JEnv env;
auto chars = env.GetStringChars(value, NULL);
auto length = env.GetStringLength(value);
auto v8String = ConvertToV8String(chars, length);
env.ReleaseStringChars(value, chars);
return v8String;
}
bool ArgConverter::ReadJStringInBuffer(jstring value, jsize& utfLength) {
if (value == nullptr) {
return false;
}
JEnv env;
utfLength = env.GetStringUTFLength(value);
if(utfLength > BUFFER_SIZE) {
return false;
}
jsize strLength = env.GetStringLength(value);
// use existing buffer to prevent extensive memory allocation
env.GetStringUTFRegion(value, (jsize)0, strLength, charBuffer);
return true;
}
Local<String> ArgConverter::jcharToV8String(jchar value)
{
auto v8String = ConvertToV8String(&value, 1);
return v8String;
}
Local<Value> ArgConverter::ConvertFromJavaLong(jlong value)
{
Local<Value> convertedValue;
long long longValue = value;
auto isolate = Isolate::GetCurrent();
if ((-JS_LONG_LIMIT < longValue) && (longValue < JS_LONG_LIMIT))
{
convertedValue = Number::New(isolate, longValue);
}
else
{
char strNumber[24];
sprintf(strNumber, "%lld", longValue);
Local<Value> strValue = ConvertToV8String(strNumber);
convertedValue = Local<Function>::New(isolate, *NATIVESCRIPT_NUMERA_CTOR_FUNC)->CallAsConstructor(1, &strValue);
}
return convertedValue;
}
int64_t ArgConverter::ConvertToJavaLong(const Local<Value>& value)
{
assert(!value.IsEmpty());
auto obj = Local<Object>::Cast(value);
assert(!obj.IsEmpty());
auto valueProp = obj->Get(V8StringConstants::GetValue());
assert(!valueProp.IsEmpty());
string num = ConvertToString(valueProp->ToString());
int64_t longValue = atoll(num.c_str());
return longValue;
}
bool ArgConverter::TryConvertToJavaLong(const Local<Value>& value, jlong& javaLong)
{
bool success = false;
if (!value.IsEmpty())
{
if (value->IsNumber() || value->IsNumberObject())
{
javaLong = (jlong)value->IntegerValue();
success = true;
}
else if (value->IsObject())
{
auto obj = Local<Object>::Cast(value);
auto isJavaLongValue = obj->GetHiddenValue(V8StringConstants::GetJavaLong());
if (!isJavaLongValue.IsEmpty() && isJavaLongValue->BooleanValue())
{
javaLong = (jlong)ConvertToJavaLong(value);
success = true;
}
}
}
return success;
}
JavaVM* ArgConverter::jvm = nullptr;
Persistent<Function>* ArgConverter::NATIVESCRIPT_NUMERA_CTOR_FUNC = nullptr;
Persistent<NumberObject>* ArgConverter::NAN_NUMBER_OBJECT = nullptr;
char* ArgConverter::charBuffer = new char[ArgConverter::BUFFER_SIZE];
<commit_msg>fixed char type conversion<commit_after>#include "ArgConverter.h"
#include "ObjectManager.h"
#include "JniLocalRef.h"
#include "Util.h"
#include "V8GlobalHelpers.h"
#include "V8StringConstants.h"
#include "NativeScriptAssert.h"
#include "JType.h"
#include <assert.h>
#include <sstream>
#include <cstdlib>
using namespace v8;
using namespace std;
using namespace tns;
void ArgConverter::Init(JavaVM *jvm)
{
ArgConverter::jvm = jvm;
auto isolate = Isolate::GetCurrent();
auto ft = FunctionTemplate::New(isolate, ArgConverter::NativeScriptLongFunctionCallback);
ft->SetClassName(V8StringConstants::GetLongNumber());
ft->InstanceTemplate()->Set(V8StringConstants::GetValueOf(), FunctionTemplate::New(isolate, ArgConverter::NativeScriptLongValueOfFunctionCallback));
ft->InstanceTemplate()->Set(V8StringConstants::GetToString(), FunctionTemplate::New(isolate, ArgConverter::NativeScriptLongToStringFunctionCallback));
NATIVESCRIPT_NUMERA_CTOR_FUNC = new Persistent<Function>(isolate, ft->GetFunction());
auto nanObject = Number::New(isolate, numeric_limits<double>::quiet_NaN()).As<NumberObject>();
NAN_NUMBER_OBJECT = new Persistent<NumberObject>(isolate, nanObject);
}
void ArgConverter::NativeScriptLongValueOfFunctionCallback(const v8::FunctionCallbackInfo<Value>& args)
{
auto isolate = Isolate::GetCurrent();
args.GetReturnValue().Set(Number::New(isolate, numeric_limits<double>::quiet_NaN()));
}
void ArgConverter::NativeScriptLongToStringFunctionCallback(const v8::FunctionCallbackInfo<Value>& args)
{
args.GetReturnValue().Set(args.This()->Get(V8StringConstants::GetValue()));
}
void ArgConverter::NativeScriptLongFunctionCallback(const v8::FunctionCallbackInfo<Value>& args)
{
auto isolate = Isolate::GetCurrent();
args.This()->SetHiddenValue(V8StringConstants::GetJavaLong(), Boolean::New(isolate, true));
args.This()->SetHiddenValue(V8StringConstants::GetMarkedAsLong(), args[0]);
args.This()->Set(V8StringConstants::GetValue(), args[0]);
args.This()->SetPrototype(Local<NumberObject>::New(Isolate::GetCurrent(), *NAN_NUMBER_OBJECT));
}
jstring ArgConverter::ObjectToString(jobject object)
{
return (jstring)object;
}
Local<Array> ArgConverter::ConvertJavaArgsToJsArgs(jobjectArray args)
{
JEnv env;
auto isolate = Isolate::GetCurrent();
int argc = env.GetArrayLength(args) / 3;
Local<Array> arr(Array::New(isolate, argc));
int jArrayIndex = 0;
for (int i = 0; i < argc; i++)
{
JniLocalRef argTypeIDObj(env.GetObjectArrayElement(args, jArrayIndex++));
JniLocalRef arg(env.GetObjectArrayElement(args, jArrayIndex++));
JniLocalRef argJavaClassPath(env.GetObjectArrayElement(args, jArrayIndex++));
jint length;
Type argTypeID = (Type)JType::IntValue(env, argTypeIDObj);
Local<Value> jsArg;
switch (argTypeID)
{
case Type::Boolean:
jsArg = Boolean::New(isolate, JType::BooleanValue(env, arg));
break;
case Type::Char:
jsArg =jcharToV8String(JType::CharValue(env, arg));
break;
case Type::Byte:
jsArg = Number::New(isolate, JType::ByteValue(env, arg));
break;
case Type::Short:
jsArg = Number::New(isolate, JType::ShortValue(env, arg));
break;
case Type::Int:
jsArg = Number::New(isolate, JType::IntValue(env, arg));
break;
case Type::Long:
jsArg = Number::New(isolate, JType::LongValue(env, arg));
break;
case Type::Float:
jsArg = Number::New(isolate, JType::FloatValue(env, arg));
break;
case Type::Double:
jsArg = Number::New(isolate, JType::DoubleValue(env, arg));
break;
case Type::String:
jsArg = jstringToV8String((jstring)arg);
break;
case Type::JsObject:
{
jint javaObjectID = JType::IntValue(env, arg);
jsArg = ObjectManager::GetJsObjectByJavaObjectStatic(javaObjectID);
if (jsArg.IsEmpty())
{
string argClassName = jstringToString(ObjectToString(argJavaClassPath));
argClassName = Util::ConvertFromCanonicalToJniName(argClassName);
jsArg = ObjectManager::CreateJSWrapperStatic(javaObjectID, argClassName);
}
break;
}
case Type::Null:
jsArg = Null(isolate);
break;
}
arr->Set(i, jsArg);
}
return arr;
}
std::string ArgConverter::jstringToString(jstring value)
{
if (value == nullptr) {
return string();
}
jsize utfLength;
bool readInBuffer = ReadJStringInBuffer(value, utfLength);
if(readInBuffer) {
string s(charBuffer, utfLength);
return s;
}
JEnv env;
jboolean f = false;
const char* chars = env.GetStringUTFChars(value, &f);
string s(chars);
env.ReleaseStringUTFChars(value, chars);
return s;
}
Local<Value> ArgConverter::jstringToV8String(jstring value)
{
if (value == nullptr)
{
return Null(Isolate::GetCurrent());
}
JEnv env;
auto chars = env.GetStringChars(value, NULL);
auto length = env.GetStringLength(value);
auto v8String = ConvertToV8String(chars, length);
env.ReleaseStringChars(value, chars);
return v8String;
}
bool ArgConverter::ReadJStringInBuffer(jstring value, jsize& utfLength) {
if (value == nullptr) {
return false;
}
JEnv env;
utfLength = env.GetStringUTFLength(value);
if(utfLength > BUFFER_SIZE) {
return false;
}
jsize strLength = env.GetStringLength(value);
// use existing buffer to prevent extensive memory allocation
env.GetStringUTFRegion(value, (jsize)0, strLength, charBuffer);
return true;
}
Local<String> ArgConverter::jcharToV8String(jchar value)
{
auto v8String = ConvertToV8String(&value, 1);
return v8String;
}
Local<Value> ArgConverter::ConvertFromJavaLong(jlong value)
{
Local<Value> convertedValue;
long long longValue = value;
auto isolate = Isolate::GetCurrent();
if ((-JS_LONG_LIMIT < longValue) && (longValue < JS_LONG_LIMIT))
{
convertedValue = Number::New(isolate, longValue);
}
else
{
char strNumber[24];
sprintf(strNumber, "%lld", longValue);
Local<Value> strValue = ConvertToV8String(strNumber);
convertedValue = Local<Function>::New(isolate, *NATIVESCRIPT_NUMERA_CTOR_FUNC)->CallAsConstructor(1, &strValue);
}
return convertedValue;
}
int64_t ArgConverter::ConvertToJavaLong(const Local<Value>& value)
{
assert(!value.IsEmpty());
auto obj = Local<Object>::Cast(value);
assert(!obj.IsEmpty());
auto valueProp = obj->Get(V8StringConstants::GetValue());
assert(!valueProp.IsEmpty());
string num = ConvertToString(valueProp->ToString());
int64_t longValue = atoll(num.c_str());
return longValue;
}
bool ArgConverter::TryConvertToJavaLong(const Local<Value>& value, jlong& javaLong)
{
bool success = false;
if (!value.IsEmpty())
{
if (value->IsNumber() || value->IsNumberObject())
{
javaLong = (jlong)value->IntegerValue();
success = true;
}
else if (value->IsObject())
{
auto obj = Local<Object>::Cast(value);
auto isJavaLongValue = obj->GetHiddenValue(V8StringConstants::GetJavaLong());
if (!isJavaLongValue.IsEmpty() && isJavaLongValue->BooleanValue())
{
javaLong = (jlong)ConvertToJavaLong(value);
success = true;
}
}
}
return success;
}
JavaVM* ArgConverter::jvm = nullptr;
Persistent<Function>* ArgConverter::NATIVESCRIPT_NUMERA_CTOR_FUNC = nullptr;
Persistent<NumberObject>* ArgConverter::NAN_NUMBER_OBJECT = nullptr;
char* ArgConverter::charBuffer = new char[ArgConverter::BUFFER_SIZE];
<|endoftext|> |
<commit_before>//
// leaf-node-ground.cpp
// gepetto-viewer
//
// Created by Justin Carpentier, Mathieu Geisert in November 2014.
// Copyright (c) 2014 LAAS-CNRS. All rights reserved.
//
#include <gepetto/viewer/leaf-node-ground.h>
namespace gepetto {
namespace viewer {
/* Declaration of private function members */
void LeafNodeGround::init()
{
osgVector3 center = osgVector3( length_ , width_ , 0.f );
/* Number of cells on both dimensions */
float nX = floorf( 2.f * length_ / square_length_ );
float nY = floorf( 2.f * width_ / square_width_ );
/* According to floor operation, we adapt sizes */
//setSquareLength(2. * length_ / nX);
//setSquareWidth(2. * width_ / nY);
/* Setting base vectors */
osgVector3 x_base_square = osgVector3( square_length_ , 0.0f , 0.0f );
osgVector3 y_base_square = osgVector3( 0.0f , square_width_ , 0.0f );
/* Allocation of vertices */
::osg::Vec3ArrayRefPtr vertices_array_ptr = new ::osg::Vec3Array;
colors_array_ptr_ = new ::osg::Vec4Array;
for ( int j(0) ; j < nY ; j++ )
{
for ( int i(0) ; i < nX ; i++ )
{
vertices_array_ptr->push_back( - center + x_base_square * ((float) i) + y_base_square * ((float) (j+1)));
vertices_array_ptr->push_back( - center + x_base_square * ((float) i) + y_base_square * ((float) j));
vertices_array_ptr->push_back( - center + x_base_square * ((float) (i+1)) + y_base_square * ((float) j));
vertices_array_ptr->push_back( - center + x_base_square * ((float) (i+1)) + y_base_square * ((float) (j+1)));
if ((i+j)%2) {
colors_array_ptr_->push_back(color1_);
colors_array_ptr_->push_back(color1_);
colors_array_ptr_->push_back(color1_);
colors_array_ptr_->push_back(color1_);
}
else {
colors_array_ptr_->push_back(color2_);
colors_array_ptr_->push_back(color2_);
colors_array_ptr_->push_back(color2_);
colors_array_ptr_->push_back(color2_);
}
}
}
/* Allocating grid_geometry_ptr_ */
if (~grid_geometry_ptr_.valid()) {
grid_geometry_ptr_ = new ::osg::Geometry;
}
grid_geometry_ptr_->setVertexArray(vertices_array_ptr);
grid_geometry_ptr_->setColorArray(colors_array_ptr_);
grid_geometry_ptr_->setColorBinding(::osg::Geometry::BIND_PER_VERTEX);
/* Define the normal to all quads */
::osg::Vec3ArrayRefPtr normals_array_ptr = new ::osg::Vec3Array;
normals_array_ptr->push_back( osgVector3(0.0f,0.0f, 1.0f) );
grid_geometry_ptr_->setNormalArray( normals_array_ptr );
grid_geometry_ptr_->setNormalBinding( ::osg::Geometry::BIND_OVERALL );
/* Defining type of geometries */
grid_geometry_ptr_->addPrimitiveSet
(new ::osg::DrawArrays (::osg::PrimitiveSet::QUADS, 0,
(GLsizei) vertices_array_ptr->size ()));
/* Allocating geode_ptr_ */
if (~geode_ptr_.valid()) {
geode_ptr_ = new ::osg::Geode;
}
geode_ptr_->addDrawable(grid_geometry_ptr_);
//node_osg_ptr_->asGroup()->addChild(geode_ptr_);
asQueue()->addChild(geode_ptr_);
/* Apply colors */
setColors(color1_,color2_);
if (hasProperty("Color"))
properties_.erase("Color");
addProperty(Vector4Property::create("Color1",
Vector4Property::getterFromMemberFunction(this, &LeafNodeGround::getColor1),
Vector4Property::setterFromMemberFunction(this, &LeafNodeGround::setColor1)));
addProperty(Vector4Property::create("Color2",
Vector4Property::getterFromMemberFunction(this, &LeafNodeGround::getColor2),
Vector4Property::setterFromMemberFunction(this, &LeafNodeGround::setColor2)));
#ifdef DEBUG
std::cout << getID() << " created" << std::endl;
#endif
}
void LeafNodeGround::initWeakPtr( const LeafNodeGroundWeakPtr &other_weak_ptr )
{
weak_ptr_ = other_weak_ptr;
}
/* End of declaration of private function members */
/* Declaration of protected function members */
LeafNodeGround::LeafNodeGround(const std::string& name, const float &length, const float &width, const float &square_length, const float &square_width, const osgVector4& color1, const osgVector4& color2):
Node(name), length_(length), width_(width), square_length_(square_length), square_width_(square_width), color1_(color1), color2_(color2)
{
init();
}
LeafNodeGround::LeafNodeGround(const LeafNodeGround &other) :
Node(other.getID()), length_(other.length_), width_(other.width_), square_length_(other.square_length_), square_width_(other.square_width_), color1_(other.getColor1()), color2_(other.getColor2())
{
init();
}
/* End of declaration of protected function members */
/* Declaration of public function members */
LeafNodeGroundPtr_t LeafNodeGround::create(const std::string& name, const float& length, const float& width)
{
LeafNodeGroundPtr_t shared_ptr( new LeafNodeGround(name, length, width, length/10.f, width/10.f, osgVector4(0.,0.,0.,1.), osgVector4(1.,1.,1.,1.)) );
// Add reference to itself
shared_ptr->initWeakPtr(shared_ptr);
return shared_ptr;
}
LeafNodeGroundPtr_t LeafNodeGround::create(const std::string& name, const float &length, const float &width, const float &square_length, const float &square_width)
{
LeafNodeGroundPtr_t shared_ptr( new LeafNodeGround(name, length, width, square_length, square_width, osgVector4(0.,0.,0.,1.), osgVector4(1.,1.,1.,1.)) );
// Add reference to itself
shared_ptr->initWeakPtr(shared_ptr);
return shared_ptr;
}
LeafNodeGroundPtr_t LeafNodeGround::create(const std::string& name)
{
LeafNodeGroundPtr_t shared_ptr( new LeafNodeGround(name, 10.f, 10.f, 1.f, 1.f, osgVector4(0.,0.,0.,1.), osgVector4(1.,1.,1.,1.)) );
// Add reference to itself
shared_ptr->initWeakPtr(shared_ptr);
return shared_ptr;
}
LeafNodeGroundPtr_t LeafNodeGround::createCopy(const LeafNodeGroundPtr_t &other)
{
LeafNodeGroundPtr_t shared_ptr( new LeafNodeGround( *other ) );
// Add reference to itself
shared_ptr->initWeakPtr(shared_ptr);
return shared_ptr;
}
LeafNodeGroundPtr_t LeafNodeGround::clone(void) const
{
return LeafNodeGround::createCopy( weak_ptr_.lock() );
}
LeafNodeGroundPtr_t LeafNodeGround::self(void) const
{
return weak_ptr_.lock();
}
void LeafNodeGround::setColor(const osgVector4 &color)
{
setColor1(color);
}
void LeafNodeGround::setColor1(const osgVector4 &color1)
{
LeafNodeGround::setColors(color1, color2_);
}
void LeafNodeGround::setColor2(const osgVector4 &color2)
{
LeafNodeGround::setColors(color1_, color2);
}
void LeafNodeGround::setColors(const osgVector4 &color1 , const osgVector4 &color2)
{
color1_ = color1;
color2_ = color2;
/* Reset colors array */
colors_array_ptr_.release();
colors_array_ptr_ = new ::osg::Vec4Array;
/* Number of cells on both dimensions */
float nX = floorf( 2.f * length_ / square_length_ );
float nY = floorf( 2.f * width_ / square_width_ );
/* Set colors */
for ( int j(0) ; j < nY ; j++ )
{
for ( int i(0) ; i < nX ; i++ )
{
if ((i+j)%2) {
colors_array_ptr_->push_back(color1_);
colors_array_ptr_->push_back(color1_);
colors_array_ptr_->push_back(color1_);
colors_array_ptr_->push_back(color1_);
}
else {
colors_array_ptr_->push_back(color2_);
colors_array_ptr_->push_back(color2_);
colors_array_ptr_->push_back(color2_);
colors_array_ptr_->push_back(color2_);
}
}
}
/* Apply colors */
grid_geometry_ptr_->setColorArray(colors_array_ptr_);
grid_geometry_ptr_->setColorBinding(::osg::Geometry::BIND_PER_VERTEX);
setTransparentRenderingBin ( color1[3] < Node::TransparencyRenderingBinThreshold
|| color2[3] < Node::TransparencyRenderingBinThreshold);
setDirty();
}
LeafNodeGround::~LeafNodeGround()
{
/* Proper deletion of all tree scene */
geode_ptr_->removeDrawable(grid_geometry_ptr_);
grid_geometry_ptr_ = NULL;
this->asQueue()->removeChild(geode_ptr_);
geode_ptr_ = NULL;
colors_array_ptr_.release();
weak_ptr_.reset();
}
/* End of declaration of public function members */
} /* namespace viewer */
}
<commit_msg>Fix compilation warnings.<commit_after>//
// leaf-node-ground.cpp
// gepetto-viewer
//
// Created by Justin Carpentier, Mathieu Geisert in November 2014.
// Copyright (c) 2014 LAAS-CNRS. All rights reserved.
//
#include <gepetto/viewer/leaf-node-ground.h>
namespace gepetto {
namespace viewer {
/* Declaration of private function members */
void LeafNodeGround::init()
{
osgVector3 center = osgVector3( length_ , width_ , 0.f );
/* Number of cells on both dimensions */
float nX = floorf( 2.f * length_ / square_length_ );
float nY = floorf( 2.f * width_ / square_width_ );
/* According to floor operation, we adapt sizes */
//setSquareLength(2. * length_ / nX);
//setSquareWidth(2. * width_ / nY);
/* Setting base vectors */
osgVector3 x_base_square = osgVector3( square_length_ , 0.0f , 0.0f );
osgVector3 y_base_square = osgVector3( 0.0f , square_width_ , 0.0f );
/* Allocation of vertices */
::osg::Vec3ArrayRefPtr vertices_array_ptr = new ::osg::Vec3Array;
colors_array_ptr_ = new ::osg::Vec4Array;
for ( int j(0) ; j < (int)nY ; j++ )
{
for ( int i(0) ; i < (int)nX ; i++ )
{
vertices_array_ptr->push_back( - center + x_base_square * ((float) i) + y_base_square * ((float) (j+1)));
vertices_array_ptr->push_back( - center + x_base_square * ((float) i) + y_base_square * ((float) j));
vertices_array_ptr->push_back( - center + x_base_square * ((float) (i+1)) + y_base_square * ((float) j));
vertices_array_ptr->push_back( - center + x_base_square * ((float) (i+1)) + y_base_square * ((float) (j+1)));
if ((i+j)%2) {
colors_array_ptr_->push_back(color1_);
colors_array_ptr_->push_back(color1_);
colors_array_ptr_->push_back(color1_);
colors_array_ptr_->push_back(color1_);
}
else {
colors_array_ptr_->push_back(color2_);
colors_array_ptr_->push_back(color2_);
colors_array_ptr_->push_back(color2_);
colors_array_ptr_->push_back(color2_);
}
}
}
/* Allocating grid_geometry_ptr_ */
if (!grid_geometry_ptr_.valid()) {
grid_geometry_ptr_ = new ::osg::Geometry;
}
grid_geometry_ptr_->setVertexArray(vertices_array_ptr);
grid_geometry_ptr_->setColorArray(colors_array_ptr_);
grid_geometry_ptr_->setColorBinding(::osg::Geometry::BIND_PER_VERTEX);
/* Define the normal to all quads */
::osg::Vec3ArrayRefPtr normals_array_ptr = new ::osg::Vec3Array;
normals_array_ptr->push_back( osgVector3(0.0f,0.0f, 1.0f) );
grid_geometry_ptr_->setNormalArray( normals_array_ptr );
grid_geometry_ptr_->setNormalBinding( ::osg::Geometry::BIND_OVERALL );
/* Defining type of geometries */
grid_geometry_ptr_->addPrimitiveSet
(new ::osg::DrawArrays (::osg::PrimitiveSet::QUADS, 0,
(GLsizei) vertices_array_ptr->size ()));
/* Allocating geode_ptr_ */
if (!geode_ptr_.valid()) {
geode_ptr_ = new ::osg::Geode;
}
geode_ptr_->addDrawable(grid_geometry_ptr_);
//node_osg_ptr_->asGroup()->addChild(geode_ptr_);
asQueue()->addChild(geode_ptr_);
/* Apply colors */
setColors(color1_,color2_);
if (hasProperty("Color"))
properties_.erase("Color");
addProperty(Vector4Property::create("Color1",
Vector4Property::getterFromMemberFunction(this, &LeafNodeGround::getColor1),
Vector4Property::setterFromMemberFunction(this, &LeafNodeGround::setColor1)));
addProperty(Vector4Property::create("Color2",
Vector4Property::getterFromMemberFunction(this, &LeafNodeGround::getColor2),
Vector4Property::setterFromMemberFunction(this, &LeafNodeGround::setColor2)));
#ifdef DEBUG
std::cout << getID() << " created" << std::endl;
#endif
}
void LeafNodeGround::initWeakPtr( const LeafNodeGroundWeakPtr &other_weak_ptr )
{
weak_ptr_ = other_weak_ptr;
}
/* End of declaration of private function members */
/* Declaration of protected function members */
LeafNodeGround::LeafNodeGround(const std::string& name, const float &length, const float &width, const float &square_length, const float &square_width, const osgVector4& color1, const osgVector4& color2):
Node(name), length_(length), width_(width), square_length_(square_length), square_width_(square_width), color1_(color1), color2_(color2)
{
init();
}
LeafNodeGround::LeafNodeGround(const LeafNodeGround &other) :
Node(other.getID()), length_(other.length_), width_(other.width_), square_length_(other.square_length_), square_width_(other.square_width_), color1_(other.getColor1()), color2_(other.getColor2())
{
init();
}
/* End of declaration of protected function members */
/* Declaration of public function members */
LeafNodeGroundPtr_t LeafNodeGround::create(const std::string& name, const float& length, const float& width)
{
LeafNodeGroundPtr_t shared_ptr( new LeafNodeGround(name, length, width, length/10.f, width/10.f, osgVector4(0.,0.,0.,1.), osgVector4(1.,1.,1.,1.)) );
// Add reference to itself
shared_ptr->initWeakPtr(shared_ptr);
return shared_ptr;
}
LeafNodeGroundPtr_t LeafNodeGround::create(const std::string& name, const float &length, const float &width, const float &square_length, const float &square_width)
{
LeafNodeGroundPtr_t shared_ptr( new LeafNodeGround(name, length, width, square_length, square_width, osgVector4(0.,0.,0.,1.), osgVector4(1.,1.,1.,1.)) );
// Add reference to itself
shared_ptr->initWeakPtr(shared_ptr);
return shared_ptr;
}
LeafNodeGroundPtr_t LeafNodeGround::create(const std::string& name)
{
LeafNodeGroundPtr_t shared_ptr( new LeafNodeGround(name, 10.f, 10.f, 1.f, 1.f, osgVector4(0.,0.,0.,1.), osgVector4(1.,1.,1.,1.)) );
// Add reference to itself
shared_ptr->initWeakPtr(shared_ptr);
return shared_ptr;
}
LeafNodeGroundPtr_t LeafNodeGround::createCopy(const LeafNodeGroundPtr_t &other)
{
LeafNodeGroundPtr_t shared_ptr( new LeafNodeGround( *other ) );
// Add reference to itself
shared_ptr->initWeakPtr(shared_ptr);
return shared_ptr;
}
LeafNodeGroundPtr_t LeafNodeGround::clone(void) const
{
return LeafNodeGround::createCopy( weak_ptr_.lock() );
}
LeafNodeGroundPtr_t LeafNodeGround::self(void) const
{
return weak_ptr_.lock();
}
void LeafNodeGround::setColor(const osgVector4 &color)
{
setColor1(color);
}
void LeafNodeGround::setColor1(const osgVector4 &color1)
{
LeafNodeGround::setColors(color1, color2_);
}
void LeafNodeGround::setColor2(const osgVector4 &color2)
{
LeafNodeGround::setColors(color1_, color2);
}
void LeafNodeGround::setColors(const osgVector4 &color1 , const osgVector4 &color2)
{
color1_ = color1;
color2_ = color2;
/* Reset colors array */
colors_array_ptr_.release();
colors_array_ptr_ = new ::osg::Vec4Array;
/* Number of cells on both dimensions */
float nX = floorf( 2.f * length_ / square_length_ );
float nY = floorf( 2.f * width_ / square_width_ );
/* Set colors */
for ( int j(0) ; j < (int)nY ; j++ )
{
for ( int i(0) ; i < (int)nX ; i++ )
{
if ((i+j)%2) {
colors_array_ptr_->push_back(color1_);
colors_array_ptr_->push_back(color1_);
colors_array_ptr_->push_back(color1_);
colors_array_ptr_->push_back(color1_);
}
else {
colors_array_ptr_->push_back(color2_);
colors_array_ptr_->push_back(color2_);
colors_array_ptr_->push_back(color2_);
colors_array_ptr_->push_back(color2_);
}
}
}
/* Apply colors */
grid_geometry_ptr_->setColorArray(colors_array_ptr_);
grid_geometry_ptr_->setColorBinding(::osg::Geometry::BIND_PER_VERTEX);
setTransparentRenderingBin ( color1[3] < Node::TransparencyRenderingBinThreshold
|| color2[3] < Node::TransparencyRenderingBinThreshold);
setDirty();
}
LeafNodeGround::~LeafNodeGround()
{
/* Proper deletion of all tree scene */
geode_ptr_->removeDrawable(grid_geometry_ptr_);
grid_geometry_ptr_ = NULL;
this->asQueue()->removeChild(geode_ptr_);
geode_ptr_ = NULL;
colors_array_ptr_.release();
weak_ptr_.reset();
}
/* End of declaration of public function members */
} /* namespace viewer */
}
<|endoftext|> |
<commit_before>#include "client.h"
#include "controller/controlcontroller.h"
#include "controller/reportcontroller.h"
#include "controller/logincontroller.h"
#include "controller/registrationcontroller.h"
#include "controller/configcontroller.h"
#include "network/networkmanager.h"
#include "task/taskexecutor.h"
#include "scheduler/schedulerstorage.h"
#include "report/reportstorage.h"
#include "scheduler/scheduler.h"
#include "settings.h"
#include "log/logger.h"
#include <QCoreApplication>
#include <QNetworkAccessManager>
#include <QDebug>
#ifdef Q_OS_UNIX
#include <QSocketNotifier>
#include <sys/socket.h>
#include <signal.h>
#include <unistd.h>
#endif // Q_OS_UNIX
#ifdef Q_OS_WIN
#include <Windows.h>
#include <stdio.h>
#endif // Q_OS_WIN
// TEST INCLUDES
#include "timing/immediatetiming.h"
#include "task/task.h"
#include "measurement/btc/btc_definition.h"
#include "measurement/ping/ping_definition.h"
LOGGER(Client);
class Client::Private : public QObject
{
Q_OBJECT
public:
Private(Client* q)
: q(q)
, status(Client::Unregistered)
, networkAccessManager(new QNetworkAccessManager(q))
, schedulerStorage(&scheduler)
, reportStorage(&reportScheduler)
{
executor.setNetworkManager(&networkManager);
scheduler.setExecutor(&executor);
connect(&executor, SIGNAL(finished(TestDefinitionPtr,ResultPtr)), this, SLOT(taskFinished(TestDefinitionPtr,ResultPtr)));
}
Client* q;
// Properties
Client::Status status;
QNetworkAccessManager* networkAccessManager;
TaskExecutor executor;
Scheduler scheduler;
SchedulerStorage schedulerStorage;
ReportScheduler reportScheduler;
ReportStorage reportStorage;
Settings settings;
NetworkManager networkManager;
ControlController controlController;
ReportController reportController;
RegistrationController registrationController;
LoginController loginController;
ConfigController configController;
#ifdef Q_OS_UNIX
static int sigintFd[2];
static int sighupFd[2];
static int sigtermFd[2];
QSocketNotifier* snInt;
QSocketNotifier* snHup;
QSocketNotifier* snTerm;
// Unix signal handlers.
static void intSignalHandler(int unused);
static void hupSignalHandler(int unused);
static void termSignalHandler(int unused);
#endif // Q_OS_UNIX
// Functions
void setupUnixSignalHandlers();
#ifdef Q_OS_WIN
static BOOL CtrlHandler(DWORD ctrlType);
#endif // Q_OS_WIN
public slots:
#ifdef Q_OS_UNIX
void handleSigInt();
void handleSigHup();
void handleSigTerm();
#endif // Q_OS_UNIX
void taskFinished(const TestDefinitionPtr& test, const ResultPtr& result);
};
#ifdef Q_OS_UNIX
int Client::Private::sigintFd[2];
int Client::Private::sighupFd[2];
int Client::Private::sigtermFd[2];
void Client::Private::intSignalHandler(int)
{
char a = 1;
::write(sigintFd[0], &a, sizeof(a));
}
void Client::Private::hupSignalHandler(int)
{
char a = 1;
::write(sighupFd[0], &a, sizeof(a));
}
void Client::Private::termSignalHandler(int)
{
char a = 1;
::write(sigtermFd[0], &a, sizeof(a));
}
#endif // Q_OS_UNIX
void Client::Private::setupUnixSignalHandlers()
{
#ifdef Q_OS_UNIX
struct sigaction Int, hup, term;
Int.sa_handler = Client::Private::intSignalHandler;
sigemptyset(&Int.sa_mask);
Int.sa_flags = 0;
Int.sa_flags |= SA_RESTART;
if (sigaction(SIGINT, &Int, 0) > 0)
return;
hup.sa_handler = Client::Private::hupSignalHandler;
sigemptyset(&hup.sa_mask);
hup.sa_flags = 0;
hup.sa_flags |= SA_RESTART;
if (sigaction(SIGHUP, &hup, 0) > 0)
return;
term.sa_handler = Client::Private::termSignalHandler;
sigemptyset(&term.sa_mask);
term.sa_flags = 0;
term.sa_flags |= SA_RESTART;
if (sigaction(SIGTERM, &term, 0) > 0)
return;
if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sigintFd))
qFatal("Couldn't create INT socketpair");
if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sighupFd))
qFatal("Couldn't create HUP socketpair");
if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sigtermFd))
qFatal("Couldn't create TERM socketpair");
snInt = new QSocketNotifier(sigintFd[1], QSocketNotifier::Read, this);
connect(snInt, SIGNAL(activated(int)), this, SLOT(handleSigInt()));
snHup = new QSocketNotifier(sighupFd[1], QSocketNotifier::Read, this);
connect(snHup, SIGNAL(activated(int)), this, SLOT(handleSigHup()));
snTerm = new QSocketNotifier(sigtermFd[1], QSocketNotifier::Read, this);
connect(snTerm, SIGNAL(activated(int)), this, SLOT(handleSigTerm()));
#elif defined(Q_OS_WIN)
SetConsoleCtrlHandler((PHANDLER_ROUTINE)Private::CtrlHandler, TRUE);
#endif
}
BOOL Client::Private::CtrlHandler(DWORD ctrlType)
{
switch(ctrlType) {
case CTRL_C_EVENT:
case CTRL_CLOSE_EVENT:
LOG_INFO("Close requested, quitting.");
qApp->quit();
return TRUE;
case CTRL_LOGOFF_EVENT:
case CTRL_SHUTDOWN_EVENT:
LOG_INFO("System shutdown or user logout, quitting.");
qApp->quit();
return FALSE;
default:
return FALSE;
}
}
#ifdef Q_OS_UNIX
void Client::Private::handleSigInt()
{
snInt->setEnabled(false);
char tmp;
::read(sigintFd[1], &tmp, sizeof(tmp));
LOG_INFO("Interrupt requested, quitting.");
qApp->quit();
snInt->setEnabled(true);
}
void Client::Private::handleSigTerm()
{
snTerm->setEnabled(false);
char tmp;
::read(sigtermFd[1], &tmp, sizeof(tmp));
LOG_INFO("Termination requested, quitting.");
qApp->quit();
snTerm->setEnabled(true);
}
void Client::Private::handleSigHup()
{
snHup->setEnabled(false);
char tmp;
::read(sighupFd[1], &tmp, sizeof(tmp));
LOG_INFO("Hangup detected, quitting.");
qApp->quit();
snHup->setEnabled(true);
}
#endif // Q_OS_UNIX
void Client::Private::taskFinished(const TestDefinitionPtr &test, const ResultPtr &result)
{
ReportPtr oldReport = reportScheduler.reportByTaskId(test->id());
ResultList results = oldReport.isNull() ? ResultList() : oldReport->results();
results.append(result);
ReportPtr report(new Report(test->id(), QDateTime::currentDateTime(), results));
reportScheduler.addReport(report);
}
Client::Client(QObject *parent)
: QObject(parent)
, d(new Private(this))
{
}
Client::~Client()
{
d->schedulerStorage.storeData();
d->reportStorage.storeData();
delete d;
}
Client *Client::instance()
{
static Client* ins = NULL;
if ( !ins )
ins = new Client();
return ins;
}
bool Client::init()
{
qRegisterMetaType<TestDefinitionPtr>();
qRegisterMetaType<ResultPtr>();
d->setupUnixSignalHandlers();
d->settings.init();
// Initialize storages
d->schedulerStorage.loadData();
d->reportStorage.loadData();
// Initialize controllers
d->networkManager.init(&d->scheduler, &d->settings);
d->configController.init(&d->networkManager, &d->settings);
d->controlController.init(&d->networkManager, &d->scheduler, &d->settings);
d->reportController.init(&d->reportScheduler, &d->settings);
d->loginController.init(&d->networkManager, &d->settings);
d->registrationController.init(&d->networkManager, &d->settings);
return true;
}
void Client::btc()
{
BulkTransportCapacityDefinition btcDef("141.82.49.80", 3365, 1024*50);
TimingPtr timing(new ImmediateTiming());
TestDefinitionPtr testDefinition(new TestDefinition(QUuid::createUuid(), "btc_ma", timing, btcDef.toVariant()));
d->scheduler.enqueue(testDefinition);
}
void Client::upnp()
{
TimingPtr timing(new ImmediateTiming());
TestDefinitionPtr testDefinition(new TestDefinition("{3702e527-f84f-4542-8df6-4e3d2a0ec977}", "upnp", timing, QVariant()));
d->scheduler.enqueue(testDefinition);
}
void Client::ping()
{
PingDefinition pingDef("141.82.49.80", 4, 2);
TimingPtr timing(new ImmediateTiming());
TestDefinitionPtr testDefinition(new TestDefinition(QUuid::createUuid(), "ping", timing, pingDef.toVariant()));
d->scheduler.enqueue(testDefinition);
}
void Client::setStatus(Client::Status status)
{
if ( d->status == status )
return;
d->status = status;
emit statusChanged();
}
Client::Status Client::status() const
{
return d->status;
}
QNetworkAccessManager *Client::networkAccessManager() const
{
return d->networkAccessManager;
}
Scheduler *Client::scheduler() const
{
return &d->scheduler;
}
ReportScheduler *Client::reportScheduler() const
{
return &d->reportScheduler;
}
NetworkManager *Client::networkManager() const
{
return &d->networkManager;
}
TaskExecutor *Client::taskExecutor() const
{
return &d->executor;
}
ConfigController *Client::configController() const
{
return &d->configController;
}
RegistrationController *Client::registrationController() const
{
return &d->registrationController;
}
LoginController *Client::loginController() const
{
return &d->loginController;
}
ReportController *Client::reportController() const
{
return &d->reportController;
}
Settings *Client::settings() const
{
return &d->settings;
}
#include "client.moc"
<commit_msg>Forgot to only include the CtrlHandler on Windows.<commit_after>#include "client.h"
#include "controller/controlcontroller.h"
#include "controller/reportcontroller.h"
#include "controller/logincontroller.h"
#include "controller/registrationcontroller.h"
#include "controller/configcontroller.h"
#include "network/networkmanager.h"
#include "task/taskexecutor.h"
#include "scheduler/schedulerstorage.h"
#include "report/reportstorage.h"
#include "scheduler/scheduler.h"
#include "settings.h"
#include "log/logger.h"
#include <QCoreApplication>
#include <QNetworkAccessManager>
#include <QDebug>
#ifdef Q_OS_UNIX
#include <QSocketNotifier>
#include <sys/socket.h>
#include <signal.h>
#include <unistd.h>
#endif // Q_OS_UNIX
#ifdef Q_OS_WIN
#include <Windows.h>
#include <stdio.h>
#endif // Q_OS_WIN
// TEST INCLUDES
#include "timing/immediatetiming.h"
#include "task/task.h"
#include "measurement/btc/btc_definition.h"
#include "measurement/ping/ping_definition.h"
LOGGER(Client);
class Client::Private : public QObject
{
Q_OBJECT
public:
Private(Client* q)
: q(q)
, status(Client::Unregistered)
, networkAccessManager(new QNetworkAccessManager(q))
, schedulerStorage(&scheduler)
, reportStorage(&reportScheduler)
{
executor.setNetworkManager(&networkManager);
scheduler.setExecutor(&executor);
connect(&executor, SIGNAL(finished(TestDefinitionPtr,ResultPtr)), this, SLOT(taskFinished(TestDefinitionPtr,ResultPtr)));
}
Client* q;
// Properties
Client::Status status;
QNetworkAccessManager* networkAccessManager;
TaskExecutor executor;
Scheduler scheduler;
SchedulerStorage schedulerStorage;
ReportScheduler reportScheduler;
ReportStorage reportStorage;
Settings settings;
NetworkManager networkManager;
ControlController controlController;
ReportController reportController;
RegistrationController registrationController;
LoginController loginController;
ConfigController configController;
#ifdef Q_OS_UNIX
static int sigintFd[2];
static int sighupFd[2];
static int sigtermFd[2];
QSocketNotifier* snInt;
QSocketNotifier* snHup;
QSocketNotifier* snTerm;
// Unix signal handlers.
static void intSignalHandler(int unused);
static void hupSignalHandler(int unused);
static void termSignalHandler(int unused);
#endif // Q_OS_UNIX
// Functions
void setupUnixSignalHandlers();
#ifdef Q_OS_WIN
static BOOL CtrlHandler(DWORD ctrlType);
#endif // Q_OS_WIN
public slots:
#ifdef Q_OS_UNIX
void handleSigInt();
void handleSigHup();
void handleSigTerm();
#endif // Q_OS_UNIX
void taskFinished(const TestDefinitionPtr& test, const ResultPtr& result);
};
#ifdef Q_OS_UNIX
int Client::Private::sigintFd[2];
int Client::Private::sighupFd[2];
int Client::Private::sigtermFd[2];
void Client::Private::intSignalHandler(int)
{
char a = 1;
::write(sigintFd[0], &a, sizeof(a));
}
void Client::Private::hupSignalHandler(int)
{
char a = 1;
::write(sighupFd[0], &a, sizeof(a));
}
void Client::Private::termSignalHandler(int)
{
char a = 1;
::write(sigtermFd[0], &a, sizeof(a));
}
#endif // Q_OS_UNIX
void Client::Private::setupUnixSignalHandlers()
{
#ifdef Q_OS_UNIX
struct sigaction Int, hup, term;
Int.sa_handler = Client::Private::intSignalHandler;
sigemptyset(&Int.sa_mask);
Int.sa_flags = 0;
Int.sa_flags |= SA_RESTART;
if (sigaction(SIGINT, &Int, 0) > 0)
return;
hup.sa_handler = Client::Private::hupSignalHandler;
sigemptyset(&hup.sa_mask);
hup.sa_flags = 0;
hup.sa_flags |= SA_RESTART;
if (sigaction(SIGHUP, &hup, 0) > 0)
return;
term.sa_handler = Client::Private::termSignalHandler;
sigemptyset(&term.sa_mask);
term.sa_flags = 0;
term.sa_flags |= SA_RESTART;
if (sigaction(SIGTERM, &term, 0) > 0)
return;
if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sigintFd))
qFatal("Couldn't create INT socketpair");
if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sighupFd))
qFatal("Couldn't create HUP socketpair");
if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sigtermFd))
qFatal("Couldn't create TERM socketpair");
snInt = new QSocketNotifier(sigintFd[1], QSocketNotifier::Read, this);
connect(snInt, SIGNAL(activated(int)), this, SLOT(handleSigInt()));
snHup = new QSocketNotifier(sighupFd[1], QSocketNotifier::Read, this);
connect(snHup, SIGNAL(activated(int)), this, SLOT(handleSigHup()));
snTerm = new QSocketNotifier(sigtermFd[1], QSocketNotifier::Read, this);
connect(snTerm, SIGNAL(activated(int)), this, SLOT(handleSigTerm()));
#elif defined(Q_OS_WIN)
SetConsoleCtrlHandler((PHANDLER_ROUTINE)Private::CtrlHandler, TRUE);
#endif
}
#ifdef Q_OS_WIN
BOOL Client::Private::CtrlHandler(DWORD ctrlType)
{
switch(ctrlType) {
case CTRL_C_EVENT:
case CTRL_CLOSE_EVENT:
LOG_INFO("Close requested, quitting.");
qApp->quit();
return TRUE;
case CTRL_LOGOFF_EVENT:
case CTRL_SHUTDOWN_EVENT:
LOG_INFO("System shutdown or user logout, quitting.");
qApp->quit();
return FALSE;
default:
return FALSE;
}
}
#endif // Q_OS_WIN
#ifdef Q_OS_UNIX
void Client::Private::handleSigInt()
{
snInt->setEnabled(false);
char tmp;
::read(sigintFd[1], &tmp, sizeof(tmp));
LOG_INFO("Interrupt requested, quitting.");
qApp->quit();
snInt->setEnabled(true);
}
void Client::Private::handleSigTerm()
{
snTerm->setEnabled(false);
char tmp;
::read(sigtermFd[1], &tmp, sizeof(tmp));
LOG_INFO("Termination requested, quitting.");
qApp->quit();
snTerm->setEnabled(true);
}
void Client::Private::handleSigHup()
{
snHup->setEnabled(false);
char tmp;
::read(sighupFd[1], &tmp, sizeof(tmp));
LOG_INFO("Hangup detected, quitting.");
qApp->quit();
snHup->setEnabled(true);
}
#endif // Q_OS_UNIX
void Client::Private::taskFinished(const TestDefinitionPtr &test, const ResultPtr &result)
{
ReportPtr oldReport = reportScheduler.reportByTaskId(test->id());
ResultList results = oldReport.isNull() ? ResultList() : oldReport->results();
results.append(result);
ReportPtr report(new Report(test->id(), QDateTime::currentDateTime(), results));
reportScheduler.addReport(report);
}
Client::Client(QObject *parent)
: QObject(parent)
, d(new Private(this))
{
}
Client::~Client()
{
d->schedulerStorage.storeData();
d->reportStorage.storeData();
delete d;
}
Client *Client::instance()
{
static Client* ins = NULL;
if ( !ins )
ins = new Client();
return ins;
}
bool Client::init()
{
qRegisterMetaType<TestDefinitionPtr>();
qRegisterMetaType<ResultPtr>();
d->setupUnixSignalHandlers();
d->settings.init();
// Initialize storages
d->schedulerStorage.loadData();
d->reportStorage.loadData();
// Initialize controllers
d->networkManager.init(&d->scheduler, &d->settings);
d->configController.init(&d->networkManager, &d->settings);
d->controlController.init(&d->networkManager, &d->scheduler, &d->settings);
d->reportController.init(&d->reportScheduler, &d->settings);
d->loginController.init(&d->networkManager, &d->settings);
d->registrationController.init(&d->networkManager, &d->settings);
return true;
}
void Client::btc()
{
BulkTransportCapacityDefinition btcDef("141.82.49.80", 3365, 1024*50);
TimingPtr timing(new ImmediateTiming());
TestDefinitionPtr testDefinition(new TestDefinition(QUuid::createUuid(), "btc_ma", timing, btcDef.toVariant()));
d->scheduler.enqueue(testDefinition);
}
void Client::upnp()
{
TimingPtr timing(new ImmediateTiming());
TestDefinitionPtr testDefinition(new TestDefinition("{3702e527-f84f-4542-8df6-4e3d2a0ec977}", "upnp", timing, QVariant()));
d->scheduler.enqueue(testDefinition);
}
void Client::ping()
{
PingDefinition pingDef("141.82.49.80", 4, 2);
TimingPtr timing(new ImmediateTiming());
TestDefinitionPtr testDefinition(new TestDefinition(QUuid::createUuid(), "ping", timing, pingDef.toVariant()));
d->scheduler.enqueue(testDefinition);
}
void Client::setStatus(Client::Status status)
{
if ( d->status == status )
return;
d->status = status;
emit statusChanged();
}
Client::Status Client::status() const
{
return d->status;
}
QNetworkAccessManager *Client::networkAccessManager() const
{
return d->networkAccessManager;
}
Scheduler *Client::scheduler() const
{
return &d->scheduler;
}
ReportScheduler *Client::reportScheduler() const
{
return &d->reportScheduler;
}
NetworkManager *Client::networkManager() const
{
return &d->networkManager;
}
TaskExecutor *Client::taskExecutor() const
{
return &d->executor;
}
ConfigController *Client::configController() const
{
return &d->configController;
}
RegistrationController *Client::registrationController() const
{
return &d->registrationController;
}
LoginController *Client::loginController() const
{
return &d->loginController;
}
ReportController *Client::reportController() const
{
return &d->reportController;
}
Settings *Client::settings() const
{
return &d->settings;
}
#include "client.moc"
<|endoftext|> |
<commit_before>/*
* Copyright 2009-2018 The VOTCA Development Team (http://www.votca.org)
*
* 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 <stdexcept>
#include <stdio.h>
#include <expat.h>
#include <string.h>
#include <fstream>
#include <string>
#include <stack>
#include <iomanip>
#include <votca/tools/property.h>
#include <votca/tools/colors.h>
#include <votca/tools/tokenizer.h>
#include <votca/tools/propertyiomanipulator.h>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <unistd.h>
namespace votca { namespace tools {
using namespace std;
// ostream modifier defines the output format, level, indentation
const int Property::IOindex = std::ios_base::xalloc();
Property &Property::get(const string &key)
{
Tokenizer tok(key, ".");
Tokenizer::iterator n;
n = tok.begin();
if(n==tok.end()) return *this;
Property *p;
map<string, Property*>::iterator iter;
if(*n=="") {
p = this;
}
else {
iter = _map.find(*n);
if(iter == _map.end())
throw runtime_error("property not found: " + key);
p = (((*iter).second));
}
++n;
try {
for(; n!=tok.end(); ++n) {
p = &p->get(*n);
}
}
catch(string err) { // catch here to get full key in exception
throw runtime_error("property not found: " + key);
}
return *p;
}
std::list<Property *> Property::Select(const string &filter)
{
Tokenizer tok(filter, ".");
std::list<Property *> selection;
if(tok.begin()==tok.end()) return selection;
selection.push_back(this);
for (Tokenizer::iterator n = tok.begin();
n != tok.end(); ++n) {
std::list<Property *> childs;
for (std::list<Property *>::iterator p = selection.begin();
p != selection.end(); ++p) {
for (list<Property>::iterator iter = (*p)->_properties.begin();
iter != (*p)->_properties.end(); ++iter) {
if (wildcmp((*n).c_str(), (*iter).name().c_str())) {
childs.push_back(&(*iter));
}
}
}
selection = childs;
}
return selection;
}
static void start_hndl(void *data, const char *el, const char **attr)
{
stack<Property *> *property_stack =
(stack<Property *> *)XML_GetUserData((XML_Parser*)data);
Property *cur = property_stack->top();
Property &np = cur->add(el, "");
for (int i = 0; attr[i]; i += 2)
np.setAttribute(attr[i], attr[i + 1]);
property_stack->push(&np);
}
static void end_hndl(void *data, const char *el)
{
stack<Property *> *property_stack =
(stack<Property *> *)XML_GetUserData((XML_Parser*)data);
property_stack->pop();
}
void char_hndl(void *data, const char *txt, int txtlen)
{
stack<Property *> *property_stack =
(stack<Property *> *)XML_GetUserData((XML_Parser*)data);
Property *cur = property_stack->top();
cur->value().append(txt, txtlen);
}
bool load_property_from_xml(Property &p, string filename)
{
XML_Parser parser = XML_ParserCreate(NULL);
if (! parser)
throw std::runtime_error("Couldn't allocate memory for xml parser");
XML_UseParserAsHandlerArg(parser);
XML_SetElementHandler(parser, start_hndl, end_hndl);
XML_SetCharacterDataHandler(parser, char_hndl);
ifstream fl;
fl.open(filename.c_str());
if(!fl.is_open())
throw std::ios_base::failure("Error on open xml file: " + filename);
stack<Property *> pstack;
pstack.push(&p);
XML_SetUserData(parser, (void*)&pstack);
while(!fl.eof()) {
string line;
getline(fl, line);
line=line + "\n";
if (! XML_Parse(parser, line.c_str(), line.length(), fl.eof()))
throw std::ios_base::failure(filename + ": Parse error at line " +
boost::lexical_cast<string>(XML_GetCurrentLineNumber(parser)) + "\n" +
XML_ErrorString(XML_GetErrorCode(parser)));
}
fl.close();
XML_ParserFree(parser);
return true;
}
void PrintNodeTXT(std::ostream &out, Property &p, const int start_level, int level=0, string prefix="", string offset="")
{
if((p.value() != "") || p.HasChilds() ) {
if ( level >= start_level ) {
if((p.value()).find_first_not_of("\t\n ") != std::string::npos)
out << offset << prefix << " = " << p.value() << endl;
} else {
prefix="";
}
}
for(Property& prop:p) {
if(prefix=="") {
level++;
PrintNodeTXT(out,prop, start_level, level, prefix +prop.name(), offset );
level--;
} else {
level++;
PrintNodeTXT(out,prop, start_level, level, prefix + "." + prop.name(), offset );
level--;
}
}
}
void PrintNodeXML(std::ostream &out, Property &p, PropertyIOManipulator *piom, int level = 0, string offset = "") {
Property::AttributeIterator ia;
bool linebreak = true;
bool has_value = false;
const ColorSchemeBase *color = &DEFAULT_COLORS;
string indent("");
int start_level(0);
if (piom) {
start_level = piom->getLevel();
indent = piom->getIndentation();
color = piom->getColorScheme();
}
string cKey = color->Magenta();
string cAttribute = color->Blue();
string cAttributeValue = color->Green();
string cReset = color->Reset();
// print starting only from the start_level (the first node (level 0) can be <> </>)
if (level >= start_level) {
// print the node name
out << indent << offset << "<" << cKey << p.name() << cReset;
// print the node attributes
for (ia = p.firstAttribute(); ia != p.lastAttribute(); ++ia) {
out << " "
<< cAttribute << ia->first << cReset
<< "=\""
<< cAttributeValue << ia->second << cReset << "\"";
}
// print node value if it is not empty
has_value = ((p.value()).find_first_not_of("\t\n ") != std::string::npos);
if (has_value || p.HasChilds()) {
out << ">";
} else {
out << "/>"<<std::endl;
}
if (has_value) {
out << cAttributeValue << p.value() << cReset;
linebreak = false;
}
// check if we need the end of the line or not
if (!has_value && p.HasChilds()) out << std::endl;
if (!has_value && !p.HasChilds()) linebreak = false;
}
// continue iteratively through the rest of the nodes
for (Property& prop : p) {
level++;
if (level > start_level) offset += "\t";
PrintNodeXML(out, prop, piom, level, offset);
if (level > start_level) offset.resize(offset.size() - 1);
level--;
}
if (level >= start_level) {
if (linebreak) {
out << indent << offset << "</" << cKey << p.name() << cReset << ">" << std::endl;
} else if (has_value) {
out << "</" << cKey << p.name() << cReset << ">" << std::endl;
}
}
}
void PrintNodeTEX(std::ostream &out, Property &p, PropertyIOManipulator *piom, int level=0, string prefix="") {
list<Property>::iterator iter;
string head_name;
string _label(""); // reference of the xml file in the manual
string _section(""); // reference of the description section in the manual
string _help("");
string _default(""); // default value if supplied
string _unit(""); //unit, if supplied
int start_level(0);
if ( piom ) {
start_level = piom->getLevel();
}
string header_format("\\subsection{%1%}\n"
"\\label{%2%}\n%3%\n"
"\\rowcolors{1}{invisiblegray}{white}\n"
"{\\small\n "
"\\begin{longtable}{m{3cm}|m{2cm}|m{1cm}|m{8cm}}\n"
" option & default & unit & description\\\\\n\\hline\n");
string footer_format("\\end{longtable}\n}\n"
"\\noindent Return to the description of \\slink{%1%}{\\texttt{%2%}}.\n");
string body_format(" \\hspace{%1%pt}\\hypertarget{%2%}{%3%} & %4% & %5% & %6% \\\\\n");
// if this is the head node, print the header
if ( level == start_level ) {
head_name = p.name();
_label = "calc:" + head_name;
if ( p.hasAttribute("section") ) _section = p.getAttribute<string>("section");
if ( p.hasAttribute("help") ) _help = p.getAttribute<string>("help");
out << boost::format(header_format) % head_name % _label % _help;
prefix = p.name();
}
if ( level > start_level ) {
// if this node has children or a value or is not the first, start recursive printing
if( ( p.value() != "" || p.HasChilds() ) && level > -1) {
string _tex_name = boost::replace_all_copy( p.name(), "_", "\\_" );
if ( p.hasAttribute("default") ) _default = p.getAttribute<string>("default");
if ( p.hasAttribute("unit") ) _unit = p.getAttribute<string>("unit");
if ( p.hasAttribute("help") ) _help = p.getAttribute<string>("help");
out << boost::format(body_format) % int((level-start_level-1)*10)
% prefix
% _tex_name
% _default
% _unit
% _help;
}
}
// continue iteratively through the rest of the nodes
for(iter = p.begin(); iter != p.end(); ++iter) {
if(prefix=="") {
level++;
PrintNodeTEX(out, (*iter), piom, level, prefix);
level--;
} else {
level++;
PrintNodeTEX(out, (*iter), piom, level, prefix);
level--;
}
}
// if this is the head node, print the footer
if ( level == start_level ) out << boost::format(footer_format) % _section % head_name;
}
void PrintNodeHLP(std::ostream &out, Property &p, const int start_level=0, int level=0, string prefix="", string offset="") {
list<Property>::iterator iter;
string head_name;
string _help("");
string _unit("");
string _default("");
string _name("");
typedef Color<csRGB> ColorRGB; // use the RGB palette
ColorRGB RGB; // Instance of an RGB palette
string fmt = "t|%1%%|15t|" + string(RGB.Blue()) + "%2%"
+ string(RGB.Green()) + "%|40t|%3%%|55t|"
+ string(RGB.Reset()) + "%4%\n";
int _offset = level;
// if this is the head node, print the header
if ( level == start_level ) {
head_name = string(RGB.Magenta()) + p.name();
if ( p.hasAttribute("help") ) {
if ( p.hasAttribute("help") ) _help = string(RGB.Red()) + p.getAttribute<string>("help");
out << boost::format(" %1%: %|18t| %2%" + string(RGB.Reset()) + "\n") % head_name % _help;
}
_offset=0;
out << boost::format("%|3" + fmt) % "OPTION" % "DEFAULT" % "UNIT" % "DESCRIPTION";
}
if ( level > start_level ) {
string ofmt;
ofmt = "%|" + boost::lexical_cast<string>(_offset) + fmt;
//cout << ofmt << " " << fmt << endl;
if ( p.hasAttribute("unit") )
_unit = p.getAttribute<string>("unit");
if ( p.hasAttribute("default") )
_default = p.getAttribute<string>("default");
if ( p.hasAttribute("help") ) _help = p.getAttribute<string>("help") ;
if ( !_unit.empty() ) _unit = "[" + _unit + "]";
if ( !_default.empty() ) _default = "(" + _default + ")";
_name = p.name();
out << boost::format(ofmt)
% _name
% _default
% _unit
% _help;
}
for(iter = p.begin(); iter != p.end(); ++iter) {
if(prefix=="") {
_offset = level + 2; level++;
PrintNodeHLP(out, (*iter), start_level, level, (*iter).name(), offset);
_offset = level - 2; level--;
} else {
_offset = level + 2; level++;
PrintNodeHLP(out, (*iter), start_level, level, prefix + "." + (*iter).name(), offset);
_offset = level - 2; level--;
}
}
}
std::ostream &operator<<(std::ostream &out, Property& p)
{
if (!out.good())
return out;
std::ostream::sentry sentry(out);
if(sentry)
{
// get the property format object attached to the stream
PropertyIOManipulator *pm =
(PropertyIOManipulator*)out.pword(Property::getIOindex());
string _indentation("");
int _level = 0;
PropertyIOManipulator::Type _type = PropertyIOManipulator::XML;
if (pm) {
_indentation = pm->getIndentation();
_level = pm->getLevel();
_type = pm->getType();
// check if we > or >> to a file and remove color codes
// if ( out.tellp() != -1 ) - not suitable for pipes
if( !isatty(STDOUT_FILENO) || !isatty(STDERR_FILENO) ) {
pm->setColorScheme<csDefault>();
}
}
switch( _type )
{
default:
PrintNodeTXT(out, p, _level);
case PropertyIOManipulator::XML:
PrintNodeXML(out, p, pm);
break;
case PropertyIOManipulator::TXT:
PrintNodeTXT(out, p, _level, 0, "", _indentation);
break;
case PropertyIOManipulator::TEX:
PrintNodeTEX(out, p, pm);
break;
case PropertyIOManipulator::HLP:
PrintNodeHLP(out, p, _level, 0, "", _indentation);
break;
}
//out << endl;
}
return out;
};
}}
<commit_msg>ran clang format<commit_after>/*
* Copyright 2009-2018 The VOTCA Development Team (http://www.votca.org)
*
* 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 <expat.h>
#include <stdio.h>
#include <string.h>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <stack>
#include <stdexcept>
#include <string>
#include <votca/tools/colors.h>
#include <votca/tools/property.h>
#include <votca/tools/propertyiomanipulator.h>
#include <votca/tools/tokenizer.h>
#include <unistd.h>
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
namespace votca {
namespace tools {
using namespace std;
// ostream modifier defines the output format, level, indentation
const int Property::IOindex = std::ios_base::xalloc();
Property &Property::get(const string &key) {
Tokenizer tok(key, ".");
Tokenizer::iterator n;
n = tok.begin();
if (n == tok.end()) return *this;
Property *p;
map<string, Property *>::iterator iter;
if (*n == "") {
p = this;
} else {
iter = _map.find(*n);
if (iter == _map.end()) throw runtime_error("property not found: " + key);
p = (((*iter).second));
}
++n;
try {
for (; n != tok.end(); ++n) {
p = &p->get(*n);
}
} catch (string err) { // catch here to get full key in exception
throw runtime_error("property not found: " + key);
}
return *p;
}
std::list<Property *> Property::Select(const string &filter) {
Tokenizer tok(filter, ".");
std::list<Property *> selection;
if (tok.begin() == tok.end()) return selection;
selection.push_back(this);
for (Tokenizer::iterator n = tok.begin(); n != tok.end(); ++n) {
std::list<Property *> childs;
for (std::list<Property *>::iterator p = selection.begin();
p != selection.end(); ++p) {
for (list<Property>::iterator iter = (*p)->_properties.begin();
iter != (*p)->_properties.end(); ++iter) {
if (wildcmp((*n).c_str(), (*iter).name().c_str())) {
childs.push_back(&(*iter));
}
}
}
selection = childs;
}
return selection;
}
static void start_hndl(void *data, const char *el, const char **attr) {
stack<Property *> *property_stack =
(stack<Property *> *)XML_GetUserData((XML_Parser *)data);
Property *cur = property_stack->top();
Property &np = cur->add(el, "");
for (int i = 0; attr[i]; i += 2) np.setAttribute(attr[i], attr[i + 1]);
property_stack->push(&np);
}
static void end_hndl(void *data, const char *el) {
stack<Property *> *property_stack =
(stack<Property *> *)XML_GetUserData((XML_Parser *)data);
property_stack->pop();
}
void char_hndl(void *data, const char *txt, int txtlen) {
stack<Property *> *property_stack =
(stack<Property *> *)XML_GetUserData((XML_Parser *)data);
Property *cur = property_stack->top();
cur->value().append(txt, txtlen);
}
bool load_property_from_xml(Property &p, string filename) {
XML_Parser parser = XML_ParserCreate(NULL);
if (!parser)
throw std::runtime_error("Couldn't allocate memory for xml parser");
XML_UseParserAsHandlerArg(parser);
XML_SetElementHandler(parser, start_hndl, end_hndl);
XML_SetCharacterDataHandler(parser, char_hndl);
ifstream fl;
fl.open(filename.c_str());
if (!fl.is_open())
throw std::ios_base::failure("Error on open xml file: " + filename);
stack<Property *> pstack;
pstack.push(&p);
XML_SetUserData(parser, (void *)&pstack);
while (!fl.eof()) {
string line;
getline(fl, line);
line = line + "\n";
if (!XML_Parse(parser, line.c_str(), line.length(), fl.eof()))
throw std::ios_base::failure(
filename + ": Parse error at line " +
boost::lexical_cast<string>(XML_GetCurrentLineNumber(parser)) + "\n" +
XML_ErrorString(XML_GetErrorCode(parser)));
}
fl.close();
XML_ParserFree(parser);
return true;
}
void PrintNodeTXT(std::ostream &out, Property &p, const int start_level,
int level = 0, string prefix = "", string offset = "") {
if ((p.value() != "") || p.HasChilds()) {
if (level >= start_level) {
if ((p.value()).find_first_not_of("\t\n ") != std::string::npos)
out << offset << prefix << " = " << p.value() << endl;
} else {
prefix = "";
}
}
for (Property &prop : p) {
if (prefix == "") {
level++;
PrintNodeTXT(out, prop, start_level, level, prefix + prop.name(), offset);
level--;
} else {
level++;
PrintNodeTXT(out, prop, start_level, level, prefix + "." + prop.name(),
offset);
level--;
}
}
}
void PrintNodeXML(std::ostream &out, Property &p, PropertyIOManipulator *piom,
int level = 0, string offset = "") {
Property::AttributeIterator ia;
bool linebreak = true;
bool has_value = false;
const ColorSchemeBase *color = &DEFAULT_COLORS;
string indent("");
int start_level(0);
if (piom) {
start_level = piom->getLevel();
indent = piom->getIndentation();
color = piom->getColorScheme();
}
string cKey = color->Magenta();
string cAttribute = color->Blue();
string cAttributeValue = color->Green();
string cReset = color->Reset();
// print starting only from the start_level (the first node (level 0) can be
// <> </>)
if (level >= start_level) {
// print the node name
out << indent << offset << "<" << cKey << p.name() << cReset;
// print the node attributes
for (ia = p.firstAttribute(); ia != p.lastAttribute(); ++ia) {
out << " " << cAttribute << ia->first << cReset << "=\""
<< cAttributeValue << ia->second << cReset << "\"";
}
// print node value if it is not empty
has_value = ((p.value()).find_first_not_of("\t\n ") != std::string::npos);
if (has_value || p.HasChilds()) {
out << ">";
} else {
out << "/>" << std::endl;
}
if (has_value) {
out << cAttributeValue << p.value() << cReset;
linebreak = false;
}
// check if we need the end of the line or not
if (!has_value && p.HasChilds()) out << std::endl;
if (!has_value && !p.HasChilds()) linebreak = false;
}
// continue iteratively through the rest of the nodes
for (Property &prop : p) {
level++;
if (level > start_level) offset += "\t";
PrintNodeXML(out, prop, piom, level, offset);
if (level > start_level) offset.resize(offset.size() - 1);
level--;
}
if (level >= start_level) {
if (linebreak) {
out << indent << offset << "</" << cKey << p.name() << cReset << ">"
<< std::endl;
} else if (has_value) {
out << "</" << cKey << p.name() << cReset << ">" << std::endl;
}
}
}
void PrintNodeTEX(std::ostream &out, Property &p, PropertyIOManipulator *piom,
int level = 0, string prefix = "") {
list<Property>::iterator iter;
string head_name;
string _label(""); // reference of the xml file in the manual
string _section(""); // reference of the description section in the manual
string _help("");
string _default(""); // default value if supplied
string _unit(""); // unit, if supplied
int start_level(0);
if (piom) {
start_level = piom->getLevel();
}
string header_format(
"\\subsection{%1%}\n"
"\\label{%2%}\n%3%\n"
"\\rowcolors{1}{invisiblegray}{white}\n"
"{\\small\n "
"\\begin{longtable}{m{3cm}|m{2cm}|m{1cm}|m{8cm}}\n"
" option & default & unit & description\\\\\n\\hline\n");
string footer_format(
"\\end{longtable}\n}\n"
"\\noindent Return to the description of \\slink{%1%}{\\texttt{%2%}}.\n");
string body_format(
" \\hspace{%1%pt}\\hypertarget{%2%}{%3%} & %4% & %5% & %6% \\\\\n");
// if this is the head node, print the header
if (level == start_level) {
head_name = p.name();
_label = "calc:" + head_name;
if (p.hasAttribute("section")) _section = p.getAttribute<string>("section");
if (p.hasAttribute("help")) _help = p.getAttribute<string>("help");
out << boost::format(header_format) % head_name % _label % _help;
prefix = p.name();
}
if (level > start_level) {
// if this node has children or a value or is not the first, start recursive
// printing
if ((p.value() != "" || p.HasChilds()) && level > -1) {
string _tex_name = boost::replace_all_copy(p.name(), "_", "\\_");
if (p.hasAttribute("default"))
_default = p.getAttribute<string>("default");
if (p.hasAttribute("unit")) _unit = p.getAttribute<string>("unit");
if (p.hasAttribute("help")) _help = p.getAttribute<string>("help");
out << boost::format(body_format) % int((level - start_level - 1) * 10) %
prefix % _tex_name % _default % _unit % _help;
}
}
// continue iteratively through the rest of the nodes
for (iter = p.begin(); iter != p.end(); ++iter) {
if (prefix == "") {
level++;
PrintNodeTEX(out, (*iter), piom, level, prefix);
level--;
} else {
level++;
PrintNodeTEX(out, (*iter), piom, level, prefix);
level--;
}
}
// if this is the head node, print the footer
if (level == start_level)
out << boost::format(footer_format) % _section % head_name;
}
void PrintNodeHLP(std::ostream &out, Property &p, const int start_level = 0,
int level = 0, string prefix = "", string offset = "") {
list<Property>::iterator iter;
string head_name;
string _help("");
string _unit("");
string _default("");
string _name("");
typedef Color<csRGB> ColorRGB; // use the RGB palette
ColorRGB RGB; // Instance of an RGB palette
string fmt = "t|%1%%|15t|" + string(RGB.Blue()) + "%2%" +
string(RGB.Green()) + "%|40t|%3%%|55t|" + string(RGB.Reset()) +
"%4%\n";
int _offset = level;
// if this is the head node, print the header
if (level == start_level) {
head_name = string(RGB.Magenta()) + p.name();
if (p.hasAttribute("help")) {
if (p.hasAttribute("help"))
_help = string(RGB.Red()) + p.getAttribute<string>("help");
out << boost::format(" %1%: %|18t| %2%" + string(RGB.Reset()) + "\n") %
head_name % _help;
}
_offset = 0;
out << boost::format("%|3" + fmt) % "OPTION" % "DEFAULT" % "UNIT" %
"DESCRIPTION";
}
if (level > start_level) {
string ofmt;
ofmt = "%|" + boost::lexical_cast<string>(_offset) + fmt;
// cout << ofmt << " " << fmt << endl;
if (p.hasAttribute("unit")) _unit = p.getAttribute<string>("unit");
if (p.hasAttribute("default")) _default = p.getAttribute<string>("default");
if (p.hasAttribute("help")) _help = p.getAttribute<string>("help");
if (!_unit.empty()) _unit = "[" + _unit + "]";
if (!_default.empty()) _default = "(" + _default + ")";
_name = p.name();
out << boost::format(ofmt) % _name % _default % _unit % _help;
}
for (iter = p.begin(); iter != p.end(); ++iter) {
if (prefix == "") {
_offset = level + 2;
level++;
PrintNodeHLP(out, (*iter), start_level, level, (*iter).name(), offset);
_offset = level - 2;
level--;
} else {
_offset = level + 2;
level++;
PrintNodeHLP(out, (*iter), start_level, level,
prefix + "." + (*iter).name(), offset);
_offset = level - 2;
level--;
}
}
}
std::ostream &operator<<(std::ostream &out, Property &p) {
if (!out.good()) return out;
std::ostream::sentry sentry(out);
if (sentry) {
// get the property format object attached to the stream
PropertyIOManipulator *pm =
(PropertyIOManipulator *)out.pword(Property::getIOindex());
string _indentation("");
int _level = 0;
PropertyIOManipulator::Type _type = PropertyIOManipulator::XML;
if (pm) {
_indentation = pm->getIndentation();
_level = pm->getLevel();
_type = pm->getType();
// check if we > or >> to a file and remove color codes
// if ( out.tellp() != -1 ) - not suitable for pipes
if (!isatty(STDOUT_FILENO) || !isatty(STDERR_FILENO)) {
pm->setColorScheme<csDefault>();
}
}
switch (_type) {
default:
PrintNodeTXT(out, p, _level);
case PropertyIOManipulator::XML:
PrintNodeXML(out, p, pm);
break;
case PropertyIOManipulator::TXT:
PrintNodeTXT(out, p, _level, 0, "", _indentation);
break;
case PropertyIOManipulator::TEX:
PrintNodeTEX(out, p, pm);
break;
case PropertyIOManipulator::HLP:
PrintNodeHLP(out, p, _level, 0, "", _indentation);
break;
}
// out << endl;
}
return out;
};
}
}
<|endoftext|> |
<commit_before>#include "line_modification.hh"
#include "buffer.hh"
#include "unit_tests.hh"
namespace Kakoune
{
static LineModification make_line_modif(const Buffer::Change& change)
{
LineCount num_added = 0, num_removed = 0;
if (change.type == Buffer::Change::Insert)
num_added = change.end.line - change.begin.line;
else
num_removed = change.end.line - change.begin.line;
// modified a line
if ((change.begin.column != 0 or change.end.column != 0))
{
++num_removed;
++num_added;
}
return { change.begin.line, change.begin.line, num_removed, num_added };
}
Vector<LineModification> compute_line_modifications(const Buffer& buffer, size_t timestamp)
{
Vector<LineModification> res;
for (auto& buf_change : buffer.changes_since(timestamp))
{
auto change = make_line_modif(buf_change);
auto pos = std::upper_bound(res.begin(), res.end(), change.new_line,
[](const LineCount& l, const LineModification& c)
{ return l < c.new_line; });
if (pos != res.begin())
{
auto& prev = *(pos-1);
if (change.new_line <= prev.new_line + prev.num_added)
{
--pos;
const LineCount removed_from_previously_added_by_pos =
clamp(pos->new_line + pos->num_added - change.new_line,
0_line, std::min(pos->num_added, change.num_removed));
pos->num_removed += change.num_removed - removed_from_previously_added_by_pos;
pos->num_added += change.num_added - removed_from_previously_added_by_pos;
}
else
{
change.old_line -= prev.diff();
pos = res.insert(pos, change);
}
}
else
pos = res.insert(pos, change);
auto next = pos + 1;
auto diff = buf_change.end.line - buf_change.begin.line;
if (buf_change.type == Buffer::Change::Erase)
{
auto delend = std::upper_bound(next, res.end(), change.new_line + change.num_removed,
[](const LineCount& l, const LineModification& c)
{ return l < c.new_line; });
for (auto it = next; it != delend; ++it)
{
const LineCount removed_from_previously_added_by_it =
std::min(it->num_added, change.new_line + change.num_removed - it->new_line);
pos->num_removed += it->num_removed - removed_from_previously_added_by_it;
pos->num_added += it->num_added - removed_from_previously_added_by_it;
}
next = res.erase(next, delend);
if (diff != 0)
{
for (auto it = next; it != res.end(); ++it)
it->new_line -= diff;
}
}
else if (diff != 0)
{
for (auto it = next; it != res.end(); ++it)
it->new_line += diff;
}
}
return res;
}
bool operator==(const LineModification& lhs, const LineModification& rhs)
{
return lhs.old_line == rhs.old_line and lhs.new_line == rhs.new_line and
lhs.num_removed == rhs.num_removed and lhs.num_added == rhs.num_added;
}
void LineRangeSet::update(ConstArrayView<LineModification> modifs)
{
if (modifs.empty())
return;
for (auto it = begin(); it != end(); ++it)
{
auto modif_beg = std::lower_bound(modifs.begin(), modifs.end(), it->begin,
[](const LineModification& c, const LineCount& l)
{ return c.old_line + c.num_removed < l; });
auto modif_end = std::upper_bound(modifs.begin(), modifs.end(), it->end,
[](const LineCount& l, const LineModification& c)
{ return l < c.old_line; });
if (modif_beg == modifs.end())
{
const auto diff = (modif_beg-1)->diff();
it->begin += diff;
it->end += diff;
continue;
}
const auto diff = modif_beg->new_line - modif_beg->old_line;
it->begin += diff;
it->end += diff;
while (modif_beg != modif_end)
{
auto& m = *modif_beg++;
if (m.num_removed > 0)
{
if (m.new_line < it->begin)
it->begin = std::max(m.new_line, it->begin - m.num_removed);
it->end = std::max(m.new_line, std::max(it->begin, it->end - m.num_removed));
}
if (m.num_added > 0)
{
if (it->begin >= m.new_line)
it->begin += m.num_added;
else
{
it = insert(it, {it->begin, m.new_line}) + 1;
it->begin = m.new_line + m.num_added;
}
it->end += m.num_added;
}
}
};
erase(remove_if(*this, [](auto& r) { return r.begin >= r.end; }), end());
}
void LineRangeSet::add_range(LineRange range, FunctionRef<void (LineRange)> on_new_range)
{
auto it = std::lower_bound(begin(), end(), range.begin,
[](LineRange range, LineCount line) { return range.end < line; });
if (it == end() or it->begin > range.end)
on_new_range(range);
else
{
auto pos = range.begin;
while (it != end() and it->begin <= range.end)
{
if (pos < it->begin)
on_new_range({pos, it->begin});
range = LineRange{std::min(range.begin, it->begin), std::max(range.end, it->end)};
pos = it->end;
it = erase(it);
}
if (pos < range.end)
on_new_range({pos, range.end});
}
insert(it, range);
}
void LineRangeSet::remove_range(LineRange range)
{
auto inside = [](LineCount line, LineRange range) {
return range.begin <= line and line < range.end;
};
auto it = std::lower_bound(begin(), end(), range.begin,
[](LineRange range, LineCount line) { return range.end < line; });
if (it == end() or it->begin > range.end)
return;
else while (it != end() and it->begin <= range.end)
{
if (it->begin < range.begin and range.end <= it->end)
{
it = insert(it, {it->begin, range.begin}) + 1;
it->begin = range.end;
}
if (inside(it->begin, range))
it->begin = range.end;
if (inside(it->end, range))
it->end = range.begin;
if (it->end <= it->begin)
it = erase(it);
else
++it;
}
}
UnitTest test_line_modifications{[]()
{
auto make_lines = [](auto&&... lines) { return BufferLines{StringData::create({lines})...}; };
{
Buffer buffer("test", Buffer::Flags::None, make_lines("line 1\n", "line 2\n"));
auto ts = buffer.timestamp();
buffer.erase({1, 0}, {2, 0});
auto modifs = compute_line_modifications(buffer, ts);
kak_assert(modifs.size() == 1 and modifs[0] == LineModification{ 1, 1, 1, 0 });
}
{
Buffer buffer("test", Buffer::Flags::None, make_lines("line 1\n", "line 2\n"));
auto ts = buffer.timestamp();
buffer.insert({2, 0}, "line 3");
auto modifs = compute_line_modifications(buffer, ts);
kak_assert(modifs.size() == 1 and modifs[0] == LineModification{ 2, 2, 0, 1 });
}
{
Buffer buffer("test", Buffer::Flags::None, make_lines("line 1\n", "line 2\n", "line 3\n"));
auto ts = buffer.timestamp();
buffer.insert({1, 4}, "hoho\nhehe");
buffer.erase({0, 0}, {1, 0});
auto modifs = compute_line_modifications(buffer, ts);
kak_assert(modifs.size() == 1 and modifs[0] == LineModification{ 0, 0, 2, 2 });
}
{
Buffer buffer("test", Buffer::Flags::None, make_lines("line 1\n", "line 2\n", "line 3\n", "line 4\n"));
auto ts = buffer.timestamp();
buffer.erase({0,0}, {3,0});
buffer.insert({1,0}, "newline 1\nnewline 2\nnewline 3\n");
buffer.erase({0,0}, {1,0});
{
auto modifs = compute_line_modifications(buffer, ts);
kak_assert(modifs.size() == 1 and modifs[0] == LineModification{ 0, 0, 4, 3 });
}
buffer.insert({3,0}, "newline 4\n");
{
auto modifs = compute_line_modifications(buffer, ts);
kak_assert(modifs.size() == 1 and modifs[0] == LineModification{ 0, 0, 4, 4 });
}
}
{
Buffer buffer("test", Buffer::Flags::None, make_lines("line 1\n"));
auto ts = buffer.timestamp();
buffer.insert({0,0}, "n");
buffer.insert({0,1}, "e");
buffer.insert({0,2}, "w");
auto modifs = compute_line_modifications(buffer, ts);
kak_assert(modifs.size() == 1 and modifs[0] == LineModification{ 0, 0, 1, 1 });
}
}};
UnitTest test_line_range_set{[]{
auto expect = [](ConstArrayView<LineRange> ranges) {
return [it = ranges.begin(), end = ranges.end()](LineRange r) mutable {
kak_assert(it != end);
kak_assert(r == *it++);
};
};
{
LineRangeSet ranges;
ranges.add_range({0, 5}, expect({{0, 5}}));
ranges.add_range({10, 15}, expect({{10, 15}}));
ranges.add_range({5, 10}, expect({{5, 10}}));
kak_assert((ranges.view() == ConstArrayView<LineRange>{{0, 15}}));
ranges.add_range({5, 10}, expect({}));
ranges.remove_range({3, 8});
kak_assert((ranges.view() == ConstArrayView<LineRange>{{0, 3}, {8, 15}}));
}
{
LineRangeSet ranges;
ranges.add_range({0, 7}, expect({{0, 7}}));
ranges.add_range({9, 15}, expect({{9, 15}}));
ranges.add_range({5, 10}, expect({{7, 9}}));
kak_assert((ranges.view() == ConstArrayView<LineRange>{{0, 15}}));
}
{
LineRangeSet ranges;
ranges.add_range({0, 7}, expect({{0, 7}}));
ranges.add_range({11, 15}, expect({{11, 15}}));
ranges.add_range({5, 10}, expect({{7, 10}}));
kak_assert((ranges.view() == ConstArrayView<LineRange>{{0, 10}, {11, 15}}));
ranges.remove_range({8, 13});
kak_assert((ranges.view() == ConstArrayView<LineRange>{{0, 8}, {13, 15}}));
}
{
LineRangeSet ranges;
ranges.add_range({0, 5}, expect({{0, 5}}));
ranges.add_range({10, 15}, expect({{10, 15}}));
ranges.update(ConstArrayView<LineModification>{{3, 3, 3, 1}, {11, 9, 2, 4}});
kak_assert((ranges.view() == ConstArrayView<LineRange>{{0, 3}, {8, 9}, {13, 15}}));
}
{
LineRangeSet ranges;
ranges.add_range({0, 5}, expect({{0, 5}}));
ranges.update(ConstArrayView<LineModification>{{2, 2, 2, 0}});
kak_assert((ranges.view() == ConstArrayView<LineRange>{{0, 3}}));
}
{
LineRangeSet ranges;
ranges.add_range({0, 5}, expect({{0, 5}}));
ranges.update(ConstArrayView<LineModification>{{2, 2, 0, 2}});
kak_assert((ranges.view() == ConstArrayView<LineRange>{{0, 2}, {4, 7}}));
}
{
LineRangeSet ranges;
ranges.add_range({0, 1}, expect({{0, 1}}));
ranges.add_range({5, 10}, expect({{5, 10}}));
ranges.add_range({15, 20}, expect({{15, 20}}));
ranges.add_range({25, 30}, expect({{25, 30}}));
ranges.update(ConstArrayView<LineModification>{{2, 2, 3, 0}});
kak_assert((ranges.view() == ConstArrayView<LineRange>{{0, 1}, {2, 7}, {12, 17}, {22, 27}}));
}
}};
}
<commit_msg>Avoid potentially quadratic runtime when updating selections after modification<commit_after>#include "line_modification.hh"
#include "buffer.hh"
#include "unit_tests.hh"
namespace Kakoune
{
static LineModification make_line_modif(const Buffer::Change& change)
{
LineCount num_added = 0, num_removed = 0;
if (change.type == Buffer::Change::Insert)
num_added = change.end.line - change.begin.line;
else
num_removed = change.end.line - change.begin.line;
// modified a line
if ((change.begin.column != 0 or change.end.column != 0))
{
++num_removed;
++num_added;
}
return { change.begin.line, change.begin.line, num_removed, num_added };
}
Vector<LineModification> compute_line_modifications(const Buffer& buffer, size_t timestamp)
{
Vector<LineModification> res;
for (auto& buf_change : buffer.changes_since(timestamp))
{
auto change = make_line_modif(buf_change);
auto pos = std::upper_bound(res.begin(), res.end(), change.new_line,
[](const LineCount& l, const LineModification& c)
{ return l < c.new_line; });
if (pos != res.begin())
{
auto& prev = *(pos-1);
if (change.new_line <= prev.new_line + prev.num_added)
{
--pos;
const LineCount removed_from_previously_added_by_pos =
clamp(pos->new_line + pos->num_added - change.new_line,
0_line, std::min(pos->num_added, change.num_removed));
pos->num_removed += change.num_removed - removed_from_previously_added_by_pos;
pos->num_added += change.num_added - removed_from_previously_added_by_pos;
}
else
{
change.old_line -= prev.diff();
pos = res.insert(pos, change);
}
}
else
pos = res.insert(pos, change);
auto next = pos + 1;
auto diff = buf_change.end.line - buf_change.begin.line;
if (buf_change.type == Buffer::Change::Erase)
{
auto delend = std::upper_bound(next, res.end(), change.new_line + change.num_removed,
[](const LineCount& l, const LineModification& c)
{ return l < c.new_line; });
for (auto it = next; it != delend; ++it)
{
const LineCount removed_from_previously_added_by_it =
std::min(it->num_added, change.new_line + change.num_removed - it->new_line);
pos->num_removed += it->num_removed - removed_from_previously_added_by_it;
pos->num_added += it->num_added - removed_from_previously_added_by_it;
}
next = res.erase(next, delend);
if (diff != 0)
{
for (auto it = next; it != res.end(); ++it)
it->new_line -= diff;
}
}
else if (diff != 0)
{
for (auto it = next; it != res.end(); ++it)
it->new_line += diff;
}
}
return res;
}
bool operator==(const LineModification& lhs, const LineModification& rhs)
{
return lhs.old_line == rhs.old_line and lhs.new_line == rhs.new_line and
lhs.num_removed == rhs.num_removed and lhs.num_added == rhs.num_added;
}
void LineRangeSet::update(ConstArrayView<LineModification> modifs)
{
if (modifs.empty())
return;
for (auto it = begin(); it != end(); ++it)
{
auto modif_beg = std::lower_bound(modifs.begin(), modifs.end(), it->begin,
[](const LineModification& c, const LineCount& l)
{ return c.old_line + c.num_removed < l; });
auto modif_end = std::upper_bound(modifs.begin(), modifs.end(), it->end,
[](const LineCount& l, const LineModification& c)
{ return l < c.old_line; });
if (modif_beg == modifs.end())
{
const auto diff = (modif_beg-1)->diff();
it->begin += diff;
it->end += diff;
continue;
}
const auto diff = modif_beg->new_line - modif_beg->old_line;
it->begin += diff;
it->end += diff;
while (modif_beg != modif_end)
{
auto& m = *modif_beg++;
if (m.num_removed > 0)
{
if (m.new_line < it->begin)
it->begin = std::max(m.new_line, it->begin - m.num_removed);
it->end = std::max(m.new_line, std::max(it->begin, it->end - m.num_removed));
}
if (m.num_added > 0)
{
if (it->begin >= m.new_line)
it->begin += m.num_added;
else
{
it = insert(it, {it->begin, m.new_line}) + 1;
it->begin = m.new_line + m.num_added;
}
it->end += m.num_added;
}
}
};
erase(remove_if(*this, [](auto& r) { return r.begin >= r.end; }), end());
}
void LineRangeSet::add_range(LineRange range, FunctionRef<void (LineRange)> on_new_range)
{
auto insert_at = std::lower_bound(begin(), end(), range.begin,
[](LineRange range, LineCount line) { return range.end < line; });
if (insert_at == end() or insert_at->begin > range.end)
on_new_range(range);
else
{
auto pos = range.begin;
auto it = insert_at;
for (; it != end() and it->begin <= range.end; ++it)
{
if (pos < it->begin)
on_new_range({pos, it->begin});
range = LineRange{std::min(range.begin, it->begin), std::max(range.end, it->end)};
pos = it->end;
}
insert_at = erase(insert_at, it);
if (pos < range.end)
on_new_range({pos, range.end});
}
insert(insert_at, range);
}
void LineRangeSet::remove_range(LineRange range)
{
auto inside = [](LineCount line, LineRange range) {
return range.begin <= line and line < range.end;
};
auto it = std::lower_bound(begin(), end(), range.begin,
[](LineRange range, LineCount line) { return range.end < line; });
if (it == end() or it->begin > range.end)
return;
else while (it != end() and it->begin <= range.end)
{
if (it->begin < range.begin and range.end <= it->end)
{
it = insert(it, {it->begin, range.begin}) + 1;
it->begin = range.end;
}
if (inside(it->begin, range))
it->begin = range.end;
if (inside(it->end, range))
it->end = range.begin;
if (it->end <= it->begin)
it = erase(it);
else
++it;
}
}
UnitTest test_line_modifications{[]()
{
auto make_lines = [](auto&&... lines) { return BufferLines{StringData::create({lines})...}; };
{
Buffer buffer("test", Buffer::Flags::None, make_lines("line 1\n", "line 2\n"));
auto ts = buffer.timestamp();
buffer.erase({1, 0}, {2, 0});
auto modifs = compute_line_modifications(buffer, ts);
kak_assert(modifs.size() == 1 and modifs[0] == LineModification{ 1, 1, 1, 0 });
}
{
Buffer buffer("test", Buffer::Flags::None, make_lines("line 1\n", "line 2\n"));
auto ts = buffer.timestamp();
buffer.insert({2, 0}, "line 3");
auto modifs = compute_line_modifications(buffer, ts);
kak_assert(modifs.size() == 1 and modifs[0] == LineModification{ 2, 2, 0, 1 });
}
{
Buffer buffer("test", Buffer::Flags::None, make_lines("line 1\n", "line 2\n", "line 3\n"));
auto ts = buffer.timestamp();
buffer.insert({1, 4}, "hoho\nhehe");
buffer.erase({0, 0}, {1, 0});
auto modifs = compute_line_modifications(buffer, ts);
kak_assert(modifs.size() == 1 and modifs[0] == LineModification{ 0, 0, 2, 2 });
}
{
Buffer buffer("test", Buffer::Flags::None, make_lines("line 1\n", "line 2\n", "line 3\n", "line 4\n"));
auto ts = buffer.timestamp();
buffer.erase({0,0}, {3,0});
buffer.insert({1,0}, "newline 1\nnewline 2\nnewline 3\n");
buffer.erase({0,0}, {1,0});
{
auto modifs = compute_line_modifications(buffer, ts);
kak_assert(modifs.size() == 1 and modifs[0] == LineModification{ 0, 0, 4, 3 });
}
buffer.insert({3,0}, "newline 4\n");
{
auto modifs = compute_line_modifications(buffer, ts);
kak_assert(modifs.size() == 1 and modifs[0] == LineModification{ 0, 0, 4, 4 });
}
}
{
Buffer buffer("test", Buffer::Flags::None, make_lines("line 1\n"));
auto ts = buffer.timestamp();
buffer.insert({0,0}, "n");
buffer.insert({0,1}, "e");
buffer.insert({0,2}, "w");
auto modifs = compute_line_modifications(buffer, ts);
kak_assert(modifs.size() == 1 and modifs[0] == LineModification{ 0, 0, 1, 1 });
}
}};
UnitTest test_line_range_set{[]{
auto expect = [](ConstArrayView<LineRange> ranges) {
return [it = ranges.begin(), end = ranges.end()](LineRange r) mutable {
kak_assert(it != end);
kak_assert(r == *it++);
};
};
{
LineRangeSet ranges;
ranges.add_range({0, 5}, expect({{0, 5}}));
ranges.add_range({10, 15}, expect({{10, 15}}));
ranges.add_range({5, 10}, expect({{5, 10}}));
kak_assert((ranges.view() == ConstArrayView<LineRange>{{0, 15}}));
ranges.add_range({5, 10}, expect({}));
ranges.remove_range({3, 8});
kak_assert((ranges.view() == ConstArrayView<LineRange>{{0, 3}, {8, 15}}));
}
{
LineRangeSet ranges;
ranges.add_range({0, 7}, expect({{0, 7}}));
ranges.add_range({9, 15}, expect({{9, 15}}));
ranges.add_range({5, 10}, expect({{7, 9}}));
kak_assert((ranges.view() == ConstArrayView<LineRange>{{0, 15}}));
}
{
LineRangeSet ranges;
ranges.add_range({0, 7}, expect({{0, 7}}));
ranges.add_range({11, 15}, expect({{11, 15}}));
ranges.add_range({5, 10}, expect({{7, 10}}));
kak_assert((ranges.view() == ConstArrayView<LineRange>{{0, 10}, {11, 15}}));
ranges.remove_range({8, 13});
kak_assert((ranges.view() == ConstArrayView<LineRange>{{0, 8}, {13, 15}}));
}
{
LineRangeSet ranges;
ranges.add_range({0, 5}, expect({{0, 5}}));
ranges.add_range({10, 15}, expect({{10, 15}}));
ranges.update(ConstArrayView<LineModification>{{3, 3, 3, 1}, {11, 9, 2, 4}});
kak_assert((ranges.view() == ConstArrayView<LineRange>{{0, 3}, {8, 9}, {13, 15}}));
}
{
LineRangeSet ranges;
ranges.add_range({0, 5}, expect({{0, 5}}));
ranges.update(ConstArrayView<LineModification>{{2, 2, 2, 0}});
kak_assert((ranges.view() == ConstArrayView<LineRange>{{0, 3}}));
}
{
LineRangeSet ranges;
ranges.add_range({0, 5}, expect({{0, 5}}));
ranges.update(ConstArrayView<LineModification>{{2, 2, 0, 2}});
kak_assert((ranges.view() == ConstArrayView<LineRange>{{0, 2}, {4, 7}}));
}
{
LineRangeSet ranges;
ranges.add_range({0, 1}, expect({{0, 1}}));
ranges.add_range({5, 10}, expect({{5, 10}}));
ranges.add_range({15, 20}, expect({{15, 20}}));
ranges.add_range({25, 30}, expect({{25, 30}}));
ranges.update(ConstArrayView<LineModification>{{2, 2, 3, 0}});
kak_assert((ranges.view() == ConstArrayView<LineRange>{{0, 1}, {2, 7}, {12, 17}, {22, 27}}));
}
}};
}
<|endoftext|> |
<commit_before>/*
* Copyright 2012 Adam Murdoch
*
* 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.
*/
/*
* FreeBSD (including OS X) specific functions.
*/
#if defined(__APPLE__) || defined(__FreeBSD__)
#include "native.h"
#include "generic.h"
#include <string.h>
#include <stdlib.h>
#include <sys/param.h>
#include <sys/ucred.h>
#include <sys/mount.h>
#if defined(__APPLE__)
#include <sys/attr.h>
#endif
#include <unistd.h>
#include <errno.h>
typedef struct vol_caps_buf {
u_int32_t size;
vol_capabilities_attr_t caps;
} vol_caps_buf_t;
/*
* File system functions
*/
JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixFileSystemFunctions_listFileSystems(JNIEnv *env, jclass target, jobject info, jobject result) {
int fs_count = getfsstat(NULL, 0, MNT_NOWAIT);
if (fs_count < 0) {
mark_failed_with_errno(env, "could not stat file systems", result);
return;
}
size_t len = fs_count * sizeof(struct statfs);
struct statfs* buf = (struct statfs*)malloc(len);
if (getfsstat(buf, len, MNT_NOWAIT) < 0 ) {
mark_failed_with_errno(env, "could not stat file systems", result);
free(buf);
return;
}
jclass info_class = env->GetObjectClass(info);
jmethodID method = env->GetMethodID(info_class, "add", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZ)V");
for (int i = 0; i < fs_count; i++) {
jboolean caseSensitive = JNI_TRUE;
jboolean casePreserving = JNI_TRUE;
#if defined(__APPLE__)
struct attrlist alist;
memset(&alist, 0, sizeof(alist));
alist.bitmapcount = ATTR_BIT_MAP_COUNT;
alist.volattr = ATTR_VOL_CAPABILITIES | ATTR_VOL_INFO;
vol_caps_buf_t buffer;
// getattrlist requires the path to the actual mount point.
int err = getattrlist(buf[i].f_mntonname, &alist, &buffer, sizeof(buffer), 0);
if (err != 0) {
mark_failed_with_errno(env, "could not determine file system attributes", result);
break;
}
if (alist.volattr & ATTR_VOL_CAPABILITIES) {
if ((buffer.caps.valid[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_CASE_SENSITIVE)) {
caseSensitive = (buffer.caps.capabilities[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_CASE_SENSITIVE) != 0;
}
if ((buffer.caps.valid[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_CASE_PRESERVING)) {
casePreserving = (buffer.caps.capabilities[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_CASE_PRESERVING) != 0;
}
}
#endif
jstring mount_point = char_to_java(env, buf[i].f_mntonname, result);
jstring file_system_type = char_to_java(env, buf[i].f_fstypename, result);
jstring device_name = char_to_java(env, buf[i].f_mntfromname, result);
jboolean remote = (buf[i].f_flags & MNT_LOCAL) == 0;
env->CallVoidMethod(info, method, mount_point, file_system_type, device_name, remote, caseSensitive, casePreserving);
}
free(buf);
}
#endif
<commit_msg>Fixed compilation on FreeBSD.<commit_after>/*
* Copyright 2012 Adam Murdoch
*
* 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.
*/
/*
* FreeBSD (including OS X) specific functions.
*/
#if defined(__APPLE__) || defined(__FreeBSD__)
#include "native.h"
#include "generic.h"
#include <string.h>
#include <stdlib.h>
#include <sys/param.h>
#include <sys/ucred.h>
#include <sys/mount.h>
#include <unistd.h>
#include <errno.h>
#if defined(__APPLE__)
#include <sys/attr.h>
typedef struct vol_caps_buf {
u_int32_t size;
vol_capabilities_attr_t caps;
} vol_caps_buf_t;
#endif
/*
* File system functions
*/
JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixFileSystemFunctions_listFileSystems(JNIEnv *env, jclass target, jobject info, jobject result) {
int fs_count = getfsstat(NULL, 0, MNT_NOWAIT);
if (fs_count < 0) {
mark_failed_with_errno(env, "could not stat file systems", result);
return;
}
size_t len = fs_count * sizeof(struct statfs);
struct statfs* buf = (struct statfs*)malloc(len);
if (getfsstat(buf, len, MNT_NOWAIT) < 0 ) {
mark_failed_with_errno(env, "could not stat file systems", result);
free(buf);
return;
}
jclass info_class = env->GetObjectClass(info);
jmethodID method = env->GetMethodID(info_class, "add", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZ)V");
for (int i = 0; i < fs_count; i++) {
jboolean caseSensitive = JNI_TRUE;
jboolean casePreserving = JNI_TRUE;
#if defined(__APPLE__)
struct attrlist alist;
memset(&alist, 0, sizeof(alist));
alist.bitmapcount = ATTR_BIT_MAP_COUNT;
alist.volattr = ATTR_VOL_CAPABILITIES | ATTR_VOL_INFO;
vol_caps_buf_t buffer;
// getattrlist requires the path to the actual mount point.
int err = getattrlist(buf[i].f_mntonname, &alist, &buffer, sizeof(buffer), 0);
if (err != 0) {
mark_failed_with_errno(env, "could not determine file system attributes", result);
break;
}
if (alist.volattr & ATTR_VOL_CAPABILITIES) {
if ((buffer.caps.valid[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_CASE_SENSITIVE)) {
caseSensitive = (buffer.caps.capabilities[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_CASE_SENSITIVE) != 0;
}
if ((buffer.caps.valid[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_CASE_PRESERVING)) {
casePreserving = (buffer.caps.capabilities[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_CASE_PRESERVING) != 0;
}
}
#endif
jstring mount_point = char_to_java(env, buf[i].f_mntonname, result);
jstring file_system_type = char_to_java(env, buf[i].f_fstypename, result);
jstring device_name = char_to_java(env, buf[i].f_mntfromname, result);
jboolean remote = (buf[i].f_flags & MNT_LOCAL) == 0;
env->CallVoidMethod(info, method, mount_point, file_system_type, device_name, remote, caseSensitive, casePreserving);
}
free(buf);
}
#endif
<|endoftext|> |
<commit_before><commit_msg>SID_SAVE_ONLY_USED_SYMBOLS missing from starmath print options itemset<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: register.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: kz $ $Date: 2008-03-06 18:45: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_starmath.hxx"
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#include <sfx2/sfxmodelfactory.hxx>
#include "smdll.hxx"
#include "document.hxx"
#include "unomodel.hxx"
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
//Math document
extern Sequence< OUString > SAL_CALL
SmDocument_getSupportedServiceNames() throw();
extern OUString SAL_CALL
SmDocument_getImplementationName() throw();
extern Reference< XInterface >SAL_CALL
SmDocument_createInstance(const Reference< XMultiServiceFactory > & rSMgr, const sal_uInt64 _nCreationFlags) throw( Exception );
//MathML import
extern Sequence< OUString > SAL_CALL
SmXMLImport_getSupportedServiceNames() throw();
extern OUString SAL_CALL
SmXMLImport_getImplementationName() throw();
extern Reference< XInterface > SAL_CALL
SmXMLImport_createInstance(const Reference< XMultiServiceFactory > & rSMgr) throw( Exception );
extern Sequence< OUString > SAL_CALL
SmXMLImportMeta_getSupportedServiceNames() throw();
extern OUString SAL_CALL
SmXMLImportMeta_getImplementationName() throw();
extern Reference< XInterface > SAL_CALL
SmXMLImportMeta_createInstance(const Reference< XMultiServiceFactory > & rSMgr) throw( Exception );
extern Sequence< OUString > SAL_CALL
SmXMLImportSettings_getSupportedServiceNames() throw();
extern OUString SAL_CALL SmXMLImportSettings_getImplementationName() throw();
extern Reference< XInterface > SAL_CALL
SmXMLImportSettings_createInstance(const Reference< XMultiServiceFactory > & rSMgr) throw( Exception );
//MathML export
extern Sequence< OUString > SAL_CALL
SmXMLExport_getSupportedServiceNames() throw();
extern OUString SAL_CALL
SmXMLExport_getImplementationName() throw();
extern Reference< XInterface > SAL_CALL
SmXMLExport_createInstance(const Reference< XMultiServiceFactory > & rSMgr) throw( Exception );
extern Sequence< OUString > SAL_CALL
SmXMLExportMetaOOO_getSupportedServiceNames() throw();
extern OUString SAL_CALL
SmXMLExportMetaOOO_getImplementationName() throw();
extern Reference< XInterface > SAL_CALL
SmXMLExportMetaOOO_createInstance(const Reference< XMultiServiceFactory > & rSMgr) throw( Exception );
extern Sequence< OUString > SAL_CALL
SmXMLExportMeta_getSupportedServiceNames() throw();
extern OUString SAL_CALL
SmXMLExportMeta_getImplementationName() throw();
extern Reference< XInterface > SAL_CALL
SmXMLExportMeta_createInstance(const Reference< XMultiServiceFactory > & rSMgr) throw( Exception );
extern Sequence< OUString > SAL_CALL
SmXMLExportSettingsOOO_getSupportedServiceNames() throw();
extern OUString SAL_CALL
SmXMLExportSettingsOOO_getImplementationName() throw();
extern Reference< XInterface > SAL_CALL
SmXMLExportSettingsOOO_createInstance(const Reference< XMultiServiceFactory > & rSMgr) throw( Exception );
extern Sequence< OUString > SAL_CALL
SmXMLExportSettings_getSupportedServiceNames() throw();
extern OUString SAL_CALL
SmXMLExportSettings_getImplementationName() throw();
extern Reference< XInterface > SAL_CALL
SmXMLExportSettings_createInstance(const Reference< XMultiServiceFactory > & rSMgr) throw( Exception );
extern Sequence< OUString > SAL_CALL
SmXMLExportContent_getSupportedServiceNames() throw();
extern OUString SAL_CALL
SmXMLExportContent_getImplementationName() throw();
extern Reference< XInterface > SAL_CALL
SmXMLExportContent_createInstance(const Reference< XMultiServiceFactory > & rSMgr) throw( Exception );
extern "C" {
void SAL_CALL component_getImplementationEnvironment(
const sal_Char** ppEnvironmentTypeName,
uno_Environment** /*ppEnvironment*/ )
{
*ppEnvironmentTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ;
}
sal_Bool SAL_CALL component_writeInfo( void* /*pServiceManager*/,
void* pRegistryKey )
{
Reference< registry::XRegistryKey >
xKey( reinterpret_cast< registry::XRegistryKey* >( pRegistryKey ) ) ;
OUString aDelimiter( RTL_CONSTASCII_USTRINGPARAM("/") );
OUString aUnoServices( RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") );
// Eigentliche Implementierung und ihre Services registrieren
sal_Int32 i;
Reference< registry::XRegistryKey > xNewKey;
xNewKey = xKey->createKey( aDelimiter + SmXMLImport_getImplementationName() +
aUnoServices );
Sequence< OUString > aServices = SmXMLImport_getSupportedServiceNames();
for(i = 0; i < aServices.getLength(); i++ )
xNewKey->createKey( aServices.getConstArray()[i] );
xNewKey = xKey->createKey( aDelimiter + SmXMLExport_getImplementationName() +
aUnoServices );
aServices = SmXMLExport_getSupportedServiceNames();
for(i = 0; i < aServices.getLength(); i++ )
xNewKey->createKey( aServices.getConstArray()[i] );
xNewKey = xKey->createKey( aDelimiter + SmXMLImportMeta_getImplementationName() +
aUnoServices );
aServices = SmXMLImportMeta_getSupportedServiceNames();
for(i = 0; i < aServices.getLength(); i++ )
xNewKey->createKey( aServices.getConstArray()[i] );
xNewKey = xKey->createKey( aDelimiter + SmXMLExportMetaOOO_getImplementationName() +
aUnoServices );
aServices = SmXMLExportMetaOOO_getSupportedServiceNames();
for(i = 0; i < aServices.getLength(); i++ )
xNewKey->createKey( aServices.getConstArray()[i] );
xNewKey = xKey->createKey( aDelimiter + SmXMLExportMeta_getImplementationName() +
aUnoServices );
aServices = SmXMLExportMeta_getSupportedServiceNames();
for(i = 0; i < aServices.getLength(); i++ )
xNewKey->createKey( aServices.getConstArray()[i] );
xNewKey = xKey->createKey( aDelimiter + SmXMLImportSettings_getImplementationName() +
aUnoServices );
aServices = SmXMLImportSettings_getSupportedServiceNames();
for(i = 0; i < aServices.getLength(); i++ )
xNewKey->createKey( aServices.getConstArray()[i] );
xNewKey = xKey->createKey( aDelimiter + SmXMLExportSettingsOOO_getImplementationName() +
aUnoServices );
aServices = SmXMLExportSettingsOOO_getSupportedServiceNames();
for(i = 0; i < aServices.getLength(); i++ )
xNewKey->createKey( aServices.getConstArray()[i] );
xNewKey = xKey->createKey( aDelimiter + SmXMLExportSettings_getImplementationName() +
aUnoServices );
aServices = SmXMLExportSettings_getSupportedServiceNames();
for(i = 0; i < aServices.getLength(); i++ )
xNewKey->createKey( aServices.getConstArray()[i] );
xNewKey = xKey->createKey( aDelimiter + SmXMLExportContent_getImplementationName() +
aUnoServices );
aServices = SmXMLExportContent_getSupportedServiceNames();
for(i = 0; i < aServices.getLength(); i++ )
xNewKey->createKey( aServices.getConstArray()[i] );
xNewKey = xKey->createKey( aDelimiter + SmDocument_getImplementationName() +
aUnoServices );
aServices = SmDocument_getSupportedServiceNames();
for(i = 0; i < aServices.getLength(); i++ )
xNewKey->createKey( aServices.getConstArray()[i] );
return sal_True;
}
void* SAL_CALL component_getFactory( const sal_Char* pImplementationName,
void* pServiceManager,
void* /*pRegistryKey*/ )
{
// Set default return value for this operation - if it failed.
void* pReturn = NULL ;
if (
( pImplementationName != NULL ) &&
( pServiceManager != NULL )
)
{
// Define variables which are used in following macros.
Reference< XSingleServiceFactory > xFactory ;
Reference< XMultiServiceFactory > xServiceManager( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ;
if( SmXMLImport_getImplementationName().equalsAsciiL(
pImplementationName, strlen(pImplementationName)) )
{
xFactory = ::cppu::createSingleFactory( xServiceManager,
SmXMLImport_getImplementationName(),
SmXMLImport_createInstance,
SmXMLImport_getSupportedServiceNames() );
}
else if( SmXMLExport_getImplementationName().equalsAsciiL(
pImplementationName, strlen(pImplementationName)) )
{
xFactory = ::cppu::createSingleFactory( xServiceManager,
SmXMLExport_getImplementationName(),
SmXMLExport_createInstance,
SmXMLExport_getSupportedServiceNames() );
}
else if( SmXMLImportMeta_getImplementationName().equalsAsciiL(
pImplementationName, strlen(pImplementationName)) )
{
xFactory = ::cppu::createSingleFactory( xServiceManager,
SmXMLImportMeta_getImplementationName(),
SmXMLImportMeta_createInstance,
SmXMLImportMeta_getSupportedServiceNames() );
}
else if( SmXMLExportMetaOOO_getImplementationName().equalsAsciiL(
pImplementationName, strlen(pImplementationName)) )
{
xFactory = ::cppu::createSingleFactory( xServiceManager,
SmXMLExportMetaOOO_getImplementationName(),
SmXMLExportMetaOOO_createInstance,
SmXMLExportMetaOOO_getSupportedServiceNames() );
}
else if( SmXMLExportMeta_getImplementationName().equalsAsciiL(
pImplementationName, strlen(pImplementationName)) )
{
xFactory = ::cppu::createSingleFactory( xServiceManager,
SmXMLExportMeta_getImplementationName(),
SmXMLExportMeta_createInstance,
SmXMLExportMeta_getSupportedServiceNames() );
}
else if( SmXMLImportSettings_getImplementationName().equalsAsciiL(
pImplementationName, strlen(pImplementationName)) )
{
xFactory = ::cppu::createSingleFactory( xServiceManager,
SmXMLImportSettings_getImplementationName(),
SmXMLImportSettings_createInstance,
SmXMLImportSettings_getSupportedServiceNames() );
}
else if( SmXMLExportSettingsOOO_getImplementationName().equalsAsciiL(
pImplementationName, strlen(pImplementationName)) )
{
xFactory = ::cppu::createSingleFactory( xServiceManager,
SmXMLExportSettingsOOO_getImplementationName(),
SmXMLExportSettingsOOO_createInstance,
SmXMLExportSettingsOOO_getSupportedServiceNames() );
}
else if( SmXMLExportSettings_getImplementationName().equalsAsciiL(
pImplementationName, strlen(pImplementationName)) )
{
xFactory = ::cppu::createSingleFactory( xServiceManager,
SmXMLExportSettings_getImplementationName(),
SmXMLExportSettings_createInstance,
SmXMLExportSettings_getSupportedServiceNames() );
}
else if( SmXMLExportContent_getImplementationName().equalsAsciiL(
pImplementationName, strlen(pImplementationName)) )
{
xFactory = ::cppu::createSingleFactory( xServiceManager,
SmXMLExportContent_getImplementationName(),
SmXMLExportContent_createInstance,
SmXMLExportContent_getSupportedServiceNames() );
}
else if( SmDocument_getImplementationName().equalsAsciiL(
pImplementationName, strlen(pImplementationName)) )
{
xFactory = ::sfx2::createSfxModelFactory( xServiceManager,
SmDocument_getImplementationName(),
SmDocument_createInstance,
SmDocument_getSupportedServiceNames() );
}
// Factory is valid - service was found.
if ( xFactory.is() )
{
xFactory->acquire();
pReturn = xFactory.get();
}
}
// Return with result of this operation.
return pReturn ;
}
} // extern "C"
<commit_msg>INTEGRATION: CWS changefileheader (1.13.4); FILE MERGED 2008/04/01 15:41:59 thb 1.13.4.3: #i85898# Stripping all external header guards 2008/04/01 12:41:40 thb 1.13.4.2: #i85898# Stripping all external header guards 2008/03/31 16:29:44 rt 1.13.4.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: register.cxx,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.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_starmath.hxx"
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/uno/Sequence.h>
#include <rtl/ustring.hxx>
#include <sfx2/sfxmodelfactory.hxx>
#include "smdll.hxx"
#include "document.hxx"
#include "unomodel.hxx"
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
//Math document
extern Sequence< OUString > SAL_CALL
SmDocument_getSupportedServiceNames() throw();
extern OUString SAL_CALL
SmDocument_getImplementationName() throw();
extern Reference< XInterface >SAL_CALL
SmDocument_createInstance(const Reference< XMultiServiceFactory > & rSMgr, const sal_uInt64 _nCreationFlags) throw( Exception );
//MathML import
extern Sequence< OUString > SAL_CALL
SmXMLImport_getSupportedServiceNames() throw();
extern OUString SAL_CALL
SmXMLImport_getImplementationName() throw();
extern Reference< XInterface > SAL_CALL
SmXMLImport_createInstance(const Reference< XMultiServiceFactory > & rSMgr) throw( Exception );
extern Sequence< OUString > SAL_CALL
SmXMLImportMeta_getSupportedServiceNames() throw();
extern OUString SAL_CALL
SmXMLImportMeta_getImplementationName() throw();
extern Reference< XInterface > SAL_CALL
SmXMLImportMeta_createInstance(const Reference< XMultiServiceFactory > & rSMgr) throw( Exception );
extern Sequence< OUString > SAL_CALL
SmXMLImportSettings_getSupportedServiceNames() throw();
extern OUString SAL_CALL SmXMLImportSettings_getImplementationName() throw();
extern Reference< XInterface > SAL_CALL
SmXMLImportSettings_createInstance(const Reference< XMultiServiceFactory > & rSMgr) throw( Exception );
//MathML export
extern Sequence< OUString > SAL_CALL
SmXMLExport_getSupportedServiceNames() throw();
extern OUString SAL_CALL
SmXMLExport_getImplementationName() throw();
extern Reference< XInterface > SAL_CALL
SmXMLExport_createInstance(const Reference< XMultiServiceFactory > & rSMgr) throw( Exception );
extern Sequence< OUString > SAL_CALL
SmXMLExportMetaOOO_getSupportedServiceNames() throw();
extern OUString SAL_CALL
SmXMLExportMetaOOO_getImplementationName() throw();
extern Reference< XInterface > SAL_CALL
SmXMLExportMetaOOO_createInstance(const Reference< XMultiServiceFactory > & rSMgr) throw( Exception );
extern Sequence< OUString > SAL_CALL
SmXMLExportMeta_getSupportedServiceNames() throw();
extern OUString SAL_CALL
SmXMLExportMeta_getImplementationName() throw();
extern Reference< XInterface > SAL_CALL
SmXMLExportMeta_createInstance(const Reference< XMultiServiceFactory > & rSMgr) throw( Exception );
extern Sequence< OUString > SAL_CALL
SmXMLExportSettingsOOO_getSupportedServiceNames() throw();
extern OUString SAL_CALL
SmXMLExportSettingsOOO_getImplementationName() throw();
extern Reference< XInterface > SAL_CALL
SmXMLExportSettingsOOO_createInstance(const Reference< XMultiServiceFactory > & rSMgr) throw( Exception );
extern Sequence< OUString > SAL_CALL
SmXMLExportSettings_getSupportedServiceNames() throw();
extern OUString SAL_CALL
SmXMLExportSettings_getImplementationName() throw();
extern Reference< XInterface > SAL_CALL
SmXMLExportSettings_createInstance(const Reference< XMultiServiceFactory > & rSMgr) throw( Exception );
extern Sequence< OUString > SAL_CALL
SmXMLExportContent_getSupportedServiceNames() throw();
extern OUString SAL_CALL
SmXMLExportContent_getImplementationName() throw();
extern Reference< XInterface > SAL_CALL
SmXMLExportContent_createInstance(const Reference< XMultiServiceFactory > & rSMgr) throw( Exception );
extern "C" {
void SAL_CALL component_getImplementationEnvironment(
const sal_Char** ppEnvironmentTypeName,
uno_Environment** /*ppEnvironment*/ )
{
*ppEnvironmentTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ;
}
sal_Bool SAL_CALL component_writeInfo( void* /*pServiceManager*/,
void* pRegistryKey )
{
Reference< registry::XRegistryKey >
xKey( reinterpret_cast< registry::XRegistryKey* >( pRegistryKey ) ) ;
OUString aDelimiter( RTL_CONSTASCII_USTRINGPARAM("/") );
OUString aUnoServices( RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") );
// Eigentliche Implementierung und ihre Services registrieren
sal_Int32 i;
Reference< registry::XRegistryKey > xNewKey;
xNewKey = xKey->createKey( aDelimiter + SmXMLImport_getImplementationName() +
aUnoServices );
Sequence< OUString > aServices = SmXMLImport_getSupportedServiceNames();
for(i = 0; i < aServices.getLength(); i++ )
xNewKey->createKey( aServices.getConstArray()[i] );
xNewKey = xKey->createKey( aDelimiter + SmXMLExport_getImplementationName() +
aUnoServices );
aServices = SmXMLExport_getSupportedServiceNames();
for(i = 0; i < aServices.getLength(); i++ )
xNewKey->createKey( aServices.getConstArray()[i] );
xNewKey = xKey->createKey( aDelimiter + SmXMLImportMeta_getImplementationName() +
aUnoServices );
aServices = SmXMLImportMeta_getSupportedServiceNames();
for(i = 0; i < aServices.getLength(); i++ )
xNewKey->createKey( aServices.getConstArray()[i] );
xNewKey = xKey->createKey( aDelimiter + SmXMLExportMetaOOO_getImplementationName() +
aUnoServices );
aServices = SmXMLExportMetaOOO_getSupportedServiceNames();
for(i = 0; i < aServices.getLength(); i++ )
xNewKey->createKey( aServices.getConstArray()[i] );
xNewKey = xKey->createKey( aDelimiter + SmXMLExportMeta_getImplementationName() +
aUnoServices );
aServices = SmXMLExportMeta_getSupportedServiceNames();
for(i = 0; i < aServices.getLength(); i++ )
xNewKey->createKey( aServices.getConstArray()[i] );
xNewKey = xKey->createKey( aDelimiter + SmXMLImportSettings_getImplementationName() +
aUnoServices );
aServices = SmXMLImportSettings_getSupportedServiceNames();
for(i = 0; i < aServices.getLength(); i++ )
xNewKey->createKey( aServices.getConstArray()[i] );
xNewKey = xKey->createKey( aDelimiter + SmXMLExportSettingsOOO_getImplementationName() +
aUnoServices );
aServices = SmXMLExportSettingsOOO_getSupportedServiceNames();
for(i = 0; i < aServices.getLength(); i++ )
xNewKey->createKey( aServices.getConstArray()[i] );
xNewKey = xKey->createKey( aDelimiter + SmXMLExportSettings_getImplementationName() +
aUnoServices );
aServices = SmXMLExportSettings_getSupportedServiceNames();
for(i = 0; i < aServices.getLength(); i++ )
xNewKey->createKey( aServices.getConstArray()[i] );
xNewKey = xKey->createKey( aDelimiter + SmXMLExportContent_getImplementationName() +
aUnoServices );
aServices = SmXMLExportContent_getSupportedServiceNames();
for(i = 0; i < aServices.getLength(); i++ )
xNewKey->createKey( aServices.getConstArray()[i] );
xNewKey = xKey->createKey( aDelimiter + SmDocument_getImplementationName() +
aUnoServices );
aServices = SmDocument_getSupportedServiceNames();
for(i = 0; i < aServices.getLength(); i++ )
xNewKey->createKey( aServices.getConstArray()[i] );
return sal_True;
}
void* SAL_CALL component_getFactory( const sal_Char* pImplementationName,
void* pServiceManager,
void* /*pRegistryKey*/ )
{
// Set default return value for this operation - if it failed.
void* pReturn = NULL ;
if (
( pImplementationName != NULL ) &&
( pServiceManager != NULL )
)
{
// Define variables which are used in following macros.
Reference< XSingleServiceFactory > xFactory ;
Reference< XMultiServiceFactory > xServiceManager( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ;
if( SmXMLImport_getImplementationName().equalsAsciiL(
pImplementationName, strlen(pImplementationName)) )
{
xFactory = ::cppu::createSingleFactory( xServiceManager,
SmXMLImport_getImplementationName(),
SmXMLImport_createInstance,
SmXMLImport_getSupportedServiceNames() );
}
else if( SmXMLExport_getImplementationName().equalsAsciiL(
pImplementationName, strlen(pImplementationName)) )
{
xFactory = ::cppu::createSingleFactory( xServiceManager,
SmXMLExport_getImplementationName(),
SmXMLExport_createInstance,
SmXMLExport_getSupportedServiceNames() );
}
else if( SmXMLImportMeta_getImplementationName().equalsAsciiL(
pImplementationName, strlen(pImplementationName)) )
{
xFactory = ::cppu::createSingleFactory( xServiceManager,
SmXMLImportMeta_getImplementationName(),
SmXMLImportMeta_createInstance,
SmXMLImportMeta_getSupportedServiceNames() );
}
else if( SmXMLExportMetaOOO_getImplementationName().equalsAsciiL(
pImplementationName, strlen(pImplementationName)) )
{
xFactory = ::cppu::createSingleFactory( xServiceManager,
SmXMLExportMetaOOO_getImplementationName(),
SmXMLExportMetaOOO_createInstance,
SmXMLExportMetaOOO_getSupportedServiceNames() );
}
else if( SmXMLExportMeta_getImplementationName().equalsAsciiL(
pImplementationName, strlen(pImplementationName)) )
{
xFactory = ::cppu::createSingleFactory( xServiceManager,
SmXMLExportMeta_getImplementationName(),
SmXMLExportMeta_createInstance,
SmXMLExportMeta_getSupportedServiceNames() );
}
else if( SmXMLImportSettings_getImplementationName().equalsAsciiL(
pImplementationName, strlen(pImplementationName)) )
{
xFactory = ::cppu::createSingleFactory( xServiceManager,
SmXMLImportSettings_getImplementationName(),
SmXMLImportSettings_createInstance,
SmXMLImportSettings_getSupportedServiceNames() );
}
else if( SmXMLExportSettingsOOO_getImplementationName().equalsAsciiL(
pImplementationName, strlen(pImplementationName)) )
{
xFactory = ::cppu::createSingleFactory( xServiceManager,
SmXMLExportSettingsOOO_getImplementationName(),
SmXMLExportSettingsOOO_createInstance,
SmXMLExportSettingsOOO_getSupportedServiceNames() );
}
else if( SmXMLExportSettings_getImplementationName().equalsAsciiL(
pImplementationName, strlen(pImplementationName)) )
{
xFactory = ::cppu::createSingleFactory( xServiceManager,
SmXMLExportSettings_getImplementationName(),
SmXMLExportSettings_createInstance,
SmXMLExportSettings_getSupportedServiceNames() );
}
else if( SmXMLExportContent_getImplementationName().equalsAsciiL(
pImplementationName, strlen(pImplementationName)) )
{
xFactory = ::cppu::createSingleFactory( xServiceManager,
SmXMLExportContent_getImplementationName(),
SmXMLExportContent_createInstance,
SmXMLExportContent_getSupportedServiceNames() );
}
else if( SmDocument_getImplementationName().equalsAsciiL(
pImplementationName, strlen(pImplementationName)) )
{
xFactory = ::sfx2::createSfxModelFactory( xServiceManager,
SmDocument_getImplementationName(),
SmDocument_createInstance,
SmDocument_getSupportedServiceNames() );
}
// Factory is valid - service was found.
if ( xFactory.is() )
{
xFactory->acquire();
pReturn = xFactory.get();
}
}
// Return with result of this operation.
return pReturn ;
}
} // extern "C"
<|endoftext|> |
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_PDELAB_HH
#define DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_PDELAB_HH
#include <memory>
#include <type_traits>
#include <dune/geometry/genericgeometry/topologytypes.hh>
#include <dune/common/typetraits.hh>
#include <dune/stuff/common/disable_warnings.hh>
#include <dune/common/fvector.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#if HAVE_DUNE_ISTL
#include <dune/stuff/common/disable_warnings.hh>
#include <dune/istl/paamg/pinfo.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#include <dune/stuff/la/solver/istl_amg.hh>
#endif
#if HAVE_DUNE_PDELAB
#include <dune/stuff/common/disable_warnings.hh>
#include <dune/pdelab/finiteelementmap/pkfem.hh>
#include <dune/pdelab/finiteelementmap/qkfem.hh>
#include <dune/pdelab/gridfunctionspace/gridfunctionspace.hh>
#include <dune/pdelab/constraints/conforming.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#endif // HAVE_DUNE_PDELAB
#include <dune/gdt/spaces/parallel.hh>
#include "../../mapper/pdelab.hh"
#include "../../basefunctionset/pdelab.hh"
#include "base.hh"
namespace Dune {
namespace GDT {
namespace Spaces {
namespace ContinuousLagrange {
#if HAVE_DUNE_PDELAB
// forward, to be used in the traits and to allow for specialization
template <class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>
class PdelabBased
{
static_assert((Dune::AlwaysFalse<GridViewImp>::value), "Untested for this combination of dimensions!");
};
template <class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>
class PdelabBasedTraits
{
public:
typedef PdelabBased<GridViewImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols> derived_type;
typedef GridViewImp GridViewType;
static const int polOrder = polynomialOrder;
static_assert(polOrder >= 1, "Wrong polOrder given!");
private:
typedef typename GridViewType::ctype DomainFieldType;
public:
static const unsigned int dimDomain = GridViewType::dimension;
typedef RangeFieldImp RangeFieldType;
static const unsigned int dimRange = rangeDim;
static const unsigned int dimRangeCols = rangeDimCols;
private:
template <class G, bool single_geom, bool is_simplex, bool is_cube>
struct FeMap
{
static_assert(Dune::AlwaysFalse<G>::value,
"This space is only implemented for either fully simplicial or fully cubic grids!");
};
template <class G>
struct FeMap<G, true, true, false>
{
typedef PDELab::PkLocalFiniteElementMap<GridViewType, DomainFieldType, RangeFieldType, polOrder> Type;
};
template <class G>
struct FeMap<G, true, false, true>
{
typedef PDELab::QkLocalFiniteElementMap<GridViewType, DomainFieldType, RangeFieldType, polOrder> Type;
};
typedef typename GridViewType::Grid GridType;
static const bool single_geom_ = Dune::Capabilities::hasSingleGeometryType<GridType>::v;
static const bool simplicial_ = (Dune::Capabilities::hasSingleGeometryType<GridType>::topologyId
== GenericGeometry::SimplexTopology<dimDomain>::type::id);
static const bool cubic_ = (Dune::Capabilities::hasSingleGeometryType<GridType>::topologyId
== GenericGeometry::CubeTopology<dimDomain>::type::id);
typedef typename FeMap<GridType, single_geom_, simplicial_, cubic_>::Type FEMapType;
public:
typedef PDELab::GridFunctionSpace<GridViewType, FEMapType, PDELab::OverlappingConformingDirichletConstraints>
BackendType;
typedef Mapper::SimplePdelabWrapper<BackendType> MapperType;
typedef typename GridViewType::template Codim<0>::Entity EntityType;
typedef BaseFunctionSet::PdelabWrapper<BackendType, EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange,
dimRangeCols> BaseFunctionSetType;
static const Stuff::Grid::ChoosePartView part_view_type = Stuff::Grid::ChoosePartView::view;
static const bool needs_grid_view = true;
typedef typename CommunicationChooser<GridViewType>::Type CommunicatorType;
private:
friend class PdelabBased<GridViewImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols>;
}; // class SpaceWrappedFemContinuousLagrangeTraits
template <class GridViewImp, int polynomialOrder, class RangeFieldImp>
class PdelabBased<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1>
: public Spaces::ContinuousLagrangeBase<PdelabBasedTraits<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1>,
GridViewImp::dimension, RangeFieldImp, 1, 1>
{
typedef Spaces::ContinuousLagrangeBase<PdelabBasedTraits<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1>,
GridViewImp::dimension, RangeFieldImp, 1, 1> BaseType;
typedef PdelabBased<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1> ThisType;
public:
typedef PdelabBasedTraits<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1> Traits;
typedef typename Traits::GridViewType GridViewType;
static const int polOrder = Traits::polOrder;
typedef typename GridViewType::ctype DomainFieldType;
static const unsigned int dimDomain = GridViewType::dimension;
typedef FieldVector<DomainFieldType, dimDomain> DomainType;
typedef typename Traits::RangeFieldType RangeFieldType;
static const unsigned int dimRange = Traits::dimRange;
static const unsigned int dimRangeCols = Traits::dimRangeCols;
typedef typename Traits::BackendType BackendType;
typedef typename Traits::MapperType MapperType;
typedef typename Traits::BaseFunctionSetType BaseFunctionSetType;
typedef typename Traits::CommunicatorType CommunicatorType;
private:
typedef typename Traits::FEMapType FEMapType;
public:
typedef typename BaseType::IntersectionType IntersectionType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::PatternType PatternType;
typedef typename BaseType::BoundaryInfoType BoundaryInfoType;
PdelabBased(const std::shared_ptr<const GridViewType>& gV)
: gridView_(gV)
, fe_map_(std::make_shared<FEMapType>(*(gridView_)))
, backend_(std::make_shared<BackendType>(const_cast<GridViewType&>(*gridView_), *(*fe_map_)))
, mapper_(std::make_shared<MapperType>(*(*backend_)))
, communicator_(CommunicationChooser<GridViewImp>::create(*gridView_))
, communicator_prepared_(false)
{
}
PdelabBased(const ThisType& other)
: gridView_(other.gridView_)
, fe_map_(other.fe_map_)
, backend_(other.backend_)
, mapper_(other.mapper_)
, communicator_(other.communicator_)
, communicator_prepared_(other.communicator_prepared_)
{
}
ThisType& operator=(const ThisType& other)
{
if (this != &other) {
gridView_ = other.gridView_;
fe_map_ = other.fe_map_;
backend_ = other.backend_;
mapper_ = other.mapper_;
communicator_ = other.communicator_;
communicator_prepared_ = other.communicator_prepared_;
}
return *this;
}
~PdelabBased()
{
}
const std::shared_ptr<const GridViewType>& grid_view() const
{
return gridView_;
}
const BackendType& backend() const
{
return *(*backend_);
}
const MapperType& mapper() const
{
return *(*mapper_);
}
BaseFunctionSetType base_function_set(const EntityType& entity) const
{
return BaseFunctionSetType(*(*backend_), entity);
}
CommunicatorType& communicator() const
{
std::lock_guard<std::mutex> gg(communicator_mutex_);
if (!communicator_prepared_) {
communicator_prepared_ = CommunicationChooser<GridViewType>::prepare(*this, *communicator_);
}
return *communicator_;
} // ... communicator(...)
private:
std::shared_ptr<const GridViewType> gridView_;
DS::PerThreadValue<std::shared_ptr<const FEMapType>> fe_map_;
DS::PerThreadValue<std::shared_ptr<const BackendType>> backend_;
DS::PerThreadValue<std::shared_ptr<const MapperType>> mapper_;
mutable std::shared_ptr<CommunicatorType> communicator_;
mutable bool communicator_prepared_;
mutable std::mutex communicator_mutex_;
}; // class PdelabBased< ..., 1 >
#else // HAVE_DUNE_PDELAB
template <class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>
class PdelabBased
{
static_assert((Dune::AlwaysFalse<GridViewImp>::value), "You are missing dune-pdelab!");
};
#endif // HAVE_DUNE_PDELAB
} // namespace ContinuousLagrange
} // namespace Spaces
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_PDELAB_HH
<commit_msg>[spaces.cg.pdelab] fixed closing comment<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_PDELAB_HH
#define DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_PDELAB_HH
#include <memory>
#include <type_traits>
#include <dune/geometry/genericgeometry/topologytypes.hh>
#include <dune/common/typetraits.hh>
#include <dune/stuff/common/disable_warnings.hh>
#include <dune/common/fvector.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#if HAVE_DUNE_ISTL
#include <dune/stuff/common/disable_warnings.hh>
#include <dune/istl/paamg/pinfo.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#include <dune/stuff/la/solver/istl_amg.hh>
#endif
#if HAVE_DUNE_PDELAB
#include <dune/stuff/common/disable_warnings.hh>
#include <dune/pdelab/finiteelementmap/pkfem.hh>
#include <dune/pdelab/finiteelementmap/qkfem.hh>
#include <dune/pdelab/gridfunctionspace/gridfunctionspace.hh>
#include <dune/pdelab/constraints/conforming.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#endif // HAVE_DUNE_PDELAB
#include <dune/gdt/spaces/parallel.hh>
#include "../../mapper/pdelab.hh"
#include "../../basefunctionset/pdelab.hh"
#include "base.hh"
namespace Dune {
namespace GDT {
namespace Spaces {
namespace ContinuousLagrange {
#if HAVE_DUNE_PDELAB
// forward, to be used in the traits and to allow for specialization
template <class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>
class PdelabBased
{
static_assert((Dune::AlwaysFalse<GridViewImp>::value), "Untested for this combination of dimensions!");
};
template <class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>
class PdelabBasedTraits
{
public:
typedef PdelabBased<GridViewImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols> derived_type;
typedef GridViewImp GridViewType;
static const int polOrder = polynomialOrder;
static_assert(polOrder >= 1, "Wrong polOrder given!");
private:
typedef typename GridViewType::ctype DomainFieldType;
public:
static const unsigned int dimDomain = GridViewType::dimension;
typedef RangeFieldImp RangeFieldType;
static const unsigned int dimRange = rangeDim;
static const unsigned int dimRangeCols = rangeDimCols;
private:
template <class G, bool single_geom, bool is_simplex, bool is_cube>
struct FeMap
{
static_assert(Dune::AlwaysFalse<G>::value,
"This space is only implemented for either fully simplicial or fully cubic grids!");
};
template <class G>
struct FeMap<G, true, true, false>
{
typedef PDELab::PkLocalFiniteElementMap<GridViewType, DomainFieldType, RangeFieldType, polOrder> Type;
};
template <class G>
struct FeMap<G, true, false, true>
{
typedef PDELab::QkLocalFiniteElementMap<GridViewType, DomainFieldType, RangeFieldType, polOrder> Type;
};
typedef typename GridViewType::Grid GridType;
static const bool single_geom_ = Dune::Capabilities::hasSingleGeometryType<GridType>::v;
static const bool simplicial_ = (Dune::Capabilities::hasSingleGeometryType<GridType>::topologyId
== GenericGeometry::SimplexTopology<dimDomain>::type::id);
static const bool cubic_ = (Dune::Capabilities::hasSingleGeometryType<GridType>::topologyId
== GenericGeometry::CubeTopology<dimDomain>::type::id);
typedef typename FeMap<GridType, single_geom_, simplicial_, cubic_>::Type FEMapType;
public:
typedef PDELab::GridFunctionSpace<GridViewType, FEMapType, PDELab::OverlappingConformingDirichletConstraints>
BackendType;
typedef Mapper::SimplePdelabWrapper<BackendType> MapperType;
typedef typename GridViewType::template Codim<0>::Entity EntityType;
typedef BaseFunctionSet::PdelabWrapper<BackendType, EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange,
dimRangeCols> BaseFunctionSetType;
static const Stuff::Grid::ChoosePartView part_view_type = Stuff::Grid::ChoosePartView::view;
static const bool needs_grid_view = true;
typedef typename CommunicationChooser<GridViewType>::Type CommunicatorType;
private:
friend class PdelabBased<GridViewImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols>;
}; // class PdelabBasedTraits
template <class GridViewImp, int polynomialOrder, class RangeFieldImp>
class PdelabBased<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1>
: public Spaces::ContinuousLagrangeBase<PdelabBasedTraits<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1>,
GridViewImp::dimension, RangeFieldImp, 1, 1>
{
typedef Spaces::ContinuousLagrangeBase<PdelabBasedTraits<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1>,
GridViewImp::dimension, RangeFieldImp, 1, 1> BaseType;
typedef PdelabBased<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1> ThisType;
public:
typedef PdelabBasedTraits<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1> Traits;
typedef typename Traits::GridViewType GridViewType;
static const int polOrder = Traits::polOrder;
typedef typename GridViewType::ctype DomainFieldType;
static const unsigned int dimDomain = GridViewType::dimension;
typedef FieldVector<DomainFieldType, dimDomain> DomainType;
typedef typename Traits::RangeFieldType RangeFieldType;
static const unsigned int dimRange = Traits::dimRange;
static const unsigned int dimRangeCols = Traits::dimRangeCols;
typedef typename Traits::BackendType BackendType;
typedef typename Traits::MapperType MapperType;
typedef typename Traits::BaseFunctionSetType BaseFunctionSetType;
typedef typename Traits::CommunicatorType CommunicatorType;
private:
typedef typename Traits::FEMapType FEMapType;
public:
typedef typename BaseType::IntersectionType IntersectionType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::PatternType PatternType;
typedef typename BaseType::BoundaryInfoType BoundaryInfoType;
PdelabBased(const std::shared_ptr<const GridViewType>& gV)
: gridView_(gV)
, fe_map_(std::make_shared<FEMapType>(*(gridView_)))
, backend_(std::make_shared<BackendType>(const_cast<GridViewType&>(*gridView_), *(*fe_map_)))
, mapper_(std::make_shared<MapperType>(*(*backend_)))
, communicator_(CommunicationChooser<GridViewImp>::create(*gridView_))
, communicator_prepared_(false)
{
}
PdelabBased(const ThisType& other)
: gridView_(other.gridView_)
, fe_map_(other.fe_map_)
, backend_(other.backend_)
, mapper_(other.mapper_)
, communicator_(other.communicator_)
, communicator_prepared_(other.communicator_prepared_)
{
}
ThisType& operator=(const ThisType& other)
{
if (this != &other) {
gridView_ = other.gridView_;
fe_map_ = other.fe_map_;
backend_ = other.backend_;
mapper_ = other.mapper_;
communicator_ = other.communicator_;
communicator_prepared_ = other.communicator_prepared_;
}
return *this;
}
~PdelabBased()
{
}
const std::shared_ptr<const GridViewType>& grid_view() const
{
return gridView_;
}
const BackendType& backend() const
{
return *(*backend_);
}
const MapperType& mapper() const
{
return *(*mapper_);
}
BaseFunctionSetType base_function_set(const EntityType& entity) const
{
return BaseFunctionSetType(*(*backend_), entity);
}
CommunicatorType& communicator() const
{
std::lock_guard<std::mutex> gg(communicator_mutex_);
if (!communicator_prepared_) {
communicator_prepared_ = CommunicationChooser<GridViewType>::prepare(*this, *communicator_);
}
return *communicator_;
} // ... communicator(...)
private:
std::shared_ptr<const GridViewType> gridView_;
DS::PerThreadValue<std::shared_ptr<const FEMapType>> fe_map_;
DS::PerThreadValue<std::shared_ptr<const BackendType>> backend_;
DS::PerThreadValue<std::shared_ptr<const MapperType>> mapper_;
mutable std::shared_ptr<CommunicatorType> communicator_;
mutable bool communicator_prepared_;
mutable std::mutex communicator_mutex_;
}; // class PdelabBased< ..., 1 >
#else // HAVE_DUNE_PDELAB
template <class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>
class PdelabBased
{
static_assert((Dune::AlwaysFalse<GridViewImp>::value), "You are missing dune-pdelab!");
};
#endif // HAVE_DUNE_PDELAB
} // namespace ContinuousLagrange
} // namespace Spaces
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_PDELAB_HH
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: MetaImportComponent.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2005-09-09 14:17: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 _XMLOFF_METAIMPORTCOMPONENT_HXX
#include "MetaImportComponent.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_XMLMETAI_HXX
#include "xmlmetai.hxx"
#endif
using namespace ::com::sun::star;
using namespace ::xmloff::token;
class SvXMLMetaDocumentContext : public SvXMLImportContext
{
private:
::com::sun::star::uno::Reference<
::com::sun::star::document::XDocumentInfo> xDocInfo;
public:
SvXMLMetaDocumentContext(SvXMLImport& rImport, USHORT nPrfx,
const rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList,
const ::com::sun::star::uno::Reference<
::com::sun::star::document::XDocumentInfo>& rDocInfo);
virtual ~SvXMLMetaDocumentContext();
virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,
const rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList );
virtual void EndElement();
};
SvXMLMetaDocumentContext::SvXMLMetaDocumentContext(SvXMLImport& rImport,
USHORT nPrfx, const rtl::OUString& rLName,
const uno::Reference<xml::sax::XAttributeList>& xAttrList,
const uno::Reference<document::XDocumentInfo>& rDocInfo) :
SvXMLImportContext( rImport, nPrfx, rLName ),
xDocInfo(rDocInfo)
{
// here are no attributes
}
SvXMLMetaDocumentContext::~SvXMLMetaDocumentContext()
{
}
SvXMLImportContext *SvXMLMetaDocumentContext::CreateChildContext( USHORT nPrefix,
const rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
if ( (XML_NAMESPACE_OFFICE == nPrefix) &&
IsXMLToken(rLocalName, XML_META) )
{
return new SfxXMLMetaContext(GetImport(), nPrefix, rLocalName, xDocInfo);
}
else
{
return new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
}
}
void SvXMLMetaDocumentContext::EndElement()
{
}
//===========================================================================
// #110680#
XMLMetaImportComponent::XMLMetaImportComponent(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory) throw()
: SvXMLImport(xServiceFactory)
{
}
XMLMetaImportComponent::~XMLMetaImportComponent() throw()
{
}
SvXMLImportContext* XMLMetaImportComponent::CreateContext(
sal_uInt16 nPrefix,
const rtl::OUString& rLocalName,
const uno::Reference<xml::sax::XAttributeList > & xAttrList )
{
if ( (XML_NAMESPACE_OFFICE == nPrefix) &&
IsXMLToken(rLocalName, XML_DOCUMENT_META) )
{
return new SvXMLMetaDocumentContext(*this, nPrefix, rLocalName, xAttrList, xDocInfo);
}
else
{
return SvXMLImport::CreateContext(nPrefix, rLocalName, xAttrList);
}
}
void SAL_CALL XMLMetaImportComponent::setTargetDocument( const uno::Reference< lang::XComponent >& xDoc )
throw(lang::IllegalArgumentException, uno::RuntimeException)
{
xDocInfo = uno::Reference< document::XDocumentInfo >::query( xDoc );
if( !xDocInfo.is() )
throw lang::IllegalArgumentException();
}
uno::Sequence< rtl::OUString > SAL_CALL
XMLMetaImportComponent_getSupportedServiceNames()
throw()
{
const rtl::OUString aServiceName( RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.document.XMLOasisMetaImporter" ) );
const uno::Sequence< rtl::OUString > aSeq( &aServiceName, 1 );
return aSeq;
}
rtl::OUString SAL_CALL XMLMetaImportComponent_getImplementationName() throw()
{
return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "XMLMetaImportComponent" ) );
}
uno::Reference< uno::XInterface > SAL_CALL XMLMetaImportComponent_createInstance(
const uno::Reference< lang::XMultiServiceFactory > & rSMgr)
throw( uno::Exception )
{
// #110680#
// return (cppu::OWeakObject*)new XMLMetaImportComponent;
return (cppu::OWeakObject*)new XMLMetaImportComponent(rSMgr);
}
<commit_msg>INTEGRATION: CWS warnings01 (1.9.34); FILE MERGED 2005/11/16 22:47:12 pl 1.9.34.1: #i55991# removed warnings<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: MetaImportComponent.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: hr $ $Date: 2006-06-19 18:21:29 $
*
* 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 _XMLOFF_METAIMPORTCOMPONENT_HXX
#include "MetaImportComponent.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_XMLMETAI_HXX
#include "xmlmetai.hxx"
#endif
using namespace ::com::sun::star;
using namespace ::xmloff::token;
class SvXMLMetaDocumentContext : public SvXMLImportContext
{
private:
::com::sun::star::uno::Reference<
::com::sun::star::document::XDocumentInfo> xDocInfo;
public:
SvXMLMetaDocumentContext(SvXMLImport& rImport, USHORT nPrfx,
const rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList,
const ::com::sun::star::uno::Reference<
::com::sun::star::document::XDocumentInfo>& rDocInfo);
virtual ~SvXMLMetaDocumentContext();
virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,
const rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList );
virtual void EndElement();
};
SvXMLMetaDocumentContext::SvXMLMetaDocumentContext(SvXMLImport& rImport,
USHORT nPrfx, const rtl::OUString& rLName,
const uno::Reference<xml::sax::XAttributeList>&,
const uno::Reference<document::XDocumentInfo>& rDocInfo) :
SvXMLImportContext( rImport, nPrfx, rLName ),
xDocInfo(rDocInfo)
{
// here are no attributes
}
SvXMLMetaDocumentContext::~SvXMLMetaDocumentContext()
{
}
SvXMLImportContext *SvXMLMetaDocumentContext::CreateChildContext( USHORT nPrefix,
const rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& )
{
if ( (XML_NAMESPACE_OFFICE == nPrefix) &&
IsXMLToken(rLocalName, XML_META) )
{
return new SfxXMLMetaContext(GetImport(), nPrefix, rLocalName, xDocInfo);
}
else
{
return new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
}
}
void SvXMLMetaDocumentContext::EndElement()
{
}
//===========================================================================
// #110680#
XMLMetaImportComponent::XMLMetaImportComponent(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory) throw()
: SvXMLImport(xServiceFactory)
{
}
XMLMetaImportComponent::~XMLMetaImportComponent() throw()
{
}
SvXMLImportContext* XMLMetaImportComponent::CreateContext(
sal_uInt16 nPrefix,
const rtl::OUString& rLocalName,
const uno::Reference<xml::sax::XAttributeList > & xAttrList )
{
if ( (XML_NAMESPACE_OFFICE == nPrefix) &&
IsXMLToken(rLocalName, XML_DOCUMENT_META) )
{
return new SvXMLMetaDocumentContext(*this, nPrefix, rLocalName, xAttrList, xDocInfo);
}
else
{
return SvXMLImport::CreateContext(nPrefix, rLocalName, xAttrList);
}
}
void SAL_CALL XMLMetaImportComponent::setTargetDocument( const uno::Reference< lang::XComponent >& xDoc )
throw(lang::IllegalArgumentException, uno::RuntimeException)
{
xDocInfo = uno::Reference< document::XDocumentInfo >::query( xDoc );
if( !xDocInfo.is() )
throw lang::IllegalArgumentException();
}
uno::Sequence< rtl::OUString > SAL_CALL
XMLMetaImportComponent_getSupportedServiceNames()
throw()
{
const rtl::OUString aServiceName( RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.document.XMLOasisMetaImporter" ) );
const uno::Sequence< rtl::OUString > aSeq( &aServiceName, 1 );
return aSeq;
}
rtl::OUString SAL_CALL XMLMetaImportComponent_getImplementationName() throw()
{
return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "XMLMetaImportComponent" ) );
}
uno::Reference< uno::XInterface > SAL_CALL XMLMetaImportComponent_createInstance(
const uno::Reference< lang::XMultiServiceFactory > & rSMgr)
throw( uno::Exception )
{
// #110680#
// return (cppu::OWeakObject*)new XMLMetaImportComponent;
return (cppu::OWeakObject*)new XMLMetaImportComponent(rSMgr);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: TransGradientStyle.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: cl $ $Date: 2002-09-25 16:19:26 $
*
* 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 _XMLOFF_TRANSGRADIENTSTYLE_HXX
#include "TransGradientStyle.hxx"
#endif
#ifndef _COM_SUN_STAR_AWT_GRADIENT_HPP_
#include <com/sun/star/awt/Gradient.hpp>
#endif
#ifndef _XMLOFF_ATTRLIST_HXX
#include "attrlist.hxx"
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _RTL_USTRING_
#include <rtl/ustring>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _XMLOFF_XMLTKMAP_HXX
#include "xmltkmap.hxx"
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include "xmlexp.hxx"
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include "xmlimp.hxx"
#endif
using namespace ::com::sun::star;
using namespace ::rtl;
using namespace ::xmloff::token;
enum SvXMLTokenMapAttrs
{
XML_TOK_GRADIENT_NAME,
XML_TOK_GRADIENT_STYLE,
XML_TOK_GRADIENT_CX,
XML_TOK_GRADIENT_CY,
XML_TOK_GRADIENT_START,
XML_TOK_GRADIENT_END,
XML_TOK_GRADIENT_ANGLE,
XML_TOK_GRADIENT_BORDER,
XML_TOK_TABSTOP_END=XML_TOK_UNKNOWN
};
static __FAR_DATA SvXMLTokenMapEntry aTrGradientAttrTokenMap[] =
{
{ XML_NAMESPACE_DRAW, XML_NAME, XML_TOK_GRADIENT_NAME },
{ XML_NAMESPACE_DRAW, XML_STYLE, XML_TOK_GRADIENT_STYLE },
{ XML_NAMESPACE_DRAW, XML_CX, XML_TOK_GRADIENT_CX },
{ XML_NAMESPACE_DRAW, XML_CY, XML_TOK_GRADIENT_CY },
{ XML_NAMESPACE_DRAW, XML_START, XML_TOK_GRADIENT_START },
{ XML_NAMESPACE_DRAW, XML_END, XML_TOK_GRADIENT_END },
{ XML_NAMESPACE_DRAW, XML_GRADIENT_ANGLE, XML_TOK_GRADIENT_ANGLE },
{ XML_NAMESPACE_DRAW, XML_GRADIENT_BORDER, XML_TOK_GRADIENT_BORDER },
XML_TOKEN_MAP_END
};
SvXMLEnumMapEntry __READONLY_DATA pXML_GradientStyle_Enum[] =
{
{ XML_GRADIENTSTYLE_LINEAR, awt::GradientStyle_LINEAR },
{ XML_GRADIENTSTYLE_AXIAL, awt::GradientStyle_AXIAL },
{ XML_GRADIENTSTYLE_RADIAL, awt::GradientStyle_RADIAL },
{ XML_GRADIENTSTYLE_ELLIPSOID, awt::GradientStyle_ELLIPTICAL },
{ XML_GRADIENTSTYLE_SQUARE, awt::GradientStyle_SQUARE },
{ XML_GRADIENTSTYLE_RECTANGULAR, awt::GradientStyle_RECT },
{ XML_TOKEN_INVALID, 0 }
};
//-------------------------------------------------------------
// Import
//-------------------------------------------------------------
XMLTransGradientStyleImport::XMLTransGradientStyleImport( SvXMLImport& rImp )
: rImport(rImp)
{
}
XMLTransGradientStyleImport::~XMLTransGradientStyleImport()
{
}
sal_Bool XMLTransGradientStyleImport::importXML(
const uno::Reference< xml::sax::XAttributeList >& xAttrList,
uno::Any& rValue,
OUString& rStrName )
{
sal_Bool bRet = sal_False;
sal_Bool bHasName = sal_False;
sal_Bool bHasStyle = sal_False;
awt::Gradient aGradient;
aGradient.XOffset = 0;
aGradient.YOffset = 0;
aGradient.StartIntensity = 100;
aGradient.EndIntensity = 100;
aGradient.Angle = 0;
aGradient.Border = 0;
SvXMLTokenMap aTokenMap( aTrGradientAttrTokenMap );
SvXMLNamespaceMap& rNamespaceMap = rImport.GetNamespaceMap();
SvXMLUnitConverter& rUnitConverter = rImport.GetMM100UnitConverter();
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
const OUString& rFullAttrName = xAttrList->getNameByIndex( i );
OUString aStrAttrName;
sal_uInt16 nPrefix = rNamespaceMap.GetKeyByAttrName( rFullAttrName, &aStrAttrName );
const OUString& rStrValue = xAttrList->getValueByIndex( i );
sal_Int32 nTmpValue;
switch( aTokenMap.Get( nPrefix, aStrAttrName ) )
{
case XML_TOK_GRADIENT_NAME:
{
rStrName = rStrValue;
bHasName = sal_True;
}
break;
case XML_TOK_GRADIENT_STYLE:
{
sal_uInt16 eValue;
if( rUnitConverter.convertEnum( eValue, rStrValue, pXML_GradientStyle_Enum ) )
{
aGradient.Style = (awt::GradientStyle) eValue;
bHasStyle = sal_True;
}
}
break;
case XML_TOK_GRADIENT_CX:
rUnitConverter.convertPercent( nTmpValue, rStrValue );
aGradient.XOffset = nTmpValue;
break;
case XML_TOK_GRADIENT_CY:
rUnitConverter.convertPercent( nTmpValue, rStrValue );
aGradient.YOffset = nTmpValue;
break;
case XML_TOK_GRADIENT_START:
{
sal_Int32 aStartTransparency;
rUnitConverter.convertPercent( aStartTransparency, rStrValue );
aStartTransparency = ( aStartTransparency * 255 ) / 100;
Color aColor(aStartTransparency, aStartTransparency, aStartTransparency );
aGradient.StartColor = (sal_Int32)( aColor.GetColor() );
}
break;
case XML_TOK_GRADIENT_END:
{
sal_Int32 aEndTransparency;
rUnitConverter.convertPercent( aEndTransparency, rStrValue );
aEndTransparency = ( aEndTransparency * 255 ) / 100;
Color aColor( aEndTransparency, aEndTransparency, aEndTransparency );
aGradient.EndColor = (sal_Int32)( aColor.GetColor() );
}
break;
case XML_TOK_GRADIENT_ANGLE:
{
sal_Int32 nValue;
rUnitConverter.convertNumber( nValue, rStrValue, 0, 360 );
aGradient.Angle = sal_Int16( nValue );
}
break;
case XML_TOK_GRADIENT_BORDER:
rUnitConverter.convertPercent( nTmpValue, rStrValue );
aGradient.Border = nTmpValue;
break;
default:
DBG_WARNING( "Unknown token at import transparency gradient style" )
;
}
}
rValue <<= aGradient;
bRet = bHasName && bHasStyle;
return bRet;
}
//-------------------------------------------------------------
// Export
//-------------------------------------------------------------
#ifndef SVX_LIGHT
XMLTransGradientStyleExport::XMLTransGradientStyleExport( SvXMLExport& rExp )
: rExport(rExp)
{
}
XMLTransGradientStyleExport::~XMLTransGradientStyleExport()
{
}
sal_Bool XMLTransGradientStyleExport::exportXML(
const OUString& rStrName,
const uno::Any& rValue )
{
sal_Bool bRet = sal_False;
awt::Gradient aGradient;
if( rStrName.getLength() )
{
if( rValue >>= aGradient )
{
OUString aStrValue;
OUStringBuffer aOut;
SvXMLUnitConverter& rUnitConverter =
rExport.GetMM100UnitConverter();
// Style
if( !rUnitConverter.convertEnum( aOut, aGradient.Style, pXML_GradientStyle_Enum ) )
{
bRet = sal_False;
}
else
{
// Name
rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_NAME, rStrName );
aStrValue = aOut.makeStringAndClear();
rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_STYLE, aStrValue );
// Center x/y
if( aGradient.Style != awt::GradientStyle_LINEAR &&
aGradient.Style != awt::GradientStyle_AXIAL )
{
rUnitConverter.convertPercent( aOut, aGradient.XOffset );
aStrValue = aOut.makeStringAndClear();
rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_CX, aStrValue );
rUnitConverter.convertPercent( aOut, aGradient.YOffset );
aStrValue = aOut.makeStringAndClear();
rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_CY, aStrValue );
}
Color aColor;
// Transparency start
aColor.SetColor( aGradient.StartColor );
sal_Int32 aStartValue = (sal_Int32)(((aColor.GetRed() + 1) * 100) / 255);
rUnitConverter.convertPercent( aOut, aStartValue );
aStrValue = aOut.makeStringAndClear();
rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_START, aStrValue );
// Transparency end
aColor.SetColor( aGradient.EndColor );
sal_Int32 aEndValue = (sal_Int32)(((aColor.GetRed() + 1) * 100) / 255);
rUnitConverter.convertPercent( aOut, aEndValue );
aStrValue = aOut.makeStringAndClear();
rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_END, aStrValue );
// Angle
if( aGradient.Style != awt::GradientStyle_RADIAL )
{
rUnitConverter.convertNumber( aOut, sal_Int32( aGradient.Angle ) );
aStrValue = aOut.makeStringAndClear();
rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_GRADIENT_ANGLE, aStrValue );
}
// Border
rUnitConverter.convertPercent( aOut, aGradient.Border );
aStrValue = aOut.makeStringAndClear();
rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_GRADIENT_BORDER, aStrValue );
// Do Write
SvXMLElementExport rElem( rExport,
XML_NAMESPACE_DRAW, XML_TRANSPARENCY,
sal_True, sal_False );
}
}
}
return bRet;
}
#endif // #ifndef SVX_LIGHT
<commit_msg>INTEGRATION: CWS oasis (1.10.248); FILE MERGED 2004/05/24 09:16:05 mib 1.10.248.3: - #i20153#: replaced transparency with opacity 2004/05/11 11:11:24 mib 1.10.248.2: - #i20153#: encode/decode style names finished 2004/05/07 11:59:58 mib 1.10.248.1: - #i20153#: encode/decode style names (ooo2oasis missing)<commit_after>/*************************************************************************
*
* $RCSfile: TransGradientStyle.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: rt $ $Date: 2004-07-13 08:21:45 $
*
* 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 _XMLOFF_TRANSGRADIENTSTYLE_HXX
#include "TransGradientStyle.hxx"
#endif
#ifndef _COM_SUN_STAR_AWT_GRADIENT_HPP_
#include <com/sun/star/awt/Gradient.hpp>
#endif
#ifndef _XMLOFF_ATTRLIST_HXX
#include "attrlist.hxx"
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _RTL_USTRING_
#include <rtl/ustring>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _XMLOFF_XMLTKMAP_HXX
#include "xmltkmap.hxx"
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include "xmlexp.hxx"
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include "xmlimp.hxx"
#endif
using namespace ::com::sun::star;
using namespace ::rtl;
using namespace ::xmloff::token;
enum SvXMLTokenMapAttrs
{
XML_TOK_GRADIENT_NAME,
XML_TOK_GRADIENT_DISPLAY_NAME,
XML_TOK_GRADIENT_STYLE,
XML_TOK_GRADIENT_CX,
XML_TOK_GRADIENT_CY,
XML_TOK_GRADIENT_START,
XML_TOK_GRADIENT_END,
XML_TOK_GRADIENT_ANGLE,
XML_TOK_GRADIENT_BORDER,
XML_TOK_TABSTOP_END=XML_TOK_UNKNOWN
};
static __FAR_DATA SvXMLTokenMapEntry aTrGradientAttrTokenMap[] =
{
{ XML_NAMESPACE_DRAW, XML_NAME, XML_TOK_GRADIENT_NAME },
{ XML_NAMESPACE_DRAW, XML_DISPLAY_NAME, XML_TOK_GRADIENT_DISPLAY_NAME },
{ XML_NAMESPACE_DRAW, XML_STYLE, XML_TOK_GRADIENT_STYLE },
{ XML_NAMESPACE_DRAW, XML_CX, XML_TOK_GRADIENT_CX },
{ XML_NAMESPACE_DRAW, XML_CY, XML_TOK_GRADIENT_CY },
{ XML_NAMESPACE_DRAW, XML_START, XML_TOK_GRADIENT_START },
{ XML_NAMESPACE_DRAW, XML_END, XML_TOK_GRADIENT_END },
{ XML_NAMESPACE_DRAW, XML_GRADIENT_ANGLE, XML_TOK_GRADIENT_ANGLE },
{ XML_NAMESPACE_DRAW, XML_GRADIENT_BORDER, XML_TOK_GRADIENT_BORDER },
XML_TOKEN_MAP_END
};
SvXMLEnumMapEntry __READONLY_DATA pXML_GradientStyle_Enum[] =
{
{ XML_GRADIENTSTYLE_LINEAR, awt::GradientStyle_LINEAR },
{ XML_GRADIENTSTYLE_AXIAL, awt::GradientStyle_AXIAL },
{ XML_GRADIENTSTYLE_RADIAL, awt::GradientStyle_RADIAL },
{ XML_GRADIENTSTYLE_ELLIPSOID, awt::GradientStyle_ELLIPTICAL },
{ XML_GRADIENTSTYLE_SQUARE, awt::GradientStyle_SQUARE },
{ XML_GRADIENTSTYLE_RECTANGULAR, awt::GradientStyle_RECT },
{ XML_TOKEN_INVALID, 0 }
};
//-------------------------------------------------------------
// Import
//-------------------------------------------------------------
XMLTransGradientStyleImport::XMLTransGradientStyleImport( SvXMLImport& rImp )
: rImport(rImp)
{
}
XMLTransGradientStyleImport::~XMLTransGradientStyleImport()
{
}
sal_Bool XMLTransGradientStyleImport::importXML(
const uno::Reference< xml::sax::XAttributeList >& xAttrList,
uno::Any& rValue,
OUString& rStrName )
{
sal_Bool bRet = sal_False;
sal_Bool bHasName = sal_False;
sal_Bool bHasStyle = sal_False;
OUString aDisplayName;
awt::Gradient aGradient;
aGradient.XOffset = 0;
aGradient.YOffset = 0;
aGradient.StartIntensity = 100;
aGradient.EndIntensity = 100;
aGradient.Angle = 0;
aGradient.Border = 0;
SvXMLTokenMap aTokenMap( aTrGradientAttrTokenMap );
SvXMLNamespaceMap& rNamespaceMap = rImport.GetNamespaceMap();
SvXMLUnitConverter& rUnitConverter = rImport.GetMM100UnitConverter();
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
const OUString& rFullAttrName = xAttrList->getNameByIndex( i );
OUString aStrAttrName;
sal_uInt16 nPrefix = rNamespaceMap.GetKeyByAttrName( rFullAttrName, &aStrAttrName );
const OUString& rStrValue = xAttrList->getValueByIndex( i );
sal_Int32 nTmpValue;
switch( aTokenMap.Get( nPrefix, aStrAttrName ) )
{
case XML_TOK_GRADIENT_NAME:
{
rStrName = rStrValue;
bHasName = sal_True;
}
break;
case XML_TOK_GRADIENT_DISPLAY_NAME:
{
aDisplayName = rStrValue;
}
break;
case XML_TOK_GRADIENT_STYLE:
{
sal_uInt16 eValue;
if( rUnitConverter.convertEnum( eValue, rStrValue, pXML_GradientStyle_Enum ) )
{
aGradient.Style = (awt::GradientStyle) eValue;
bHasStyle = sal_True;
}
}
break;
case XML_TOK_GRADIENT_CX:
rUnitConverter.convertPercent( nTmpValue, rStrValue );
aGradient.XOffset = nTmpValue;
break;
case XML_TOK_GRADIENT_CY:
rUnitConverter.convertPercent( nTmpValue, rStrValue );
aGradient.YOffset = nTmpValue;
break;
case XML_TOK_GRADIENT_START:
{
sal_Int32 aStartTransparency;
rUnitConverter.convertPercent( aStartTransparency, rStrValue );
aStartTransparency = ( (100 - aStartTransparency) * 255 ) / 100;
Color aColor(aStartTransparency, aStartTransparency, aStartTransparency );
aGradient.StartColor = (sal_Int32)( aColor.GetColor() );
}
break;
case XML_TOK_GRADIENT_END:
{
sal_Int32 aEndTransparency;
rUnitConverter.convertPercent( aEndTransparency, rStrValue );
aEndTransparency = ( (100 - aEndTransparency) * 255 ) / 100;
Color aColor( aEndTransparency, aEndTransparency, aEndTransparency );
aGradient.EndColor = (sal_Int32)( aColor.GetColor() );
}
break;
case XML_TOK_GRADIENT_ANGLE:
{
sal_Int32 nValue;
rUnitConverter.convertNumber( nValue, rStrValue, 0, 360 );
aGradient.Angle = sal_Int16( nValue );
}
break;
case XML_TOK_GRADIENT_BORDER:
rUnitConverter.convertPercent( nTmpValue, rStrValue );
aGradient.Border = nTmpValue;
break;
default:
DBG_WARNING( "Unknown token at import transparency gradient style" )
;
}
}
rValue <<= aGradient;
if( aDisplayName.getLength() )
{
rImport.AddStyleDisplayName( XML_STYLE_FAMILY_SD_GRADIENT_ID, rStrName,
aDisplayName );
rStrName = aDisplayName;
}
bRet = bHasName && bHasStyle;
return bRet;
}
//-------------------------------------------------------------
// Export
//-------------------------------------------------------------
#ifndef SVX_LIGHT
XMLTransGradientStyleExport::XMLTransGradientStyleExport( SvXMLExport& rExp )
: rExport(rExp)
{
}
XMLTransGradientStyleExport::~XMLTransGradientStyleExport()
{
}
sal_Bool XMLTransGradientStyleExport::exportXML(
const OUString& rStrName,
const uno::Any& rValue )
{
sal_Bool bRet = sal_False;
awt::Gradient aGradient;
if( rStrName.getLength() )
{
if( rValue >>= aGradient )
{
OUString aStrValue;
OUStringBuffer aOut;
SvXMLUnitConverter& rUnitConverter =
rExport.GetMM100UnitConverter();
// Style
if( !rUnitConverter.convertEnum( aOut, aGradient.Style, pXML_GradientStyle_Enum ) )
{
bRet = sal_False;
}
else
{
// Name
sal_Bool bEncoded = sal_False;
rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_NAME,
rExport.EncodeStyleName( rStrName,
&bEncoded ) );
if( bEncoded )
rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_DISPLAY_NAME,
rStrName );
aStrValue = aOut.makeStringAndClear();
rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_STYLE, aStrValue );
// Center x/y
if( aGradient.Style != awt::GradientStyle_LINEAR &&
aGradient.Style != awt::GradientStyle_AXIAL )
{
rUnitConverter.convertPercent( aOut, aGradient.XOffset );
aStrValue = aOut.makeStringAndClear();
rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_CX, aStrValue );
rUnitConverter.convertPercent( aOut, aGradient.YOffset );
aStrValue = aOut.makeStringAndClear();
rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_CY, aStrValue );
}
Color aColor;
// Transparency start
aColor.SetColor( aGradient.StartColor );
sal_Int32 aStartValue = 100 - (sal_Int32)(((aColor.GetRed() + 1) * 100) / 255);
rUnitConverter.convertPercent( aOut, aStartValue );
aStrValue = aOut.makeStringAndClear();
rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_START, aStrValue );
// Transparency end
aColor.SetColor( aGradient.EndColor );
sal_Int32 aEndValue = 100 - (sal_Int32)(((aColor.GetRed() + 1) * 100) / 255);
rUnitConverter.convertPercent( aOut, aEndValue );
aStrValue = aOut.makeStringAndClear();
rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_END, aStrValue );
// Angle
if( aGradient.Style != awt::GradientStyle_RADIAL )
{
rUnitConverter.convertNumber( aOut, sal_Int32( aGradient.Angle ) );
aStrValue = aOut.makeStringAndClear();
rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_GRADIENT_ANGLE, aStrValue );
}
// Border
rUnitConverter.convertPercent( aOut, aGradient.Border );
aStrValue = aOut.makeStringAndClear();
rExport.AddAttribute( XML_NAMESPACE_DRAW, XML_GRADIENT_BORDER, aStrValue );
// Do Write
SvXMLElementExport rElem( rExport,
XML_NAMESPACE_DRAW, XML_OPACITY,
sal_True, sal_False );
}
}
}
return bRet;
}
#endif // #ifndef SVX_LIGHT
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: IgnoreTContext.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2005-02-21 15:53:17 $
*
* 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 _XMLOFF_IGNORETCONTEXT_HXX
#define _XMLOFF_IGNORETCONTEXT_HXX
#ifndef _XMLOFF_TRANSFORMERCONTEXT_HXX
#include "TransformerContext.hxx"
#endif
class XMLIgnoreTransformerContext : public XMLTransformerContext
{
sal_Bool m_bIgnoreCharacters;
sal_Bool m_bIgnoreElements;
sal_Bool m_bAllowCharactersRecursive;
sal_Bool m_bRecursiveUse;
public:
TYPEINFO();
// A contexts constructor does anything that is required if an element
// starts. Namespace processing has been done already.
// Note that virtual methods cannot be used inside constructors. Use
// StartElement instead if this is required.
XMLIgnoreTransformerContext( XMLTransformerBase& rTransformer,
const ::rtl::OUString& rQName,
sal_Bool bIgnoreCharacters,
sal_Bool bIgnoreElements );
// A contexts constructor does anything that is required if an element
// starts. Namespace processing has been done already.
// Note that virtual methods cannot be used inside constructors. Use
// StartElement instead if this is required.
XMLIgnoreTransformerContext( XMLTransformerBase& rTransformer,
const ::rtl::OUString& rQName,
sal_Bool bAllowCharactersRecursive );
// A contexts destructor does anything that is required if an element
// ends. By default, nothing is done.
// Note that virtual methods cannot be used inside destructors. Use
// EndElement instead if this is required.
virtual ~XMLIgnoreTransformerContext();
// Create a childs element context. By default, the import's
// CreateContext method is called to create a new default context.
virtual XMLTransformerContext *CreateChildContext( sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const ::rtl::OUString& rQName,
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
// StartElement is called after a context has been constructed and
// before a elements context is parsed. It may be used for actions that
// require virtual methods. The default is to do nothing.
virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
// EndElement is called before a context will be destructed, but
// after a elements context has been parsed. It may be used for actions
// that require virtual methods. The default is to do nothing.
virtual void EndElement();
// This method is called for all characters that are contained in the
// current element. The default is to ignore them.
virtual void Characters( const ::rtl::OUString& rChars );
};
#endif // _XMLOFF_IGNORETCONTEXT_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.126); FILE MERGED 2005/09/05 14:40:24 rt 1.3.126.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: IgnoreTContext.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 15:47:15 $
*
* 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 _XMLOFF_IGNORETCONTEXT_HXX
#define _XMLOFF_IGNORETCONTEXT_HXX
#ifndef _XMLOFF_TRANSFORMERCONTEXT_HXX
#include "TransformerContext.hxx"
#endif
class XMLIgnoreTransformerContext : public XMLTransformerContext
{
sal_Bool m_bIgnoreCharacters;
sal_Bool m_bIgnoreElements;
sal_Bool m_bAllowCharactersRecursive;
sal_Bool m_bRecursiveUse;
public:
TYPEINFO();
// A contexts constructor does anything that is required if an element
// starts. Namespace processing has been done already.
// Note that virtual methods cannot be used inside constructors. Use
// StartElement instead if this is required.
XMLIgnoreTransformerContext( XMLTransformerBase& rTransformer,
const ::rtl::OUString& rQName,
sal_Bool bIgnoreCharacters,
sal_Bool bIgnoreElements );
// A contexts constructor does anything that is required if an element
// starts. Namespace processing has been done already.
// Note that virtual methods cannot be used inside constructors. Use
// StartElement instead if this is required.
XMLIgnoreTransformerContext( XMLTransformerBase& rTransformer,
const ::rtl::OUString& rQName,
sal_Bool bAllowCharactersRecursive );
// A contexts destructor does anything that is required if an element
// ends. By default, nothing is done.
// Note that virtual methods cannot be used inside destructors. Use
// EndElement instead if this is required.
virtual ~XMLIgnoreTransformerContext();
// Create a childs element context. By default, the import's
// CreateContext method is called to create a new default context.
virtual XMLTransformerContext *CreateChildContext( sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const ::rtl::OUString& rQName,
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
// StartElement is called after a context has been constructed and
// before a elements context is parsed. It may be used for actions that
// require virtual methods. The default is to do nothing.
virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
// EndElement is called before a context will be destructed, but
// after a elements context has been parsed. It may be used for actions
// that require virtual methods. The default is to do nothing.
virtual void EndElement();
// This method is called for all characters that are contained in the
// current element. The default is to ignore them.
virtual void Characters( const ::rtl::OUString& rChars );
};
#endif // _XMLOFF_IGNORETCONTEXT_HXX
<|endoftext|> |
<commit_before>#define DEBUG 1
/**
* File : ABC086C_.cpp
* Author : Kazune Takahashi
* Created : 2020/1/31 21:50:13
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(const Mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(const Mint &a) { return *this += -a; }
Mint &operator*=(const Mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(const Mint &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(const Mint &a) const { return Mint(*this) += a; }
Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
bool operator<(const Mint &a) const { return x < a.x; }
bool operator<=(const Mint &a) const { return x <= a.x; }
bool operator>(const Mint &a) const { return x > a.x; }
bool operator>=(const Mint &a) const { return x >= a.x; }
bool operator==(const Mint &a) const { return x == a.x; }
bool operator!=(const Mint &a) const { return !(*this == a); }
const Mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2LL; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1LL; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
int ans{0};
while (x != 0)
{
ans += x & 1;
x >>= 1;
}
return ans;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- main() -----
int main()
{
int N;
cin >> N;
vector<int> t(N + 1), x(N + 1), y(N + 1);
t[0] = x[0] = y[0] = 0;
for (auto i = 1; i <= N; ++i)
{
cin >> t[i] >> x[i] >> y[i];
}
auto dist = [](int X0, int Y0, int X1, int Y1) {
return abs(X0 - X1) + abs(Y0 - Y1);
};
auto ok = [&](int k) {
int T{t[k + 1] - t[k]};
int d{dist(x[k], x[k + 1], y[k], y[k + 1])};
#if DEBUG == 1
cerr << "T = " << T << ", d = " << d << endl;
#endif
return (T >= d && abs(T - d) % 2 == 0);
};
for (auto i = 0; i < N; ++i)
{
if (!ok(i))
{
No();
}
}
Yes();
}
<commit_msg>submit ABC086C_.cpp to 'ABC086C - Traveling' (language-test-202001) [C++ (GCC 9.2.1)]<commit_after>#define DEBUG 1
/**
* File : ABC086C_.cpp
* Author : Kazune Takahashi
* Created : 2020/1/31 21:50:13
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(const Mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(const Mint &a) { return *this += -a; }
Mint &operator*=(const Mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(const Mint &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(const Mint &a) const { return Mint(*this) += a; }
Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
bool operator<(const Mint &a) const { return x < a.x; }
bool operator<=(const Mint &a) const { return x <= a.x; }
bool operator>(const Mint &a) const { return x > a.x; }
bool operator>=(const Mint &a) const { return x >= a.x; }
bool operator==(const Mint &a) const { return x == a.x; }
bool operator!=(const Mint &a) const { return !(*this == a); }
const Mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2LL; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1LL; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
int ans{0};
while (x != 0)
{
ans += x & 1;
x >>= 1;
}
return ans;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- main() -----
int main()
{
int N;
cin >> N;
vector<int> t(N + 1), x(N + 1), y(N + 1);
t[0] = x[0] = y[0] = 0;
for (auto i = 1; i <= N; ++i)
{
cin >> t[i] >> x[i] >> y[i];
}
auto dist = [](int X0, int Y0, int X1, int Y1) {
return abs(X0 - X1) + abs(Y0 - Y1);
};
auto ok = [&](int k) {
int T{t[k + 1] - t[k]};
int d{dist(x[k], y[k], x[k + 1], y[k + 1])};
#if DEBUG == 1
cerr << "T = " << T << ", d = " << d << endl;
#endif
return (T >= d && abs(T - d) % 2 == 0);
};
for (auto i = 0; i < N; ++i)
{
if (!ok(i))
{
No();
}
}
Yes();
}
<|endoftext|> |
<commit_before>// 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.
#ifndef __STOUT_WINDOWS_FS_HPP__
#define __STOUT_WINDOWS_FS_HPP__
#include <string>
#include <stout/bytes.hpp>
#include <stout/error.hpp>
#include <stout/nothing.hpp>
#include <stout/try.hpp>
#include <stout/windows.hpp>
#include <stout/internal/windows/symlink.hpp>
namespace fs {
// Returns the total disk size in bytes.
inline Try<Bytes> size(const std::string& path = "/")
{
Result<std::string> real_path = os::realpath(path);
if (!real_path.isSome()) {
return Error(
"Failed to get realpath for '" + path+ "': " +
(real_path.isError() ? real_path.error() : "No such directory"));
}
ULARGE_INTEGER free_bytes, total_bytes, total_free_bytes;
if (::GetDiskFreeSpaceEx(
real_path.get().c_str(),
&free_bytes,
&total_bytes,
&total_free_bytes) == 0) {
return WindowsError(
"Error invoking 'GetDiskFreeSpaceEx' on '" + path + "'");
}
return Bytes(total_bytes.QuadPart);
}
// Returns relative disk usage of the file system that the given path
// is mounted at.
inline Try<double> usage(const std::string& path = "/")
{
Result<std::string> real_path = os::realpath(path);
if (!real_path.isSome()) {
return Error(
"Failed to get realpath for '" + path + "': " +
(real_path.isError() ? real_path.error() : "No such directory"));
}
ULARGE_INTEGER free_bytes, total_bytes, total_free_bytes;
if (::GetDiskFreeSpaceEx(
real_path.get().c_str(),
&free_bytes,
&total_bytes,
&total_free_bytes) == 0) {
return WindowsError(
"Error invoking 'GetDiskFreeSpaceEx' on '" + path + "'");
}
double used = static_cast<double>(total_bytes.QuadPart - free_bytes.QuadPart);
return used / total_bytes.QuadPart;
}
inline Try<Nothing> symlink(
const std::string& original,
const std::string& link)
{
return internal::windows::create_symbolic_link(original, link);
}
// Returns a list of all files matching the given pattern. This is meant to
// be a lightweight alternative to glob() - the only supported wildcards are
// `?` and `*`, and only when they appear at the tail end of `pattern` (e.g.
// `/root/dir/subdir/*.txt` or `/root/dir/subdir/file?.txt`.
inline Try<std::list<std::string>> list(const std::string& pattern)
{
std::list<std::string> found_files;
WIN32_FIND_DATAW found;
const SharedHandle search_handle(
::FindFirstFileW(wide_stringify(pattern).data(), &found),
::FindClose);
if (search_handle.get() == INVALID_HANDLE_VALUE) {
// For compliance with the POSIX implementation (which uses `::glob`),
// return an empty list instead of an error when the path does not exist.
int error = ::GetLastError();
if (error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND) {
return found_files;
}
return WindowsError(
"'fs::list' failed when searching for files with pattern '" +
pattern + "'");
}
do {
const std::wstring current_file(found.cFileName);
// Ignore `.` and `..` entries.
if (current_file.compare(L".") != 0 && current_file.compare(L"..") != 0) {
found_files.push_back(stringify(current_file));
}
} while (::FindNextFileW(search_handle.get(), &found));
const DWORD error = ::GetLastError();
if (error != ERROR_NO_MORE_FILES) {
return WindowsError(
error,
"'fs::list': 'FindNextFile' failed when searching for files with "
"'pattern '" + pattern + "'");
}
return found_files;
}
} // namespace fs {
#endif // __STOUT_WINDOWS_FS_HPP__
<commit_msg>Windows: Updated `fs::usage()` to support long paths.<commit_after>// 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.
#ifndef __STOUT_WINDOWS_FS_HPP__
#define __STOUT_WINDOWS_FS_HPP__
#include <string>
#include <stout/bytes.hpp>
#include <stout/error.hpp>
#include <stout/nothing.hpp>
#include <stout/try.hpp>
#include <stout/windows.hpp>
#include <stout/internal/windows/longpath.hpp>
#include <stout/internal/windows/symlink.hpp>
namespace fs {
// Returns the total disk size in bytes.
inline Try<Bytes> size(const std::string& path = "/")
{
Result<std::string> real_path = os::realpath(path);
if (!real_path.isSome()) {
return Error(
"Failed to get realpath for '" + path+ "': " +
(real_path.isError() ? real_path.error() : "No such directory"));
}
ULARGE_INTEGER free_bytes, total_bytes, total_free_bytes;
if (::GetDiskFreeSpaceExW(
internal::windows::longpath(real_path.get()).data(),
&free_bytes,
&total_bytes,
&total_free_bytes) == 0) {
return WindowsError(
"Error invoking 'GetDiskFreeSpaceEx' on '" + path + "'");
}
return Bytes(total_bytes.QuadPart);
}
// Returns relative disk usage of the file system that the given path
// is mounted at.
inline Try<double> usage(const std::string& path = "/")
{
Result<std::string> real_path = os::realpath(path);
if (!real_path.isSome()) {
return Error(
"Failed to get realpath for '" + path + "': " +
(real_path.isError() ? real_path.error() : "No such directory"));
}
ULARGE_INTEGER free_bytes, total_bytes, total_free_bytes;
if (::GetDiskFreeSpaceExW(
internal::windows::longpath(real_path.get()).data(),
&free_bytes,
&total_bytes,
&total_free_bytes) == 0) {
return WindowsError(
"Error invoking 'GetDiskFreeSpaceEx' on '" + path + "'");
}
double used = static_cast<double>(total_bytes.QuadPart - free_bytes.QuadPart);
return used / total_bytes.QuadPart;
}
inline Try<Nothing> symlink(
const std::string& original,
const std::string& link)
{
return internal::windows::create_symbolic_link(original, link);
}
// Returns a list of all files matching the given pattern. This is meant to
// be a lightweight alternative to glob() - the only supported wildcards are
// `?` and `*`, and only when they appear at the tail end of `pattern` (e.g.
// `/root/dir/subdir/*.txt` or `/root/dir/subdir/file?.txt`.
inline Try<std::list<std::string>> list(const std::string& pattern)
{
std::list<std::string> found_files;
WIN32_FIND_DATAW found;
const SharedHandle search_handle(
::FindFirstFileW(wide_stringify(pattern).data(), &found),
::FindClose);
if (search_handle.get() == INVALID_HANDLE_VALUE) {
// For compliance with the POSIX implementation (which uses `::glob`),
// return an empty list instead of an error when the path does not exist.
int error = ::GetLastError();
if (error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND) {
return found_files;
}
return WindowsError(
"'fs::list' failed when searching for files with pattern '" +
pattern + "'");
}
do {
const std::wstring current_file(found.cFileName);
// Ignore `.` and `..` entries.
if (current_file.compare(L".") != 0 && current_file.compare(L"..") != 0) {
found_files.push_back(stringify(current_file));
}
} while (::FindNextFileW(search_handle.get(), &found));
const DWORD error = ::GetLastError();
if (error != ERROR_NO_MORE_FILES) {
return WindowsError(
error,
"'fs::list': 'FindNextFile' failed when searching for files with "
"'pattern '" + pattern + "'");
}
return found_files;
}
} // namespace fs {
#endif // __STOUT_WINDOWS_FS_HPP__
<|endoftext|> |
<commit_before><commit_msg>Digital Monsters?<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (c) 2003-2005 The Regents of The University of Michigan
* 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 copyright holders 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.
*
* Authors: Steve Reinhardt
* Gabe Black
* Kevin Lim
*/
#include "arch/alpha/miscregfile.hh"
#include "base/misc.hh"
namespace AlphaISA
{
void
MiscRegFile::serialize(std::ostream &os)
{
SERIALIZE_SCALAR(fpcr);
SERIALIZE_SCALAR(uniq);
SERIALIZE_SCALAR(lock_flag);
SERIALIZE_SCALAR(lock_addr);
#if FULL_SYSTEM
SERIALIZE_ARRAY(ipr, NumInternalProcRegs);
#endif
}
void
MiscRegFile::unserialize(Checkpoint *cp, const std::string §ion)
{
UNSERIALIZE_SCALAR(fpcr);
UNSERIALIZE_SCALAR(uniq);
UNSERIALIZE_SCALAR(lock_flag);
UNSERIALIZE_SCALAR(lock_addr);
#if FULL_SYSTEM
UNSERIALIZE_ARRAY(ipr, NumInternalProcRegs);
#endif
}
MiscReg
MiscRegFile::readReg(int misc_reg)
{
switch(misc_reg) {
case MISCREG_FPCR:
return fpcr;
case MISCREG_UNIQ:
return uniq;
case MISCREG_LOCKFLAG:
return lock_flag;
case MISCREG_LOCKADDR:
return lock_addr;
case MISCREG_INTR:
return intr_flag;
#if FULL_SYSTEM
default:
assert(misc_reg < NumInternalProcRegs);
return ipr[misc_reg];
#else
default:
panic("Attempt to read an invalid misc register!");
return 0;
#endif
}
}
MiscReg
MiscRegFile::readRegWithEffect(int misc_reg, ThreadContext *tc)
{
#if FULL_SYSTEM
return readIpr(misc_reg, tc);
#else
panic("No faulting misc regs in SE mode!");
return 0;
#endif
}
void
MiscRegFile::setReg(int misc_reg, const MiscReg &val)
{
switch(misc_reg) {
case MISCREG_FPCR:
fpcr = val;
return;
case MISCREG_UNIQ:
uniq = val;
return;
case MISCREG_LOCKFLAG:
lock_flag = val;
return;
case MISCREG_LOCKADDR:
lock_addr = val;
return;
case MISCREG_INTR:
intr_flag = val;
return;
#if FULL_SYSTEM
default:
assert(misc_reg < NumInternalProcRegs);
ipr[misc_reg] = val;
return;
#else
default:
panic("Attempt to write to an invalid misc register!");
#endif
}
}
void
MiscRegFile::setRegWithEffect(int misc_reg, const MiscReg &val,
ThreadContext *tc)
{
#if FULL_SYSTEM
switch(misc_reg) {
case MISCREG_FPCR:
fpcr = val;
return;
case MISCREG_UNIQ:
uniq = val;
return;
case MISCREG_LOCKFLAG:
lock_flag = val;
return;
case MISCREG_LOCKADDR:
lock_addr = val;
return;
case MISCREG_INTR:
intr_flag = val;
return;
default:
return setIpr(misc_reg, val, tc);
}
#else
//panic("No registers with side effects in SE mode!");
return;
#endif
}
}
<commit_msg>Make setRegWithEffect do something in SE mode.<commit_after>/*
* Copyright (c) 2003-2005 The Regents of The University of Michigan
* 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 copyright holders 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.
*
* Authors: Steve Reinhardt
* Gabe Black
* Kevin Lim
*/
#include "arch/alpha/miscregfile.hh"
#include "base/misc.hh"
namespace AlphaISA
{
void
MiscRegFile::serialize(std::ostream &os)
{
SERIALIZE_SCALAR(fpcr);
SERIALIZE_SCALAR(uniq);
SERIALIZE_SCALAR(lock_flag);
SERIALIZE_SCALAR(lock_addr);
#if FULL_SYSTEM
SERIALIZE_ARRAY(ipr, NumInternalProcRegs);
#endif
}
void
MiscRegFile::unserialize(Checkpoint *cp, const std::string §ion)
{
UNSERIALIZE_SCALAR(fpcr);
UNSERIALIZE_SCALAR(uniq);
UNSERIALIZE_SCALAR(lock_flag);
UNSERIALIZE_SCALAR(lock_addr);
#if FULL_SYSTEM
UNSERIALIZE_ARRAY(ipr, NumInternalProcRegs);
#endif
}
MiscReg
MiscRegFile::readReg(int misc_reg)
{
switch(misc_reg) {
case MISCREG_FPCR:
return fpcr;
case MISCREG_UNIQ:
return uniq;
case MISCREG_LOCKFLAG:
return lock_flag;
case MISCREG_LOCKADDR:
return lock_addr;
case MISCREG_INTR:
return intr_flag;
#if FULL_SYSTEM
default:
assert(misc_reg < NumInternalProcRegs);
return ipr[misc_reg];
#else
default:
panic("Attempt to read an invalid misc register!");
return 0;
#endif
}
}
MiscReg
MiscRegFile::readRegWithEffect(int misc_reg, ThreadContext *tc)
{
#if FULL_SYSTEM
return readIpr(misc_reg, tc);
#else
panic("No faulting misc regs in SE mode!");
return 0;
#endif
}
void
MiscRegFile::setReg(int misc_reg, const MiscReg &val)
{
switch(misc_reg) {
case MISCREG_FPCR:
fpcr = val;
return;
case MISCREG_UNIQ:
uniq = val;
return;
case MISCREG_LOCKFLAG:
lock_flag = val;
return;
case MISCREG_LOCKADDR:
lock_addr = val;
return;
case MISCREG_INTR:
intr_flag = val;
return;
#if FULL_SYSTEM
default:
assert(misc_reg < NumInternalProcRegs);
ipr[misc_reg] = val;
return;
#else
default:
panic("Attempt to write to an invalid misc register!");
#endif
}
}
void
MiscRegFile::setRegWithEffect(int misc_reg, const MiscReg &val,
ThreadContext *tc)
{
switch(misc_reg) {
case MISCREG_FPCR:
fpcr = val;
return;
case MISCREG_UNIQ:
uniq = val;
return;
case MISCREG_LOCKFLAG:
lock_flag = val;
return;
case MISCREG_LOCKADDR:
lock_addr = val;
return;
case MISCREG_INTR:
intr_flag = val;
return;
default:
#if FULL_SYSTEM
setIpr(misc_reg, val, tc);
#else
panic("No registers with side effects in SE mode!");
#endif
return;
}
}
}
<|endoftext|> |
<commit_before>/* This file exists to provide some stat monitors for process statistics and the like. */
#include <vector>
#include <string.h>
#include <stdlib.h>
#include <sys/syscall.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sstream>
#include <iomanip>
#include <stdarg.h>
#include "arch/io/io_utils.hpp"
#include "perfmon.hpp"
#include "logger.hpp"
#include "utils.hpp"
#include "thread_local.hpp"
/* Class to represent and parse the contents of /proc/[pid]/stat */
struct proc_pid_stat_exc_t : public std::exception {
explicit proc_pid_stat_exc_t(const char *format, ...) __attribute__ ((format (printf, 2, 3))) {
char buffer[2000];
va_list l;
va_start(l, format);
vsnprintf(buffer, sizeof(buffer), format, l);
va_end(l);
msg = buffer;
}
std::string msg;
const char *what() const throw () {
return msg.c_str();
}
~proc_pid_stat_exc_t() throw () { }
};
struct proc_pid_stat_t {
int pid;
char name[500];
char state;
int ppid, pgrp, session, tty_nr, tpgid;
unsigned int flags;
unsigned long int minflt, cminflt, majflt, cmajflt, utime, stime;
long int cutime, cstime, priority, nice, num_threads, itrealvalue;
long long unsigned int starttime;
long unsigned int vsize;
long int rss;
long unsigned int rsslim, startcode, endcode, startstack, kstkesp, kstkeip, signal, blocked,
sigignore, sigcatch, wchan, nswap, cnswap;
int exit_signal, processor;
unsigned int rt_priority, policy;
long long unsigned int delayacct_blkio_ticks;
long unsigned int guest_time;
long int cguest_time;
static proc_pid_stat_t for_pid(pid_t pid) {
char path[100];
snprintf(path, sizeof(path), "/proc/%d/stat", pid);
proc_pid_stat_t stat;
stat.read_from_file(path);
return stat;
}
static proc_pid_stat_t for_pid_and_tid(pid_t pid, pid_t tid) {
char path[100];
snprintf(path, sizeof(path), "/proc/%d/task/%d/stat", pid, tid);
proc_pid_stat_t stat;
stat.read_from_file(path);
return stat;
}
private:
void read_from_file(char * path) {
scoped_fd_t stat_file(open(path, O_RDONLY));
if (stat_file.get() == INVALID_FD) {
throw proc_pid_stat_exc_t("Could not open '%s': %s (errno = %d)", path, strerror(errno), errno);
}
char buffer[1000];
int res = ::read(stat_file.get(), buffer, sizeof(buffer));
if (res <= 0) {
throw proc_pid_stat_exc_t("Could not read '%s': %s (errno = %d)", path, strerror(errno), errno);
}
buffer[res] = '\0';
const int items_to_parse = 44;
int res2 = sscanf(buffer, "%d %s %c %d %d %d %d %d %u %lu %lu %lu %lu %lu %lu %ld %ld "
"%ld %ld %ld %ld %llu %lu %ld %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %d "
"%d %u %u %llu %lu %ld",
&pid, name, &state, &ppid, &pgrp, &session, &tty_nr, &tpgid,
&flags, &minflt, &cminflt, &majflt, &cmajflt, &utime, &stime,
&cutime, &cstime, &priority, &nice, &num_threads, &itrealvalue,
&starttime, &vsize, &rss, &rsslim, &startcode, &endcode, &startstack,
&kstkesp, &kstkeip, &signal, &blocked, &sigignore, &sigcatch, &wchan,
&nswap, &cnswap, &exit_signal, &processor, &rt_priority, &policy,
&delayacct_blkio_ticks, &guest_time, &cguest_time);
if (res2 != items_to_parse) {
throw proc_pid_stat_exc_t("Could not parse '%s': expected to parse %d items, parsed "
"%d. Buffer contents: %s", path, items_to_parse, res2, buffer);
}
}
};
/* perfmon_system_t is used to monitor system stats that do not need to be polled. */
struct perfmon_system_t :
public perfmon_t
{
bool have_reported_error;
perfmon_system_t() : perfmon_t(false), have_reported_error(false) { }
void *begin_stats() {
return NULL;
}
void visit_stats(void *) {
}
void end_stats(void *, perfmon_stats_t *dest) {
put_timestamp(dest);
(*dest)["version"] = std::string(RETHINKDB_VERSION);
(*dest)["pid"] = strprintf("%d", getpid());
proc_pid_stat_t pid_stat;
try {
pid_stat = proc_pid_stat_t::for_pid(getpid());
} catch (proc_pid_stat_exc_t e) {
if (!have_reported_error) {
logWRN("Error in reporting system stats: %s (Further errors like this will "
"be suppressed.)\n", e.what());
have_reported_error = true;
}
return;
}
(*dest)["memory_virtual[bytes]"] = strprintf("%lu", pid_stat.vsize);
(*dest)["memory_real[bytes]"] = strprintf("%ld", pid_stat.rss * sysconf(_SC_PAGESIZE));
}
void put_timestamp(perfmon_stats_t *dest) {
timespec uptime = get_uptime();
std::stringstream uptime_str;
uptime_str << uptime.tv_sec << '.' << std::setfill('0') << std::setw(6) << uptime.tv_nsec / 1000;
(*dest)["uptime"] = uptime_str.str();
(*dest)["timestamp"] = format_precise_time(get_absolute_time(uptime));
}
} pm_system;
/* Some of the stats need to be polled periodically. Call this function periodically on each
thread to ensure that stats are up to date. It takes a void* so that it can be called as a timer
callback. */
perfmon_sampler_t
pm_cpu_user("cpu_user", secs_to_ticks(5)),
pm_cpu_system("cpu_system", secs_to_ticks(5)),
pm_cpu_combined("cpu_combined", secs_to_ticks(5)),
pm_memory_faults("memory_faults", secs_to_ticks(5));
TLS(proc_pid_stat_t, last_stats);
TLS_with_init(ticks_t, last_ticks, 0);
TLS_with_init(bool, have_reported_stats_error, false);
void poll_system_stats(void *) {
proc_pid_stat_t current_stats;
try {
current_stats = proc_pid_stat_t::for_pid_and_tid(getpid(), syscall(SYS_gettid));
} catch (proc_pid_stat_exc_t e) {
if (!TLS_get_have_reported_stats_error()) {
logWRN("Error in reporting per-thread stats: %s (Further errors like this will "
"be suppressed.)\n", e.what());
TLS_set_have_reported_stats_error(true);
}
}
ticks_t current_ticks = get_ticks();
if (TLS_get_last_ticks() == 0) {
TLS_set_last_stats(current_stats);
TLS_set_last_ticks(current_ticks);
} else if (current_ticks > TLS_get_last_ticks() + secs_to_ticks(1)) {
double realtime_elapsed = ticks_to_secs(current_ticks - TLS_get_last_ticks()) * sysconf(_SC_CLK_TCK);
pm_cpu_user.record((current_stats.utime - TLS_get_last_stats().utime) / realtime_elapsed);
pm_cpu_system.record((current_stats.stime - TLS_get_last_stats().stime) / realtime_elapsed);
pm_cpu_combined.record(
(current_stats.utime - TLS_get_last_stats().utime +
current_stats.stime - TLS_get_last_stats().stime) /
realtime_elapsed);
pm_memory_faults.record((current_stats.majflt - TLS_get_last_stats().majflt) / realtime_elapsed);
TLS_set_last_stats(current_stats);
TLS_set_last_ticks(current_ticks);
}
}
<commit_msg>Made perfmon_system.cc avoid the use of long.<commit_after>/* This file exists to provide some stat monitors for process statistics and the like. */
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <vector>
#include <string.h>
#include <stdlib.h>
#include <sys/syscall.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sstream>
#include <iomanip>
#include <stdarg.h>
#include "arch/io/io_utils.hpp"
#include "perfmon.hpp"
#include "logger.hpp"
#include "utils.hpp"
#include "thread_local.hpp"
/* Class to represent and parse the contents of /proc/[pid]/stat */
struct proc_pid_stat_exc_t : public std::exception {
explicit proc_pid_stat_exc_t(const char *format, ...) __attribute__ ((format (printf, 2, 3))) {
char buffer[2000];
va_list l;
va_start(l, format);
vsnprintf(buffer, sizeof(buffer), format, l);
va_end(l);
msg = buffer;
}
std::string msg;
const char *what() const throw () {
return msg.c_str();
}
~proc_pid_stat_exc_t() throw () { }
};
struct proc_pid_stat_t {
int pid;
char name[500];
char state;
int ppid, pgrp, session, tty_nr, tpgid;
unsigned int flags;
uint64_t minflt, cminflt, majflt, cmajflt, utime, stime;
int64_t cutime, cstime, priority, nice, num_threads, itrealvalue;
uint64_t starttime;
uint64_t vsize;
int64_t rss;
uint64_t rsslim, startcode, endcode, startstack, kstkesp, kstkeip, signal, blocked,
sigignore, sigcatch, wchan, nswap, cnswap;
int exit_signal, processor;
unsigned int rt_priority, policy;
uint64_t delayacct_blkio_ticks;
uint64_t guest_time;
int64_t cguest_time;
static proc_pid_stat_t for_pid(pid_t pid) {
char path[100];
snprintf(path, sizeof(path), "/proc/%d/stat", pid);
proc_pid_stat_t stat;
stat.read_from_file(path);
return stat;
}
static proc_pid_stat_t for_pid_and_tid(pid_t pid, pid_t tid) {
char path[100];
snprintf(path, sizeof(path), "/proc/%d/task/%d/stat", pid, tid);
proc_pid_stat_t stat;
stat.read_from_file(path);
return stat;
}
private:
void read_from_file(char * path) {
scoped_fd_t stat_file(open(path, O_RDONLY));
if (stat_file.get() == INVALID_FD) {
throw proc_pid_stat_exc_t("Could not open '%s': %s (errno = %d)", path, strerror(errno), errno);
}
char buffer[1000];
int res = ::read(stat_file.get(), buffer, sizeof(buffer));
if (res <= 0) {
throw proc_pid_stat_exc_t("Could not read '%s': %s (errno = %d)", path, strerror(errno), errno);
}
buffer[res] = '\0';
const int items_to_parse = 44;
int res2 = sscanf(buffer, "%d %s %c %d %d %d %d %d %u"
" %" SCNu64 " %" SCNu64 " %" SCNu64 " %" SCNu64 " %" SCNu64 " %" SCNu64
" %" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64 " %" SCNd64
" %" SCNu64 " %" SCNu64 " %" SCNd64
" %" SCNu64 " %" SCNu64 " %" SCNu64 " %" SCNu64 " %" SCNu64 " %" SCNu64 " %" SCNu64 " %" SCNu64
" %" SCNu64 " %" SCNu64 " %" SCNu64 " %" SCNu64 " %" SCNu64
" %d %d"
" %u %u"
" %" SCNu64
" %" SCNu64
" %" SCNd64,
&pid,
name,
&state,
&ppid, &pgrp, &session, &tty_nr, &tpgid,
&flags,
&minflt, &cminflt, &majflt, &cmajflt, &utime, &stime,
&cutime, &cstime, &priority, &nice, &num_threads, &itrealvalue,
&starttime,
&vsize,
&rss,
&rsslim, &startcode, &endcode, &startstack, &kstkesp, &kstkeip, &signal, &blocked,
&sigignore, &sigcatch, &wchan, &nswap, &cnswap,
&exit_signal, &processor,
&rt_priority, &policy,
&delayacct_blkio_ticks,
&guest_time,
&cguest_time);
if (res2 != items_to_parse) {
throw proc_pid_stat_exc_t("Could not parse '%s': expected to parse %d items, parsed "
"%d. Buffer contents: %s", path, items_to_parse, res2, buffer);
}
}
};
/* perfmon_system_t is used to monitor system stats that do not need to be polled. */
struct perfmon_system_t :
public perfmon_t
{
bool have_reported_error;
perfmon_system_t() : perfmon_t(false), have_reported_error(false) { }
void *begin_stats() {
return NULL;
}
void visit_stats(void *) {
}
void end_stats(void *, perfmon_stats_t *dest) {
put_timestamp(dest);
(*dest)["version"] = std::string(RETHINKDB_VERSION);
(*dest)["pid"] = strprintf("%d", getpid());
proc_pid_stat_t pid_stat;
try {
pid_stat = proc_pid_stat_t::for_pid(getpid());
} catch (proc_pid_stat_exc_t e) {
if (!have_reported_error) {
logWRN("Error in reporting system stats: %s (Further errors like this will "
"be suppressed.)\n", e.what());
have_reported_error = true;
}
return;
}
(*dest)["memory_virtual[bytes]"] = strprintf("%lu", pid_stat.vsize);
(*dest)["memory_real[bytes]"] = strprintf("%ld", pid_stat.rss * sysconf(_SC_PAGESIZE));
}
void put_timestamp(perfmon_stats_t *dest) {
timespec uptime = get_uptime();
std::stringstream uptime_str;
uptime_str << uptime.tv_sec << '.' << std::setfill('0') << std::setw(6) << uptime.tv_nsec / 1000;
(*dest)["uptime"] = uptime_str.str();
(*dest)["timestamp"] = format_precise_time(get_absolute_time(uptime));
}
} pm_system;
/* Some of the stats need to be polled periodically. Call this function periodically on each
thread to ensure that stats are up to date. It takes a void* so that it can be called as a timer
callback. */
perfmon_sampler_t
pm_cpu_user("cpu_user", secs_to_ticks(5)),
pm_cpu_system("cpu_system", secs_to_ticks(5)),
pm_cpu_combined("cpu_combined", secs_to_ticks(5)),
pm_memory_faults("memory_faults", secs_to_ticks(5));
TLS(proc_pid_stat_t, last_stats);
TLS_with_init(ticks_t, last_ticks, 0);
TLS_with_init(bool, have_reported_stats_error, false);
void poll_system_stats(void *) {
proc_pid_stat_t current_stats;
try {
current_stats = proc_pid_stat_t::for_pid_and_tid(getpid(), syscall(SYS_gettid));
} catch (proc_pid_stat_exc_t e) {
if (!TLS_get_have_reported_stats_error()) {
logWRN("Error in reporting per-thread stats: %s (Further errors like this will "
"be suppressed.)\n", e.what());
TLS_set_have_reported_stats_error(true);
}
}
ticks_t current_ticks = get_ticks();
if (TLS_get_last_ticks() == 0) {
TLS_set_last_stats(current_stats);
TLS_set_last_ticks(current_ticks);
} else if (current_ticks > TLS_get_last_ticks() + secs_to_ticks(1)) {
double realtime_elapsed = ticks_to_secs(current_ticks - TLS_get_last_ticks()) * sysconf(_SC_CLK_TCK);
pm_cpu_user.record((current_stats.utime - TLS_get_last_stats().utime) / realtime_elapsed);
pm_cpu_system.record((current_stats.stime - TLS_get_last_stats().stime) / realtime_elapsed);
pm_cpu_combined.record(
(current_stats.utime - TLS_get_last_stats().utime +
current_stats.stime - TLS_get_last_stats().stime) /
realtime_elapsed);
pm_memory_faults.record((current_stats.majflt - TLS_get_last_stats().majflt) / realtime_elapsed);
TLS_set_last_stats(current_stats);
TLS_set_last_ticks(current_ticks);
}
}
<|endoftext|> |
<commit_before>#include <ros/ros.h>
#include <string>
#include "EscortRobot.h"
#include "elderly_care_simulation/EventTrigger.h"
#include "elderly_care_simulation/FindPath.h"
#include "elderly_care_simulation/PerformTask.h"
#include "EventTriggerUtility.h"
#include "nav_msgs/Odometry.h"
#include "StaticPoiConstants.h"
#include "PerformTaskConstants.h"
#include "Robot.h"
int main(int argc, char **argv) {
geometry_msgs::Point base;
base.x = FEEDER_BASE_X;
base.y = FEEDER_BASE_Y;
geometry_msgs::Point table;
table.x = ADJACENT_TABLE_X;
table.y = ADJACENT_TABLE_Y;
EscortRobot feeder(EVENT_TRIGGER_EVENT_TYPE_EAT, base, table);
const std::string rid = "robot_10";
ros::init(argc, argv, "Feeding_Robot");
// Node handle
ros::NodeHandle chefNodeHandle;
// Will publish geometry_msgs::Twist messages to the cmd_vel topic
feeder.robotNodeStagePub = chefNodeHandle.advertise<geometry_msgs::Twist>(rid + "/cmd_vel", 1000);
feeder.eventTriggerPub = chefNodeHandle.advertise<elderly_care_simulation::EventTrigger>("event_trigger", 1000, true);
// Necessary subscribers
feeder.stageOdoSub = chefNodeHandle.subscribe<nav_msgs::Odometry>(rid + "/base_pose_ground_truth", 1000, &Robot::stage0domCallback, dynamic_cast<Robot*>( &feeder ));
feeder.eventTriggerSub = chefNodeHandle.subscribe<elderly_care_simulation::EventTrigger>("event_trigger", 1000, &EscortRobot::eventTriggered, &feeder);
feeder.residentLocationSub = chefNodeHandle.subscribe<nav_msgs::Odometry>("robot_0/base_pose_ground_truth", 1000, &EscortRobot::residentLocationCallback, &feeder);
// Service used to find paths
feeder.pathFinderService = chefNodeHandle.serviceClient<elderly_care_simulation::FindPath>("find_path");
// Service to perform tasks on the resident
feeder.performTaskClient = chefNodeHandle.serviceClient<elderly_care_simulation::PerformTask>("perform_task");
return feeder.execute();
}<commit_msg>Added documentation to FeedingRobot and renamed variables to be more descriptive. [#54]<commit_after>#include <ros/ros.h>
#include <string>
#include "EscortRobot.h"
#include "elderly_care_simulation/EventTrigger.h"
#include "elderly_care_simulation/FindPath.h"
#include "elderly_care_simulation/PerformTask.h"
#include "EventTriggerUtility.h"
#include "nav_msgs/Odometry.h"
#include "StaticPoiConstants.h"
#include "PerformTaskConstants.h"
#include "Robot.h"
/**
* Escort Robot instantiation that will take the resident to the dining area and feed them food.
*/
int main(int argc, char **argv) {
geometry_msgs::Point base;
base.x = FEEDER_BASE_X;
base.y = FEEDER_BASE_Y;
geometry_msgs::Point table;
table.x = ADJACENT_TABLE_X;
table.y = ADJACENT_TABLE_Y;
EscortRobot feeder(EVENT_TRIGGER_EVENT_TYPE_EAT, base, table);
const std::string rid = "robot_10";
ros::init(argc, argv, "Feeding_Robot");
// Node handle
ros::NodeHandle codeHandle;
// Will publish geometry_msgs::Twist messages to the cmd_vel topic
feeder.robotNodeStagePub = codeHandle.advertise<geometry_msgs::Twist>(rid + "/cmd_vel", 1000);
feeder.eventTriggerPub = codeHandle.advertise<elderly_care_simulation::EventTrigger>("event_trigger", 1000, true);
// Necessary subscribers
feeder.stageOdoSub = codeHandle.subscribe<nav_msgs::Odometry>(rid + "/base_pose_ground_truth", 1000, &Robot::stage0domCallback, dynamic_cast<Robot*>( &feeder ));
feeder.eventTriggerSub = codeHandle.subscribe<elderly_care_simulation::EventTrigger>("event_trigger", 1000, &EscortRobot::eventTriggered, &feeder);
feeder.residentLocationSub = codeHandle.subscribe<nav_msgs::Odometry>("robot_0/base_pose_ground_truth", 1000, &EscortRobot::residentLocationCallback, &feeder);
// Service used to find paths
feeder.pathFinderService = codeHandle.serviceClient<elderly_care_simulation::FindPath>("find_path");
// Service to perform tasks on the resident
feeder.performTaskClient = codeHandle.serviceClient<elderly_care_simulation::PerformTask>("perform_task");
return feeder.execute();
}<|endoftext|> |
<commit_before>/*
* Copyright 2008, 2009 Google Inc.
* Copyright 2007 Nintendo Co., Ltd.
*
* 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 <sys/stat.h>
#include <sys/types.h>
#include <set>
#include "java.h"
namespace
{
FILE* createFile(const std::string package, const Node* node)
{
std::string filename = package;
size_t pos = 0;
for (;;)
{
pos = filename.find('.', pos);
if (pos == std::string::npos)
{
break;
}
filename[pos] = '/';
}
filename += "/" + node->getName() + ".java";
std::string dir;
std::string path(filename);
for (;;)
{
size_t slash = path.find("/");
if (slash == std::string::npos)
{
break;
}
dir += path.substr(0, slash);
path.erase(0, slash + 1);
mkdir(dir.c_str(), 0777);
dir += '/';
}
printf("# %s in %s\n", node->getName().c_str(), filename.c_str());
return fopen(filename.c_str(), "w");
}
} // namespace
class JavaInterface : public Java
{
// TODO: Move to Java
void visitInterfaceElement(const Interface* interface, Node* element)
{
if (dynamic_cast<Interface*>(element))
{
// Do not process Constructor.
return;
}
optionalStage = 0;
do
{
optionalCount = 0;
element->accept(this);
++optionalStage;
} while (optionalStage <= optionalCount);
}
public:
JavaInterface(const char* source, FILE* file, const char* indent = "es") :
Java(source, file, indent)
{
}
virtual void at(const ExceptDcl* node)
{
writetab();
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
write("public class %s extends RuntimeException {\n", node->getName().c_str());
// TODO(Shiki): Need a constructor.
printChildren(node);
writeln("}");
}
virtual void at(const Interface* node)
{
if (!currentNode)
{
currentNode = node->getParent();
}
assert(!(node->getAttr() & Interface::Supplemental) && !node->isLeaf());
writetab();
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
std::string name = node->getQualifiedName();
name = getInterfaceName(name);
write("public interface %s", name.substr(name.rfind(':') + 1).c_str());
if (node->getExtends())
{
const char* separator = " extends ";
for (NodeList::iterator i = node->getExtends()->begin();
i != node->getExtends()->end();
++i)
{
if ((*i)->getName() == Node::getBaseObjectName())
{
// Do not extend from 'Object'.
continue;
}
write(separator);
separator = ", ";
(*i)->accept(this);
}
}
write(" {\n");
for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
{
visitInterfaceElement(node, *i);
}
// Expand mixins
std::list<const Interface*> interfaceList;
node->collectMixins(&interfaceList, node);
for (std::list<const Interface*>::const_iterator i = interfaceList.begin();
i != interfaceList.end();
++i)
{
if (*i == node)
{
continue;
}
writeln("// %s", (*i)->getName().c_str());
const Node* saved = currentNode;
for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j)
{
currentNode = *i;
visitInterfaceElement(*i, *j);
}
currentNode = saved;
}
writeln("}");
}
virtual void at(const BinaryExpr* node)
{
node->getLeft()->accept(this);
write(" %s ", node->getName().c_str());
node->getRight()->accept(this);
}
virtual void at(const UnaryExpr* node)
{
write("%s", node->getName().c_str());
NodeList::iterator elem = node->begin();
(*elem)->accept(this);
}
virtual void at(const GroupingExpression* node)
{
write("(");
NodeList::iterator elem = node->begin();
(*elem)->accept(this);
write(")");
}
virtual void at(const Literal* node)
{
write("%s", node->getName().c_str());
}
virtual void at(const Member* node)
{
if (node->isTypedef(node->getParent()))
{
node->getSpec()->accept(this);
}
else
{
// This node is an exception class member.
writetab();
write("public ");
node->getSpec()->accept(this);
write(" %s;\n", node->getName().c_str());
}
}
virtual void at(const ArrayDcl* node)
{
assert(!node->isLeaf());
if (node->isTypedef(node->getParent()))
{
return;
}
writetab();
node->getSpec()->accept(this);
write(" %s", node->getName().c_str());
for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
{
write("[");
(*i)->accept(this);
write("]");
}
if (node->isTypedef(node->getParent()))
{
write(";\n");
}
}
virtual void at(const ConstDcl* node)
{
writetab();
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
write("public static final ");
node->getSpec()->accept(this);
write(" %s = ", node->getName().c_str());
node->getExp()->accept(this);
write(";\n");
}
virtual void at(const Attribute* node)
{
writetab();
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
// getter
Java::getter(node);
write(";\n");
if (!node->isReadonly() || node->isPutForwards() || node->isReplaceable())
{
// setter
writetab();
Java::setter(node);
write(";\n");
}
}
virtual void at(const OpDcl* node)
{
writetab();
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
Java::at(node);
write(";\n");
}
};
class JavaImport : public Visitor, public Formatter
{
std::string package;
const Interface* current;
bool printed;
std::string prefixedName;
std::set<std::string> importSet;
public:
JavaImport(std::string package, FILE* file, const char* indent) :
Formatter(file, indent),
package(package),
current(0)
{
}
virtual void at(const Node* node)
{
visitChildren(node);
}
virtual void at(const ScopedName* node)
{
assert(current);
Node* resolved = node->search(current);
node->check(resolved, "could not resolved %s.", node->getName().c_str());
if (dynamic_cast<Interface*>(resolved) || dynamic_cast<ExceptDcl*>(resolved))
{
if (resolved->isBaseObject())
{
return;
}
if (Module* module = dynamic_cast<Module*>(resolved->getParent()))
{
if (prefixedName != module->getPrefixedName())
{
importSet.insert(Java::getPackageName(module->getPrefixedName()) + "." + resolved->getName());
}
}
}
}
virtual void at(const Interface* node)
{
if (current)
{
return;
}
current = node;
if (Module* module = dynamic_cast<Module*>(node->getParent()))
{
prefixedName = module->getPrefixedName();
}
visitChildren(node->getExtends());
visitChildren(node);
// Expand mixins
std::list<const Interface*> interfaceList;
node->collectMixins(&interfaceList, node);
for (std::list<const Interface*>::const_iterator i = interfaceList.begin();
i != interfaceList.end();
++i)
{
if (*i == node)
{
continue;
}
current = *i;
visitChildren(*i);
}
current = node;
}
virtual void at(const Attribute* node)
{
node->getSpec()->accept(this);
visitChildren(node->getGetRaises());
if (!node->isReadonly() || node->isPutForwards() || node->isReplaceable())
{
visitChildren(node->getSetRaises());
}
}
virtual void at(const OpDcl* node)
{
node->getSpec()->accept(this);
visitChildren(node);
visitChildren(node->getRaises());
}
virtual void at(const ParamDcl* node)
{
node->getSpec()->accept(this);
}
void print()
{
if (importSet.empty())
{
return;
}
for (std::set<std::string>::iterator i = importSet.begin();
i != importSet.end();
++i)
{
write("import %s;\n", (*i).c_str());
}
write("\n");
}
};
class JavaVisitor : public Visitor
{
const char* source;
const char* indent;
std::string prefixedName;
public:
JavaVisitor(const char* source, const char* indent = "es") :
source(source),
indent(indent)
{
}
virtual void at(const Node* node)
{
if (1 < node->getRank())
{
return;
}
visitChildren(node);
}
virtual void at(const Module* node)
{
std::string enclosed = prefixedName;
prefixedName = node->getPrefixedName();
at(static_cast<const Node*>(node));
prefixedName = enclosed;
}
virtual void at(const ExceptDcl* node)
{
if (1 < node->getRank() || node->isLeaf() || !node->isDefinedIn(source))
{
return;
}
FILE* file = createFile(Java::getPackageName(prefixedName), node);
if (!file)
{
return;
}
fprintf(file, "// Generated by esidl %s.\n\n", VERSION);
fprintf(file, "package %s;\n\n", Java::getPackageName(prefixedName).c_str());
JavaInterface javaInterface(source, file, indent);
javaInterface.at(node);
fclose(file);
}
virtual void at(const Interface* node)
{
if (1 < node->getRank() || node->isLeaf() || !node->isDefinedIn(source) ||
(node->getAttr() & Interface::Supplemental))
{
return;
}
FILE* file = createFile(Java::getPackageName(prefixedName), node);
if (!file)
{
return;
}
fprintf(file, "// Generated by esidl %s.\n\n", VERSION);
fprintf(file, "package %s;\n\n", Java::getPackageName(prefixedName).c_str());
JavaImport import(Java::getPackageName(prefixedName), file, indent);
import.at(node);
import.print();
JavaInterface javaInterface(source, file, indent);
javaInterface.at(node);
fclose(file);
}
};
void printJava(const char* source, const char* indent)
{
JavaVisitor visitor(source, indent);
getSpecification()->accept(&visitor);
}
<commit_msg>(Java) : Generate constructors for exception classes.<commit_after>/*
* Copyright 2008, 2009 Google Inc.
* Copyright 2007 Nintendo Co., Ltd.
*
* 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 <sys/stat.h>
#include <sys/types.h>
#include <set>
#include "java.h"
namespace
{
FILE* createFile(const std::string package, const Node* node)
{
std::string filename = package;
size_t pos = 0;
for (;;)
{
pos = filename.find('.', pos);
if (pos == std::string::npos)
{
break;
}
filename[pos] = '/';
}
filename += "/" + node->getName() + ".java";
std::string dir;
std::string path(filename);
for (;;)
{
size_t slash = path.find("/");
if (slash == std::string::npos)
{
break;
}
dir += path.substr(0, slash);
path.erase(0, slash + 1);
mkdir(dir.c_str(), 0777);
dir += '/';
}
printf("# %s in %s\n", node->getName().c_str(), filename.c_str());
return fopen(filename.c_str(), "w");
}
} // namespace
class JavaInterface : public Java
{
// TODO: Move to Java
void visitInterfaceElement(const Interface* interface, Node* element)
{
if (dynamic_cast<Interface*>(element))
{
// Do not process Constructor.
return;
}
optionalStage = 0;
do
{
optionalCount = 0;
element->accept(this);
++optionalStage;
} while (optionalStage <= optionalCount);
}
public:
JavaInterface(const char* source, FILE* file, const char* indent = "es") :
Java(source, file, indent)
{
}
virtual void at(const ExceptDcl* node)
{
writetab();
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
write("public class %s extends RuntimeException {\n", node->getName().c_str());
// Constructor
// TODO: should check exception members
writeln("public %s(short code, String message) {", node->getName().c_str());
writeln("super(message);");
writeln("this.code = code;");
writeln("}");
printChildren(node);
writeln("}");
}
virtual void at(const Interface* node)
{
if (!currentNode)
{
currentNode = node->getParent();
}
assert(!(node->getAttr() & Interface::Supplemental) && !node->isLeaf());
writetab();
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
std::string name = node->getQualifiedName();
name = getInterfaceName(name);
write("public interface %s", name.substr(name.rfind(':') + 1).c_str());
if (node->getExtends())
{
const char* separator = " extends ";
for (NodeList::iterator i = node->getExtends()->begin();
i != node->getExtends()->end();
++i)
{
if ((*i)->getName() == Node::getBaseObjectName())
{
// Do not extend from 'Object'.
continue;
}
write(separator);
separator = ", ";
(*i)->accept(this);
}
}
write(" {\n");
for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
{
visitInterfaceElement(node, *i);
}
// Expand mixins
std::list<const Interface*> interfaceList;
node->collectMixins(&interfaceList, node);
for (std::list<const Interface*>::const_iterator i = interfaceList.begin();
i != interfaceList.end();
++i)
{
if (*i == node)
{
continue;
}
writeln("// %s", (*i)->getName().c_str());
const Node* saved = currentNode;
for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j)
{
currentNode = *i;
visitInterfaceElement(*i, *j);
}
currentNode = saved;
}
writeln("}");
}
virtual void at(const BinaryExpr* node)
{
node->getLeft()->accept(this);
write(" %s ", node->getName().c_str());
node->getRight()->accept(this);
}
virtual void at(const UnaryExpr* node)
{
write("%s", node->getName().c_str());
NodeList::iterator elem = node->begin();
(*elem)->accept(this);
}
virtual void at(const GroupingExpression* node)
{
write("(");
NodeList::iterator elem = node->begin();
(*elem)->accept(this);
write(")");
}
virtual void at(const Literal* node)
{
write("%s", node->getName().c_str());
}
virtual void at(const Member* node)
{
if (node->isTypedef(node->getParent()))
{
node->getSpec()->accept(this);
}
else
{
// This node is an exception class member.
writetab();
write("public ");
node->getSpec()->accept(this);
write(" %s;\n", node->getName().c_str());
}
}
virtual void at(const ArrayDcl* node)
{
assert(!node->isLeaf());
if (node->isTypedef(node->getParent()))
{
return;
}
writetab();
node->getSpec()->accept(this);
write(" %s", node->getName().c_str());
for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
{
write("[");
(*i)->accept(this);
write("]");
}
if (node->isTypedef(node->getParent()))
{
write(";\n");
}
}
virtual void at(const ConstDcl* node)
{
writetab();
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
write("public static final ");
node->getSpec()->accept(this);
write(" %s = ", node->getName().c_str());
node->getExp()->accept(this);
write(";\n");
}
virtual void at(const Attribute* node)
{
writetab();
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
// getter
Java::getter(node);
write(";\n");
if (!node->isReadonly() || node->isPutForwards() || node->isReplaceable())
{
// setter
writetab();
Java::setter(node);
write(";\n");
}
}
virtual void at(const OpDcl* node)
{
writetab();
if (node->getJavadoc().size())
{
write("%s\n", node->getJavadoc().c_str());
writetab();
}
Java::at(node);
write(";\n");
}
};
class JavaImport : public Visitor, public Formatter
{
std::string package;
const Interface* current;
bool printed;
std::string prefixedName;
std::set<std::string> importSet;
public:
JavaImport(std::string package, FILE* file, const char* indent) :
Formatter(file, indent),
package(package),
current(0)
{
}
virtual void at(const Node* node)
{
visitChildren(node);
}
virtual void at(const ScopedName* node)
{
assert(current);
Node* resolved = node->search(current);
node->check(resolved, "could not resolved %s.", node->getName().c_str());
if (dynamic_cast<Interface*>(resolved) || dynamic_cast<ExceptDcl*>(resolved))
{
if (resolved->isBaseObject())
{
return;
}
if (Module* module = dynamic_cast<Module*>(resolved->getParent()))
{
if (prefixedName != module->getPrefixedName())
{
importSet.insert(Java::getPackageName(module->getPrefixedName()) + "." + resolved->getName());
}
}
}
}
virtual void at(const Interface* node)
{
if (current)
{
return;
}
current = node;
if (Module* module = dynamic_cast<Module*>(node->getParent()))
{
prefixedName = module->getPrefixedName();
}
visitChildren(node->getExtends());
visitChildren(node);
// Expand mixins
std::list<const Interface*> interfaceList;
node->collectMixins(&interfaceList, node);
for (std::list<const Interface*>::const_iterator i = interfaceList.begin();
i != interfaceList.end();
++i)
{
if (*i == node)
{
continue;
}
current = *i;
visitChildren(*i);
}
current = node;
}
virtual void at(const Attribute* node)
{
node->getSpec()->accept(this);
visitChildren(node->getGetRaises());
if (!node->isReadonly() || node->isPutForwards() || node->isReplaceable())
{
visitChildren(node->getSetRaises());
}
}
virtual void at(const OpDcl* node)
{
node->getSpec()->accept(this);
visitChildren(node);
visitChildren(node->getRaises());
}
virtual void at(const ParamDcl* node)
{
node->getSpec()->accept(this);
}
void print()
{
if (importSet.empty())
{
return;
}
for (std::set<std::string>::iterator i = importSet.begin();
i != importSet.end();
++i)
{
write("import %s;\n", (*i).c_str());
}
write("\n");
}
};
class JavaVisitor : public Visitor
{
const char* source;
const char* indent;
std::string prefixedName;
public:
JavaVisitor(const char* source, const char* indent = "es") :
source(source),
indent(indent)
{
}
virtual void at(const Node* node)
{
if (1 < node->getRank())
{
return;
}
visitChildren(node);
}
virtual void at(const Module* node)
{
std::string enclosed = prefixedName;
prefixedName = node->getPrefixedName();
at(static_cast<const Node*>(node));
prefixedName = enclosed;
}
virtual void at(const ExceptDcl* node)
{
if (1 < node->getRank() || node->isLeaf() || !node->isDefinedIn(source))
{
return;
}
FILE* file = createFile(Java::getPackageName(prefixedName), node);
if (!file)
{
return;
}
fprintf(file, "// Generated by esidl %s.\n\n", VERSION);
fprintf(file, "package %s;\n\n", Java::getPackageName(prefixedName).c_str());
JavaInterface javaInterface(source, file, indent);
javaInterface.at(node);
fclose(file);
}
virtual void at(const Interface* node)
{
if (1 < node->getRank() || node->isLeaf() || !node->isDefinedIn(source) ||
(node->getAttr() & Interface::Supplemental))
{
return;
}
FILE* file = createFile(Java::getPackageName(prefixedName), node);
if (!file)
{
return;
}
fprintf(file, "// Generated by esidl %s.\n\n", VERSION);
fprintf(file, "package %s;\n\n", Java::getPackageName(prefixedName).c_str());
JavaImport import(Java::getPackageName(prefixedName), file, indent);
import.at(node);
import.print();
JavaInterface javaInterface(source, file, indent);
javaInterface.at(node);
fclose(file);
}
};
void printJava(const char* source, const char* indent)
{
JavaVisitor visitor(source, indent);
getSpecification()->accept(&visitor);
}
<|endoftext|> |
<commit_before>/*
* Licensed under the MIT License (MIT)
*
* Copyright (c) 2014 AudioScience Inc.
*
* 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.
*/
/**
* cmd_wait_mgr.cpp
*
* Notification base class implementation, which is called by AVDECC LIB modules to generate notification messages.
*/
#include "cmd_wait_mgr.h"
namespace avdecc_lib
{
cmd_wait_mgr::cmd_wait_mgr()
{
state = wait_idle;
}
cmd_wait_mgr::~cmd_wait_mgr() {}
int cmd_wait_mgr::set_primed_state(void * id)
{
if (state != wait_idle)
return -1;
else
{
state = wait_primed;
return 0;
}
}
int cmd_wait_mgr::set_active_state(void)
{
if (state != wait_primed)
return -1;
else
{
state = wait_active;
return 0;
}
}
int cmd_wait_mgr::set_idle_state(void)
{
if (state != wait_active)
return -1;
else
{
state = wait_idle;
return 0;
}
}
bool cmd_wait_mgr::match_id(void * id)
{
return id == notify_id;
}
void * cmd_wait_mgr::get_notify_id(void)
{
return notify_id;
}
bool cmd_wait_mgr::active_state(void)
{
return state == wait_active;
}
bool cmd_wait_mgr::primed_state(void)
{
return state == wait_primed;
}
int cmd_wait_mgr::set_completion_status(int status)
{
if (state != wait_active)
return -1;
else
{
completion_status = status;
return 0;
}
}
int cmd_wait_mgr::get_completion_status(void)
{
return completion_status;
}
}
<commit_msg>Ensure that notifications actually cause a wait.<commit_after>/*
* Licensed under the MIT License (MIT)
*
* Copyright (c) 2014 AudioScience Inc.
*
* 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.
*/
/**
* cmd_wait_mgr.cpp
*
* Notification base class implementation, which is called by AVDECC LIB modules to generate notification messages.
*/
#include "cmd_wait_mgr.h"
namespace avdecc_lib
{
cmd_wait_mgr::cmd_wait_mgr()
{
state = wait_idle;
}
cmd_wait_mgr::~cmd_wait_mgr() {}
int cmd_wait_mgr::set_primed_state(void * id)
{
if (state != wait_idle)
return -1;
else
{
notify_id = id;
state = wait_primed;
return 0;
}
}
int cmd_wait_mgr::set_active_state(void)
{
if (state != wait_primed)
return -1;
else
{
state = wait_active;
return 0;
}
}
int cmd_wait_mgr::set_idle_state(void)
{
if (state != wait_active)
return -1;
else
{
state = wait_idle;
return 0;
}
}
bool cmd_wait_mgr::match_id(void * id)
{
return id == notify_id;
}
void * cmd_wait_mgr::get_notify_id(void)
{
return notify_id;
}
bool cmd_wait_mgr::active_state(void)
{
return state == wait_active;
}
bool cmd_wait_mgr::primed_state(void)
{
return state == wait_primed;
}
int cmd_wait_mgr::set_completion_status(int status)
{
if (state != wait_active)
return -1;
else
{
completion_status = status;
return 0;
}
}
int cmd_wait_mgr::get_completion_status(void)
{
return completion_status;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 Fondazione Istituto Italiano di Tecnologia
* Authors: Silvio Traversaro
* CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT
*
*/
#include <iDynTree/Core/SpatialForceVector.h>
#include <iDynTree/Core/SpatialMotionVector.h>
#include <iDynTree/Core/Axis.h>
#include <iDynTree/Core/SpatialForceVector.h>
#include <iDynTree/Core/SpatialMotionVector.h>
#include <iDynTree/Core/SpatialInertia.h>
#include <iDynTree/Core/TestUtils.h>
#include <iDynTree/Core/Transform.h>
#include <iostream>
#include <cstdlib>
#include <cmath>
namespace iDynTree
{
void assertStringAreEqual(const std::string& val1, const std::string& val2, double tol, std::string file, int line)
{
if( val1 != val2 )
{
std::cerr << "assertStringAreEqual failure: val1 is " << val1
<< " while val2 is " << val2 << std::endl;
exit(EXIT_FAILURE);
}
}
void assertDoubleAreEqual(const double& val1, const double& val2, double tol, std::string file, int line)
{
if( fabs(val1-val2) >= tol )
{
std::cerr << "assertDoubleAreEqual failure: val1 is " << val1
<< " while val2 is " << val2 << std::endl;
exit(EXIT_FAILURE);
}
}
void printVector(std::string name, const IVector& vec)
{
std::cerr << name << " : \n";
for(int i=0; i < vec.size(); i++ )
{
std::cerr << vec(i) << "\n";
}
}
void assertVectorAreEqual(const IVector& vec1, const IVector& vec2, double tol, std::string file, int line)
{
if( vec1.size() != vec2.size() )
{
std::cerr << file << ":" << line << " : assertVectorAreEqual failure: vec1 has size " << vec1.size()
<< " while vec2 has size " << vec2.size() << std::endl;
exit(EXIT_FAILURE);
}
for( unsigned int i = 0; i < vec1.size(); i++ )
{
if( fabs(vec1(i)-vec2(i)) >= tol )
{
std::cerr << file << ":" << line << " : assertVectorAreEqual failure: element " << i << " of vec1 is " << vec1(i)
<< " while of vec2 is " << vec2(i) << std::endl;
printVector("vec1",vec1);
printVector("vec2",vec2);
exit(EXIT_FAILURE);
}
}
}
void assertMatrixAreEqual(const IMatrix& mat1, const IMatrix& mat2, double tol, std::string file, int line)
{
if( mat1.rows() != mat2.rows() ||
mat2.cols() != mat1.cols() )
{
std::cerr << file << ":" << line << " : assertMatrixAreEqual failure: mat1 has size " << mat1.rows() << " " << mat1.cols()
<< " while mat2 has size " << mat2.rows() << " " << mat2.cols() << std::endl;
exit(EXIT_FAILURE);
}
for( unsigned int row = 0; row < mat2.rows(); row++ )
{
for( unsigned int col = 0; col < mat2.cols(); col++ )
{
if( fabs(mat1(row,col)-mat2(row,col)) >= tol )
{
std::cerr << file << ":" << line << " : assertMatrixAreEqual failure: element " << row << " " << col << " of mat1 is " << mat1(row,col)
<< " while of mat2 is " << mat2(row,col) << std::endl;
exit(EXIT_FAILURE);
}
}
}
}
void assertTransformsAreEqual(const Transform& trans1, const Transform& trans2, double tol, std::string file, int line)
{
assertVectorAreEqual(trans1.getPosition(),trans2.getPosition(),tol,file,line);
assertMatrixAreEqual(trans1.getRotation(),trans2.getRotation(),tol,file,line);
}
void assertSpatialForceAreEqual(const SpatialForceVector& f1, const SpatialForceVector& f2, double tol, std::string file, int line)
{
Vector6 f1plain = f1.asVector();
Vector6 f2plain = f2.asVector();
assertVectorAreEqual(f1plain,f2plain,tol,file,line);
}
void assertSpatialMotionAreEqual(const SpatialMotionVector& f1, const SpatialMotionVector& f2, double tol, std::string file, int line)
{
Vector6 f1plain = f1.asVector();
Vector6 f2plain = f2.asVector();
assertVectorAreEqual(f1plain,f2plain,tol,file,line);
}
double getRandomDouble(double min, double max)
{
return min + (max-min)*((double)rand())/((double)RAND_MAX);
}
Position getRandomPosition()
{
return Position(getRandomDouble(-2,2),getRandomDouble(-2,2),getRandomDouble(-2,2));
}
Rotation getRandomRotation()
{
return Rotation::RPY(getRandomDouble(),getRandomDouble(-1,1),getRandomDouble());
}
Transform getRandomTransform()
{
return Transform(getRandomRotation(),getRandomPosition());
}
Axis getRandomAxis()
{
return Axis(getRandomRotation()*Direction(1,0,0),getRandomPosition());
}
SpatialInertia getRandomInertia()
{
double cxx = getRandomDouble(0,3);
double cyy = getRandomDouble(0,4);
double czz = getRandomDouble(0,6);
double rotInertiaData[3*3] = {czz+cyy,0.0,0.0,
0.0,cxx+czz,0.0,
0.0,0.0,cxx+cyy};
Rotation rot = Rotation::RPY(getRandomDouble(),getRandomDouble(-1,1),getRandomDouble());
SpatialInertia inertiaLink(getRandomDouble(0,4),
Position(getRandomDouble(-2,2),getRandomDouble(-2,2),getRandomDouble(-2,2)),
rot*RotationalInertiaRaw(rotInertiaData,3,3));
}
SpatialMotionVector getRandomTwist()
{
SpatialMotionVector ret;
for(int i=0; i < 3; i++ )
{
ret.getLinearVec3()(i) = getRandomDouble();
ret.getAngularVec3()(i) = getRandomDouble();
}
return ret;
}
SpatialForceVector getRandomWrench()
{
SpatialForceVector ret;
for(int i=0; i < 3; i++ )
{
ret.getLinearVec3()(i) = getRandomDouble();
ret.getAngularVec3()(i) = getRandomDouble();
}
return ret;
}
}<commit_msg>Fix getRandomInertia test helper function<commit_after>/*
* Copyright (C) 2015 Fondazione Istituto Italiano di Tecnologia
* Authors: Silvio Traversaro
* CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT
*
*/
#include <iDynTree/Core/SpatialForceVector.h>
#include <iDynTree/Core/SpatialMotionVector.h>
#include <iDynTree/Core/Axis.h>
#include <iDynTree/Core/SpatialForceVector.h>
#include <iDynTree/Core/SpatialMotionVector.h>
#include <iDynTree/Core/SpatialInertia.h>
#include <iDynTree/Core/TestUtils.h>
#include <iDynTree/Core/Transform.h>
#include <iostream>
#include <cstdlib>
#include <cmath>
namespace iDynTree
{
void assertStringAreEqual(const std::string& val1, const std::string& val2, double tol, std::string file, int line)
{
if( val1 != val2 )
{
std::cerr << "assertStringAreEqual failure: val1 is " << val1
<< " while val2 is " << val2 << std::endl;
exit(EXIT_FAILURE);
}
}
void assertDoubleAreEqual(const double& val1, const double& val2, double tol, std::string file, int line)
{
if( fabs(val1-val2) >= tol )
{
std::cerr << "assertDoubleAreEqual failure: val1 is " << val1
<< " while val2 is " << val2 << std::endl;
exit(EXIT_FAILURE);
}
}
void printVector(std::string name, const IVector& vec)
{
std::cerr << name << " : \n";
for(int i=0; i < vec.size(); i++ )
{
std::cerr << vec(i) << "\n";
}
}
void assertVectorAreEqual(const IVector& vec1, const IVector& vec2, double tol, std::string file, int line)
{
if( vec1.size() != vec2.size() )
{
std::cerr << file << ":" << line << " : assertVectorAreEqual failure: vec1 has size " << vec1.size()
<< " while vec2 has size " << vec2.size() << std::endl;
exit(EXIT_FAILURE);
}
for( unsigned int i = 0; i < vec1.size(); i++ )
{
if( fabs(vec1(i)-vec2(i)) >= tol )
{
std::cerr << file << ":" << line << " : assertVectorAreEqual failure: element " << i << " of vec1 is " << vec1(i)
<< " while of vec2 is " << vec2(i) << std::endl;
printVector("vec1",vec1);
printVector("vec2",vec2);
exit(EXIT_FAILURE);
}
}
}
void assertMatrixAreEqual(const IMatrix& mat1, const IMatrix& mat2, double tol, std::string file, int line)
{
if( mat1.rows() != mat2.rows() ||
mat2.cols() != mat1.cols() )
{
std::cerr << file << ":" << line << " : assertMatrixAreEqual failure: mat1 has size " << mat1.rows() << " " << mat1.cols()
<< " while mat2 has size " << mat2.rows() << " " << mat2.cols() << std::endl;
exit(EXIT_FAILURE);
}
for( unsigned int row = 0; row < mat2.rows(); row++ )
{
for( unsigned int col = 0; col < mat2.cols(); col++ )
{
if( fabs(mat1(row,col)-mat2(row,col)) >= tol )
{
std::cerr << file << ":" << line << " : assertMatrixAreEqual failure: element " << row << " " << col << " of mat1 is " << mat1(row,col)
<< " while of mat2 is " << mat2(row,col) << std::endl;
exit(EXIT_FAILURE);
}
}
}
}
void assertTransformsAreEqual(const Transform& trans1, const Transform& trans2, double tol, std::string file, int line)
{
assertVectorAreEqual(trans1.getPosition(),trans2.getPosition(),tol,file,line);
assertMatrixAreEqual(trans1.getRotation(),trans2.getRotation(),tol,file,line);
}
void assertSpatialForceAreEqual(const SpatialForceVector& f1, const SpatialForceVector& f2, double tol, std::string file, int line)
{
Vector6 f1plain = f1.asVector();
Vector6 f2plain = f2.asVector();
assertVectorAreEqual(f1plain,f2plain,tol,file,line);
}
void assertSpatialMotionAreEqual(const SpatialMotionVector& f1, const SpatialMotionVector& f2, double tol, std::string file, int line)
{
Vector6 f1plain = f1.asVector();
Vector6 f2plain = f2.asVector();
assertVectorAreEqual(f1plain,f2plain,tol,file,line);
}
double getRandomDouble(double min, double max)
{
return min + (max-min)*((double)rand())/((double)RAND_MAX);
}
Position getRandomPosition()
{
return Position(getRandomDouble(-2,2),getRandomDouble(-2,2),getRandomDouble(-2,2));
}
Rotation getRandomRotation()
{
return Rotation::RPY(getRandomDouble(),getRandomDouble(-1,1),getRandomDouble());
}
Transform getRandomTransform()
{
return Transform(getRandomRotation(),getRandomPosition());
}
Axis getRandomAxis()
{
return Axis(getRandomRotation()*Direction(1,0,0),getRandomPosition());
}
SpatialInertia getRandomInertia()
{
double cxx = getRandomDouble(0,3);
double cyy = getRandomDouble(0,4);
double czz = getRandomDouble(0,6);
double rotInertiaData[3*3] = {czz+cyy,0.0,0.0,
0.0,cxx+czz,0.0,
0.0,0.0,cxx+cyy};
Rotation rot = Rotation::RPY(getRandomDouble(),getRandomDouble(-1,1),getRandomDouble());
SpatialInertia inertiaLink(getRandomDouble(0,4),
Position(getRandomDouble(-2,2),getRandomDouble(-2,2),getRandomDouble(-2,2)),
rot*RotationalInertiaRaw(rotInertiaData,3,3));
return inertiaLink;
}
SpatialMotionVector getRandomTwist()
{
SpatialMotionVector ret;
for(int i=0; i < 3; i++ )
{
ret.getLinearVec3()(i) = getRandomDouble();
ret.getAngularVec3()(i) = getRandomDouble();
}
return ret;
}
SpatialForceVector getRandomWrench()
{
SpatialForceVector ret;
for(int i=0; i < 3; i++ )
{
ret.getLinearVec3()(i) = getRandomDouble();
ret.getAngularVec3()(i) = getRandomDouble();
}
return ret;
}
}<|endoftext|> |
<commit_before>/* router_logger.cc
Rémi Attab and Jeremy Barnes, March 2011
Copyright (c) 2012 Datacratic. All rights reserved.
Launches the router's logger.
*/
#include "soa/service/service_base.h"
#include "soa/service/carbon_connector.h"
#include "soa/service/process_stats.h"
#include "soa/service/service_base.h"
#include "soa/service/zmq_named_pub_sub.h"
#include "soa/logger/file_output.h"
#include "soa/logger/stats_output.h"
#include "soa/logger/multi_output.h"
#include "rtbkit/common/auction.h"
#include "jml/arch/timers.h"
#include "rtbkit/core/monitor/monitor_provider.h"
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/positional_options.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/regex.hpp>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <thread>
#include <algorithm>
#include "router_logger.h"
using namespace std;
using namespace Datacratic;
using namespace RTBKIT;
bool getArgs (int argc, char** argv);
static struct {
vector<string> subscribeUris;
string logDir;
vector<string> carbonUris;
string zookeeperUri;
string installation;
string nodeName;
string rotationInterval;
} g_args;
int main (int argc, char** argv)
{
if (!getArgs(argc, argv)) {
return -1;
}
auto proxies = std::make_shared<ServiceProxies>();
proxies->useZookeeper(g_args.zookeeperUri, g_args.installation);
if (!g_args.carbonUris.empty())
proxies->logToCarbon(g_args.carbonUris,
g_args.installation + "." + g_args.nodeName);
proxies->config->dump(cerr);
string rotationInterval = g_args.rotationInterval;
cerr << "Log Directory: " << g_args.logDir << endl;
RouterLogger logger(proxies);
string myIdentity
= g_args.installation + "."
+ g_args.nodeName + "."
+ "router_logger";
// Subscribe to any sockets directly that include legacy information that
// should be logged.
for (auto u: g_args.subscribeUris) {
cerr << "subscribing to fixed URI " << u << endl;
logger.subscribe(u, vector<string>(), myIdentity);
}
// Subscribe to all messages
logger.connectAllServiceProviders("adServer", "logger");
logger.connectAllServiceProviders("rtbRequestRouter", "logger");
logger.connectAllServiceProviders("rtbPostAuctionService", "logger");
// Setup outputs
auto consoleOutput = std::make_shared<ConsoleStatsOutput>();
logger.addOutput(consoleOutput);
std::shared_ptr<CarbonStatsOutput> carbonOutput
(new CarbonStatsOutput(proxies->events, "router_logger"));
logger.addOutput(carbonOutput);
// File output (appended) for normal logs
std::shared_ptr<RotatingFileOutput> normalOutput
(new RotatingFileOutput());
normalOutput->open(g_args.logDir + "/%F/router-%F-%T.log.gz", rotationInterval, "gz");
normalOutput->onFileWrite = [&](const string& channel, size_t bytes) {
carbonOutput->recordBytesWrittenToFile("router", bytes);
};
logger.addOutput(normalOutput,
boost::regex(".*"),
boost::regex("AUCTION|BEHAVIOUR|CLICK|DATA|IMPRESSION|INTERACTION|ROUTERERROR|WIN|MATCHEDLOSS"));
// File output (appended) for router error logs
std::shared_ptr<RotatingFileOutput> errorOutput
(new RotatingFileOutput());
errorOutput->open(g_args.logDir + "/%F/errors-%F-%T.log", rotationInterval);
errorOutput->onFileWrite = [&](const string& channel, size_t bytes) {
carbonOutput->recordBytesWrittenToFile("error", bytes);
};
logger.addOutput(errorOutput, boost::regex("ROUTERERROR"), boost::regex());
std::shared_ptr<RotatingFileOutput> writeDelivery
(new RotatingFileOutput());
writeDelivery
->open(g_args.logDir + "/%F/delivery-%F-%T.log.gz", rotationInterval, "gz");
writeDelivery->onFileWrite = [&](const string& channel, size_t bytes) {
carbonOutput->recordBytesWrittenToFile("delivery", bytes);
};
logger.addOutput(writeDelivery,
boost::regex("CLICK|DATA|IMPRESSION|INTERACTION"));
// Strategy-level data
auto strategyOutput = std::make_shared<MultiOutput>();
auto createMatchedWinFile = [&] (const std::string & pattern)
{
auto result = std::make_shared<RotatingFileOutput>();
result->open(pattern, rotationInterval);
return result;
};
strategyOutput->logTo("MATCHEDWIN", g_args.logDir + "/%F/$(17)/$(5)/$(0)-%T.log.gz",
createMatchedWinFile);
strategyOutput->logTo("", g_args.logDir + "/%F/$(10)/$(11)/$(0)-%T.log.gz",
createMatchedWinFile);
logger.addOutput(strategyOutput, boost::regex("MATCHEDWIN|MATCHEDIMPRESSION|MATCHEDCLICK|MATCHEDVISIT"));
// Behaviours
std::shared_ptr<RotatingFileOutput> behaviourOutput
(new RotatingFileOutput());
behaviourOutput
->open(g_args.logDir + "/%F/behaviour-%F-%T.log.gz", rotationInterval, "gz");
behaviourOutput->onFileWrite = [&](const string& channel, size_t bytes) {
carbonOutput->recordBytesWrittenToFile("behaviour", bytes);
};
logger.addOutput(behaviourOutput, boost::regex("BEHAVIOUR"));
logger.init(proxies->config);
logger.start();
// Start periodic stats dump.
ProcessStats lastStats;
while (true) {
ML::sleep(10.0);
ProcessStats curStats;
ProcessStats::logToCallback(
[&](string name, double value) {
carbonOutput->recordLevel(name, value); },
lastStats, curStats, "process");
lastStats = curStats;
consoleOutput->dumpStats();
}
}
bool getArgs (int argc, char** argv)
{
// Default values.
g_args.logDir = "router_logger";
g_args.rotationInterval = "1h";
using namespace boost::program_options;
options_description loggerOptions("Logger Options");
loggerOptions.add_options()
("subscribe-uri,s", value<vector<string> >(&g_args.subscribeUris),
"URI to listen on for events (should be a zmq PUB socket).")
("log-dir,d", value<string>(&g_args.logDir),
"Directory where the folders should be stored.");
options_description carbonOptions("Carbon Options");
carbonOptions.add_options()
("carbon-connection,c", value<vector<string> >(&g_args.carbonUris),
"URI of connection to carbon daemon (format: host:port)");
options_description allOptions;
allOptions.add_options()
("zookeeper-uri,Z", value(&g_args.zookeeperUri),
"URI of zookeeper to use")
("installation,I", value(&g_args.installation),
"Name of the installation that is running")
("node-name,N", value(&g_args.nodeName),
"Name of the node we're running");
allOptions.add(loggerOptions).add(carbonOptions);
allOptions.add_options() ("help,h", "Prints this message");
variables_map vm;
store(command_line_parser(argc, argv).options(allOptions).run(), vm);
notify(vm);
if (vm.count("help")) {
cerr << allOptions << endl;
return false;
}
return true;
}
<commit_msg>installation and node are required for the router logger<commit_after>/* router_logger.cc
Rémi Attab and Jeremy Barnes, March 2011
Copyright (c) 2012 Datacratic. All rights reserved.
Launches the router's logger.
*/
#include "soa/service/service_base.h"
#include "soa/service/carbon_connector.h"
#include "soa/service/process_stats.h"
#include "soa/service/service_base.h"
#include "soa/service/zmq_named_pub_sub.h"
#include "soa/logger/file_output.h"
#include "soa/logger/stats_output.h"
#include "soa/logger/multi_output.h"
#include "rtbkit/common/auction.h"
#include "jml/arch/timers.h"
#include "rtbkit/core/monitor/monitor_provider.h"
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/positional_options.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/regex.hpp>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <thread>
#include <algorithm>
#include "router_logger.h"
using namespace std;
using namespace Datacratic;
using namespace RTBKIT;
bool getArgs (int argc, char** argv);
static struct {
vector<string> subscribeUris;
string logDir;
vector<string> carbonUris;
string zookeeperUri;
string installation;
string nodeName;
string rotationInterval;
} g_args;
int main (int argc, char** argv)
{
if (!getArgs(argc, argv)) {
return -1;
}
auto proxies = std::make_shared<ServiceProxies>();
proxies->useZookeeper(g_args.zookeeperUri, g_args.installation);
if (!g_args.carbonUris.empty())
proxies->logToCarbon(g_args.carbonUris,
g_args.installation + "." + g_args.nodeName);
proxies->config->dump(cerr);
string rotationInterval = g_args.rotationInterval;
cerr << "Log Directory: " << g_args.logDir << endl;
RouterLogger logger(proxies);
string myIdentity
= g_args.installation + "."
+ g_args.nodeName + "."
+ "router_logger";
// Subscribe to any sockets directly that include legacy information that
// should be logged.
for (auto u: g_args.subscribeUris) {
cerr << "subscribing to fixed URI " << u << endl;
logger.subscribe(u, vector<string>(), myIdentity);
}
// Subscribe to all messages
logger.connectAllServiceProviders("adServer", "logger");
logger.connectAllServiceProviders("rtbRequestRouter", "logger");
logger.connectAllServiceProviders("rtbPostAuctionService", "logger");
// Setup outputs
auto consoleOutput = std::make_shared<ConsoleStatsOutput>();
logger.addOutput(consoleOutput);
std::shared_ptr<CarbonStatsOutput> carbonOutput
(new CarbonStatsOutput(proxies->events, "router_logger"));
logger.addOutput(carbonOutput);
// File output (appended) for normal logs
std::shared_ptr<RotatingFileOutput> normalOutput
(new RotatingFileOutput());
normalOutput->open(g_args.logDir + "/%F/router-%F-%T.log.gz", rotationInterval, "gz");
normalOutput->onFileWrite = [&](const string& channel, size_t bytes) {
carbonOutput->recordBytesWrittenToFile("router", bytes);
};
logger.addOutput(normalOutput,
boost::regex(".*"),
boost::regex("AUCTION|BEHAVIOUR|CLICK|DATA|IMPRESSION|INTERACTION|ROUTERERROR|WIN|MATCHEDLOSS"));
// File output (appended) for router error logs
std::shared_ptr<RotatingFileOutput> errorOutput
(new RotatingFileOutput());
errorOutput->open(g_args.logDir + "/%F/errors-%F-%T.log", rotationInterval);
errorOutput->onFileWrite = [&](const string& channel, size_t bytes) {
carbonOutput->recordBytesWrittenToFile("error", bytes);
};
logger.addOutput(errorOutput, boost::regex("ROUTERERROR"), boost::regex());
std::shared_ptr<RotatingFileOutput> writeDelivery
(new RotatingFileOutput());
writeDelivery
->open(g_args.logDir + "/%F/delivery-%F-%T.log.gz", rotationInterval, "gz");
writeDelivery->onFileWrite = [&](const string& channel, size_t bytes) {
carbonOutput->recordBytesWrittenToFile("delivery", bytes);
};
logger.addOutput(writeDelivery,
boost::regex("CLICK|DATA|IMPRESSION|INTERACTION"));
// Strategy-level data
auto strategyOutput = std::make_shared<MultiOutput>();
auto createMatchedWinFile = [&] (const std::string & pattern)
{
auto result = std::make_shared<RotatingFileOutput>();
result->open(pattern, rotationInterval);
return result;
};
strategyOutput->logTo("MATCHEDWIN", g_args.logDir + "/%F/$(17)/$(5)/$(0)-%T.log.gz",
createMatchedWinFile);
strategyOutput->logTo("", g_args.logDir + "/%F/$(10)/$(11)/$(0)-%T.log.gz",
createMatchedWinFile);
logger.addOutput(strategyOutput, boost::regex("MATCHEDWIN|MATCHEDIMPRESSION|MATCHEDCLICK|MATCHEDVISIT"));
// Behaviours
std::shared_ptr<RotatingFileOutput> behaviourOutput
(new RotatingFileOutput());
behaviourOutput
->open(g_args.logDir + "/%F/behaviour-%F-%T.log.gz", rotationInterval, "gz");
behaviourOutput->onFileWrite = [&](const string& channel, size_t bytes) {
carbonOutput->recordBytesWrittenToFile("behaviour", bytes);
};
logger.addOutput(behaviourOutput, boost::regex("BEHAVIOUR"));
logger.init(proxies->config);
logger.start();
// Start periodic stats dump.
ProcessStats lastStats;
while (true) {
ML::sleep(10.0);
ProcessStats curStats;
ProcessStats::logToCallback(
[&](string name, double value) {
carbonOutput->recordLevel(name, value); },
lastStats, curStats, "process");
lastStats = curStats;
consoleOutput->dumpStats();
}
}
bool getArgs (int argc, char** argv)
{
// Default values.
g_args.logDir = "router_logger";
g_args.rotationInterval = "1h";
using namespace boost::program_options;
options_description loggerOptions("Logger Options");
loggerOptions.add_options()
("subscribe-uri,s", value<vector<string> >(&g_args.subscribeUris),
"URI to listen on for events (should be a zmq PUB socket).")
("log-dir,d", value<string>(&g_args.logDir),
"Directory where the folders should be stored.");
options_description carbonOptions("Carbon Options");
carbonOptions.add_options()
("carbon-connection,c", value<vector<string> >(&g_args.carbonUris),
"URI of connection to carbon daemon (format: host:port)");
options_description allOptions;
allOptions.add_options()
("zookeeper-uri,Z", value(&g_args.zookeeperUri),
"URI of zookeeper to use")
("installation,I", value(&g_args.installation),
"Name of the installation that is running")
("node-name,N", value(&g_args.nodeName),
"Name of the node we're running");
allOptions.add(loggerOptions).add(carbonOptions);
allOptions.add_options() ("help,h", "Prints this message");
variables_map vm;
store(command_line_parser(argc, argv).options(allOptions).run(), vm);
notify(vm);
if (vm.count("help")) {
cerr << allOptions << endl;
return false;
}
if (g_args.installation.empty()) {
cerr << "'installation' parameter is required" << endl;
return false;
}
if (g_args.nodeName.empty()) {
cerr << "'node-name' parameter is required" << endl;
return false;
}
return true;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.