text
stringlengths 54
60.6k
|
|---|
<commit_before>#include "Utils/Logging.hpp"
#include "Settings.hpp"
using Dissent::Utils::Logging;
namespace Dissent {
namespace Applications {
Settings::Settings(const QString &file, bool actions) :
_use_file(true),
_settings(new QSettings(file, QSettings::IniFormat))
{
Init(actions);
}
Settings::Settings() :
_use_file(false),
_settings(new QSettings())
{
Init();
}
Settings::Settings(const QSharedPointer<QSettings> &settings,
bool file, bool actions) :
_use_file(file),
_settings(settings)
{
Init(actions);
}
void Settings::Init(bool actions)
{
if(_settings->value("help", false).toBool()) {
Help = true;
return;
}
Help = false;
Console = false;
EntryTunnel = false;
ExitTunnel = false;
LeaderId = Id::Zero();
LocalId = Id::Zero();
LocalNodeCount = 1;
SessionType = "null";
WebServer = false;
QVariant peers = _settings->value(Param<Params::RemotePeers>());
ParseUrlList("RemotePeer", peers, RemotePeers);
QVariant endpoints = _settings->value(Param<Params::LocalEndPoints>());
ParseUrlList("EndPoint", endpoints, LocalEndPoints);
DemoMode = _settings->value(Param<Params::DemoMode>()).toBool();
if(_settings->contains(Param<Params::LocalNodeCount>())) {
LocalNodeCount = _settings->value(Param<Params::LocalNodeCount>()).toInt();
}
Console = _settings->value(Param<Params::Console>()).toBool();
WebServer = _settings->value(Param<Params::WebServer>()).toBool();
EntryTunnel = _settings->value(Param<Params::EntryTunnel>()).toBool();
ExitTunnel = _settings->value(Param<Params::ExitTunnel>()).toBool();
Multithreading = _settings->value(Param<Params::Multithreading>()).toBool();
WebServerUrl = TryParseUrl(_settings->value(Param<Params::WebServerUrl>()).toString(), "http");
EntryTunnelUrl = TryParseUrl(_settings->value(Param<Params::EntryTunnelUrl>()).toString(), "tcp");
if(_settings->contains(Param<Params::SessionType>())) {
SessionType = _settings->value(Param<Params::SessionType>()).toString();
}
if(_settings->contains(Param<Params::SubgroupPolicy>())) {
QString ptype = _settings->value(Param<Params::SubgroupPolicy>()).toString();
SubgroupPolicy = Group::StringToPolicyType(ptype);
}
if(_settings->contains(Param<Params::Log>())) {
Log = _settings->value(Param<Params::Log>()).toString();
QString lower = Log.toLower();
if(actions) {
if(lower == "stderr") {
Logging::UseStderr();
} else if(lower == "stdout") {
Logging::UseStdout();
} else if(Log.isEmpty()) {
Logging::Disable();
} else {
Logging::UseFile(Log);
}
}
}
if(_settings->contains(Param<Params::LocalId>())) {
LocalId = Id(_settings->value(Param<Params::LocalId>()).toString());
}
if(_settings->contains(Param<Params::LeaderId>())) {
LeaderId = Id(_settings->value(Param<Params::LeaderId>()).toString());
}
if(_settings->contains(Param<Params::SuperPeer>())) {
SuperPeer = _settings->value(Param<Params::SuperPeer>()).toBool();
}
}
bool Settings::IsValid()
{
if(_use_file && (_settings->status() != QSettings::NoError)) {
_reason = "File error";
return false;
}
if(LocalEndPoints.count() == 0) {
_reason = "No locally defined end points";
return false;
}
if(WebServer && (!WebServerUrl.isValid() || WebServerUrl.isEmpty())) {
_reason = "Invalid WebServerUrl: " + WebServerUrl.toString();
return false;
}
if(EntryTunnel && (!EntryTunnelUrl.isValid() || EntryTunnelUrl.isEmpty())) {
_reason = "Invalid EntryTunnelUrl: " + EntryTunnelUrl.toString();
return false;
}
if(LeaderId == Id::Zero()) {
_reason = "No leader Id";
return false;
}
if(SubgroupPolicy == -1) {
_reason = "Invalid subgroup policy";
return false;
}
return true;
}
QString Settings::GetError()
{
IsValid();
return _reason;
}
void Settings::ParseUrlList(const QString &name, const QVariant &values,
QList<QUrl> &list)
{
if(values.isNull()) {
return;
}
QVariantList varlist = values.toList();
if(!varlist.empty()) {
foreach(QVariant value, varlist) {
ParseUrl(name, value, list);
}
} else {
ParseUrl(name, values, list);
}
}
inline void Settings::ParseUrl(const QString &name, const QVariant &value,
QList<QUrl> &list)
{
QUrl url(value.toString());
if(url.isValid()) {
list << url;
} else {
qCritical() << "Invalid " << name << ": " << value.toString();
}
}
QUrl Settings::TryParseUrl(const QString &string_rep, const QString &scheme)
{
QUrl url = QUrl(string_rep);
if(url.toString() != string_rep) {
return QUrl();
}
if(url.scheme() != scheme) {
return QUrl();
}
return url;
}
void Settings::Save()
{
if(!_use_file) {
return;
}
QStringList peers;
foreach(QUrl peer, RemotePeers) {
peers << peer.toString();
}
if(!peers.empty()) {
_settings->setValue(Param<Params::RemotePeers>(), peers);
}
QStringList endpoints;
foreach(QUrl endpoint, LocalEndPoints) {
endpoints << endpoint.toString();
}
if(!endpoints.empty()) {
_settings->setValue(Param<Params::LocalEndPoints>(), endpoints);
}
_settings->setValue(Param<Params::LocalNodeCount>(), LocalNodeCount);
_settings->setValue(Param<Params::WebServer>(), WebServer);
_settings->setValue(Param<Params::WebServerUrl>(), WebServerUrl);
_settings->setValue(Param<Params::Console>(), Console);
_settings->setValue(Param<Params::DemoMode>(), DemoMode);
_settings->setValue(Param<Params::Log>(), Log);
_settings->setValue(Param<Params::Multithreading>(), Multithreading);
_settings->setValue(Param<Params::LocalId>(), LocalId.ToString());
_settings->setValue(Param<Params::LeaderId>(), LeaderId.ToString());
_settings->setValue(Param<Params::SubgroupPolicy>(),
Group::PolicyTypeToString(SubgroupPolicy));
}
Settings Settings::CommandLineParse(const QStringList ¶ms, bool actions)
{
QSharedPointer<QxtCommandOptions> options = GetOptions();
options->parse(params);
QSharedPointer<QSettings> settings;
bool file = (options->positional().count() > 0);
if(file) {
settings = QSharedPointer<QSettings>(
new QSettings(options->positional()[0], QSettings::IniFormat));
} else {
settings = QSharedPointer<QSettings>(new QSettings());
if(params.size() == 1) {
settings->setValue("help", true);
}
}
QMultiHash<QString, QVariant> kv_params = options->parameters();
if(kv_params.value("help", false).toBool() && file) {
file = false;
settings = QSharedPointer<QSettings>(new QSettings());
}
foreach(const QString &key, kv_params.uniqueKeys()) {
if(options->value(key).type() == QVariant::String &&
options->value(key).toString().isEmpty())
{
settings->setValue(key, true);
} else {
settings->setValue(key, options->value(key));
}
}
if(options->count(Param<Params::WebServerUrl>()) == 1) {
settings->setValue(Param<Params::WebServer>(), true);
}
if(options->count(Param<Params::EntryTunnelUrl>()) == 1) {
settings->setValue(Param<Params::EntryTunnel>(), true);
}
return Settings(settings, file, actions);
}
QSharedPointer<QxtCommandOptions> Settings::GetOptions()
{
QSharedPointer<QxtCommandOptions> options(new QxtCommandOptions());
options->add(Param<Params::Help>(),
"help (this screen)",
QxtCommandOptions::NoValue);
options->add(Param<Params::RemotePeers>(),
"list of remote peers",
QxtCommandOptions::ValueRequired | QxtCommandOptions::AllowMultiple);
options->add(Param<Params::LocalEndPoints>(),
"list of local end points",
QxtCommandOptions::ValueRequired | QxtCommandOptions::AllowMultiple);
options->add(Param<Params::LocalNodeCount>(),
"number of virtual nodes to start",
QxtCommandOptions::ValueRequired);
options->add(Param<Params::DemoMode>(),
"start in demo mode",
QxtCommandOptions::NoValue);
options->add(Param<Params::SessionType>(),
"the type of session",
QxtCommandOptions::ValueRequired);
options->add(Param<Params::Log>(),
"logging mechanism",
QxtCommandOptions::ValueRequired);
options->add(Param<Params::Console>(),
"enable console",
QxtCommandOptions::NoValue);
options->add(Param<Params::WebServerUrl>(),
"web server url (enables web server)",
QxtCommandOptions::ValueRequired);
options->add(Param<Params::EntryTunnelUrl>(),
"entry tunnel url (enables entry tunnel)",
QxtCommandOptions::ValueRequired);
options->add(Param<Params::ExitTunnel>(),
"enables exit tunnel",
QxtCommandOptions::NoValue);
options->add(Param<Params::Multithreading>(),
"enables multithreading",
QxtCommandOptions::NoValue);
options->add(Param<Params::LocalId>(),
"160-bit base64 local id",
QxtCommandOptions::ValueRequired);
options->add(Param<Params::LeaderId>(),
"160-bit base64 leader id",
QxtCommandOptions::ValueRequired);
options->add(Param<Params::SubgroupPolicy>(),
"subgroup policy (defining servers)",
QxtCommandOptions::ValueRequired);
options->add(Param<Params::SuperPeer>(),
"sets this peer as a capable super peer",
QxtCommandOptions::NoValue);
return options;
}
}
}
<commit_msg>[Applications] settings log<commit_after>#include "Utils/Logging.hpp"
#include "Settings.hpp"
using Dissent::Utils::Logging;
namespace Dissent {
namespace Applications {
Settings::Settings(const QString &file, bool actions) :
_use_file(true),
_settings(new QSettings(file, QSettings::IniFormat))
{
Init(actions);
}
Settings::Settings() :
_use_file(false),
_settings(new QSettings())
{
Init();
}
Settings::Settings(const QSharedPointer<QSettings> &settings,
bool file, bool actions) :
_use_file(file),
_settings(settings)
{
Init(actions);
}
void Settings::Init(bool actions)
{
if(_settings->value("help", false).toBool()) {
Help = true;
return;
}
Help = false;
Console = false;
EntryTunnel = false;
ExitTunnel = false;
LeaderId = Id::Zero();
LocalId = Id::Zero();
LocalNodeCount = 1;
SessionType = "null";
WebServer = false;
QVariant peers = _settings->value(Param<Params::RemotePeers>());
ParseUrlList("RemotePeer", peers, RemotePeers);
QVariant endpoints = _settings->value(Param<Params::LocalEndPoints>());
ParseUrlList("EndPoint", endpoints, LocalEndPoints);
DemoMode = _settings->value(Param<Params::DemoMode>()).toBool();
if(_settings->contains(Param<Params::LocalNodeCount>())) {
LocalNodeCount = _settings->value(Param<Params::LocalNodeCount>()).toInt();
}
Console = _settings->value(Param<Params::Console>()).toBool();
WebServer = _settings->value(Param<Params::WebServer>()).toBool();
EntryTunnel = _settings->value(Param<Params::EntryTunnel>()).toBool();
ExitTunnel = _settings->value(Param<Params::ExitTunnel>()).toBool();
Multithreading = _settings->value(Param<Params::Multithreading>()).toBool();
WebServerUrl = TryParseUrl(_settings->value(Param<Params::WebServerUrl>()).toString(), "http");
EntryTunnelUrl = TryParseUrl(_settings->value(Param<Params::EntryTunnelUrl>()).toString(), "tcp");
if(_settings->contains(Param<Params::SessionType>())) {
SessionType = _settings->value(Param<Params::SessionType>()).toString();
}
if(_settings->contains(Param<Params::SubgroupPolicy>())) {
QString ptype = _settings->value(Param<Params::SubgroupPolicy>()).toString();
SubgroupPolicy = Group::StringToPolicyType(ptype);
}
if(_settings->contains(Param<Params::Log>())) {
Log = _settings->value(Param<Params::Log>()).toString();
QString lower = Log.toLower();
if(actions) {
if(lower == "stderr") {
Logging::UseStderr();
} else if(lower == "stdout") {
Logging::UseStdout();
} else if(Log.isEmpty()) {
Logging::Disable();
} else {
Logging::UseFile(Log);
}
}
}
if(_settings->contains(Param<Params::LocalId>())) {
LocalId = Id(_settings->value(Param<Params::LocalId>()).toString());
}
if(_settings->contains(Param<Params::LeaderId>())) {
LeaderId = Id(_settings->value(Param<Params::LeaderId>()).toString());
}
if(_settings->contains(Param<Params::SuperPeer>())) {
SuperPeer = _settings->value(Param<Params::SuperPeer>()).toBool();
}
}
bool Settings::IsValid()
{
if(_use_file && (_settings->status() != QSettings::NoError)) {
_reason = "File error";
return false;
}
if(LocalEndPoints.count() == 0) {
_reason = "No locally defined end points";
return false;
}
if(WebServer && (!WebServerUrl.isValid() || WebServerUrl.isEmpty())) {
_reason = "Invalid WebServerUrl: " + WebServerUrl.toString();
return false;
}
if(EntryTunnel && (!EntryTunnelUrl.isValid() || EntryTunnelUrl.isEmpty())) {
_reason = "Invalid EntryTunnelUrl: " + EntryTunnelUrl.toString();
return false;
}
if(LeaderId == Id::Zero()) {
_reason = "No leader Id";
return false;
}
if(SubgroupPolicy == -1) {
_reason = "Invalid subgroup policy";
return false;
}
return true;
}
QString Settings::GetError()
{
IsValid();
return _reason;
}
void Settings::ParseUrlList(const QString &name, const QVariant &values,
QList<QUrl> &list)
{
if(values.isNull()) {
return;
}
QVariantList varlist = values.toList();
if(!varlist.empty()) {
foreach(QVariant value, varlist) {
ParseUrl(name, value, list);
}
} else {
ParseUrl(name, values, list);
}
}
inline void Settings::ParseUrl(const QString &name, const QVariant &value,
QList<QUrl> &list)
{
QUrl url(value.toString());
if(url.isValid()) {
list << url;
} else {
qCritical() << "Invalid " << name << ": " << value.toString();
}
}
QUrl Settings::TryParseUrl(const QString &string_rep, const QString &scheme)
{
QUrl url = QUrl(string_rep);
if(url.toString() != string_rep) {
return QUrl();
}
if(url.scheme() != scheme) {
return QUrl();
}
return url;
}
void Settings::Save()
{
if(!_use_file) {
return;
}
QStringList peers;
foreach(QUrl peer, RemotePeers) {
peers << peer.toString();
}
if(!peers.empty()) {
_settings->setValue(Param<Params::RemotePeers>(), peers);
}
QStringList endpoints;
foreach(QUrl endpoint, LocalEndPoints) {
endpoints << endpoint.toString();
}
if(!endpoints.empty()) {
_settings->setValue(Param<Params::LocalEndPoints>(), endpoints);
}
_settings->setValue(Param<Params::LocalNodeCount>(), LocalNodeCount);
_settings->setValue(Param<Params::WebServer>(), WebServer);
_settings->setValue(Param<Params::WebServerUrl>(), WebServerUrl);
_settings->setValue(Param<Params::Console>(), Console);
_settings->setValue(Param<Params::DemoMode>(), DemoMode);
_settings->setValue(Param<Params::Log>(), Log);
_settings->setValue(Param<Params::Multithreading>(), Multithreading);
_settings->setValue(Param<Params::LocalId>(), LocalId.ToString());
_settings->setValue(Param<Params::LeaderId>(), LeaderId.ToString());
_settings->setValue(Param<Params::SubgroupPolicy>(),
Group::PolicyTypeToString(SubgroupPolicy));
}
Settings Settings::CommandLineParse(const QStringList ¶ms, bool actions)
{
QSharedPointer<QxtCommandOptions> options = GetOptions();
options->parse(params);
QSharedPointer<QSettings> settings;
bool file = (options->positional().count() > 0);
if(file) {
settings = QSharedPointer<QSettings>(
new QSettings(options->positional()[0], QSettings::IniFormat));
} else {
settings = QSharedPointer<QSettings>(new QSettings());
if(params.size() == 1) {
settings->setValue("help", true);
}
}
QMultiHash<QString, QVariant> kv_params = options->parameters();
if(kv_params.value("help", false).toBool() && file) {
file = false;
settings = QSharedPointer<QSettings>(new QSettings());
}
foreach(const QString &key, kv_params.uniqueKeys()) {
if(options->value(key).type() == QVariant::String &&
options->value(key).toString().isEmpty())
{
settings->setValue(key, true);
} else {
settings->setValue(key, options->value(key));
}
}
if(options->count(Param<Params::WebServerUrl>()) == 1) {
settings->setValue(Param<Params::WebServer>(), true);
}
if(options->count(Param<Params::EntryTunnelUrl>()) == 1) {
settings->setValue(Param<Params::EntryTunnel>(), true);
}
return Settings(settings, file, actions);
}
QSharedPointer<QxtCommandOptions> Settings::GetOptions()
{
QSharedPointer<QxtCommandOptions> options(new QxtCommandOptions());
options->add(Param<Params::Help>(),
"help (this screen)",
QxtCommandOptions::NoValue);
options->add(Param<Params::RemotePeers>(),
"list of remote peers",
QxtCommandOptions::ValueRequired | QxtCommandOptions::AllowMultiple);
options->add(Param<Params::LocalEndPoints>(),
"list of local end points",
QxtCommandOptions::ValueRequired | QxtCommandOptions::AllowMultiple);
options->add(Param<Params::LocalNodeCount>(),
"number of virtual nodes to start",
QxtCommandOptions::ValueRequired);
options->add(Param<Params::DemoMode>(),
"start in demo mode",
QxtCommandOptions::NoValue);
options->add(Param<Params::SessionType>(),
"the type of session",
QxtCommandOptions::ValueRequired);
options->add(Param<Params::Log>(),
"logging mechanism: stderr, stdout, or a file path",
QxtCommandOptions::ValueRequired);
options->add(Param<Params::Console>(),
"enable console",
QxtCommandOptions::NoValue);
options->add(Param<Params::WebServerUrl>(),
"web server url (enables web server)",
QxtCommandOptions::ValueRequired);
options->add(Param<Params::EntryTunnelUrl>(),
"entry tunnel url (enables entry tunnel)",
QxtCommandOptions::ValueRequired);
options->add(Param<Params::ExitTunnel>(),
"enables exit tunnel",
QxtCommandOptions::NoValue);
options->add(Param<Params::Multithreading>(),
"enables multithreading",
QxtCommandOptions::NoValue);
options->add(Param<Params::LocalId>(),
"160-bit base64 local id",
QxtCommandOptions::ValueRequired);
options->add(Param<Params::LeaderId>(),
"160-bit base64 leader id",
QxtCommandOptions::ValueRequired);
options->add(Param<Params::SubgroupPolicy>(),
"subgroup policy (defining servers)",
QxtCommandOptions::ValueRequired);
options->add(Param<Params::SuperPeer>(),
"sets this peer as a capable super peer",
QxtCommandOptions::NoValue);
return options;
}
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <stdio.h>
#include <ctype.h>
#include <cstring>
#include <vector>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <sys/wait.h>
using namespace std;
//parses the entered command putting each string seperated
//by spaces into a vector passed in by reference
//the function utilizes strtok to do this
void parse(char x[], vector<string> &v){
char* tmp;
//separates the string by spaces
tmp = strtok(x, " ");
while(tmp != NULL){
//stores in the vector
v.push_back(tmp);
//searches for the next " " character
tmp = strtok(NULL, " ");
}
}
//the function returns false if the command passed in
//is "exit" or any spaced variation of it.
//returnd false otherwise
bool isExit(char x[]){
//sets up vars necessary for comparison
string tmp = x;
string hold = "exit";
char spc = ' ';
unsigned int k = 0;
//if the size of the passed in char[] is less than that
//necessary for it to be exit return false
if(tmp.size() < hold.size()){
return false;
}
//check each non-space character if within the first
//four characters any of the characters dont align with "exit" return false
//otherwise count how many more characters there are in the passed in string
//if there are more than 4 return false otherwise return true
//if a space appears when k is > 0 but < 4 return false, this prevents
//bugs like "exi t" from working
for(unsigned int i = 0; i < tmp.size(); i++){
if(tmp.at(i) != spc){
if(k < hold.size() && tmp.at(i) != hold.at(k)){
return false;
}
k++;
}
else if(k > 0 && k < hold.size()){
return false;
}
}
if(k != hold.size()){
return false;
}
else{
return true;
}
}
//traverses the entered list of commands
//and checks to see how many different kinds of
//connectors there are, if there are more than one
//it returns true else returns false
bool multiConn(string x){
int amp = 0;
int ln = 0;
int semi = 0;
int total = 0;
//if any part of the string does not
//align with "exit" returns false, otherwise counts
//all characters after the passed in command
for(unsigned int i = 0; i < x.size(); i++){
if(x.at(i) == '&' && i != x.size()-1){
if(x.at(i+1) == '&'){
amp++;
}
}
if(x.at(i) == '|' && i != x.size()-1){
if(x.at(i+1) == '|'){
ln++;
}
}
if(x.at(i) == ';'){
semi++;
}
}
//calculates the total amount of different connectors
if(amp > 0){
total++;
}
if(semi > 0){
total++;
}
if(ln > 0){
total++;
}
//if more than one return true
if(total > 1){
cerr << "Multiple connector types forbidden" << endl;
return true;
}
//else false
else{
return false;
}
}
//the function searches for the '#' and
//removes anything after that character
string commentRemoval(string x){
int comm = x.find('#');
//if no '#' is found return the entire string
if(comm == -1){
return x;
}
//if the '#' is the first character return nothing
else if(comm == 0){
return "";
}
//otherwise return every thing up to the '#'
else{
return x.substr(0, comm);
}
}
bool isls(char x[]){
string tmp = x;
if(tmp.size() < 2){
return false;
}
if(tmp.at(0) == 'l' && tmp.at(1) == 's'){
return true;
}
return false;
}
bool multiCheck(string x, bool flags[]){
string chk = "alR";
for(unsigned int i = 1; i < x.size(); i++){
if(chk.find(x.at(i)) < 0 || chk.find(x.at(i)) >= x.size()){
return false;
}
else if(x.at(i) == 'a'){
flags[0] = true;
}
else if(x.at(i) == 'l'){
flags[1] = true;
}
else if(x.at(i) == 'R'){
flags[2] = true;
}
}
return true;
}
bool ls_parse(vector<string> cmd, bool flags[], vector<string> &files){
if(cmd.size() < 0){
return false;
}
if(cmd.at(0) != "ls"){
return false;
}
for(unsigned int i = 1; i < cmd.size(); i++){
if(cmd.at(i) == "-a"){
flags[0] = true;
}
else if(cmd.at(i) == "-l"){
flags[1] = true;
}
else if(cmd.at(i) == "-R"){
flags[2] = true;
}
else if(cmd.at(i).at(0) == '-'){
if(!multiCheck(cmd.at(i), flags)){
return false;
}
}
else{
files.push_back(cmd.at(i));
}
}
return true;
}
//this function runs the command using fork and execvp
//and returns once all commands from the entered char[]
//have been executed
void run(char str[]){
//needed to parse with strtok
char* pch;
//holds the bool of if a command executed properly
bool sucs = true;
//holds the return status of a fork/execvp
int status = 0;
//holds the connector used for the current list of comamnds
string connector;
//holds a string version of the passed in char[] for later
//comparing
string strz = str;
//the vector that holds the commands to be converted and executed
vector<string> cmd;
//cbegins breaking the entered commands up by connector
pch = strtok(str, ";");
//if the command is empty return
if(pch==NULL){
return;
}
//if using strtok with ";" changed the strz
//set the connector to be ";"
else if(pch != strz){
connector = ";";
}
//else if strz was unchanged use strtok with "&&"
//if this changes the string is NULL return
//of if strtok changed from the original value of strz set the connector
if(pch == strz){
pch = strtok(str, "&&");
if(pch == NULL){
return;
}
if(pch != strz){
connector = "&&";
}
}
//repeat the above process but with "||" instead of "&&"
if(pch == strz){
pch = strtok(str, "||");
if(pch == NULL){
return;
}
if(pch != strz){
connector = "||";
}
}
//if the pch is not NULL and is the exit command exit the programm
if(pch != NULL && isExit(pch)){
exit(0);
}
//this while loop is where fork and execvp execute commands
while(pch != NULL){
if(isls(pch)){
int pid = fork();
if(pid == 0){
bool flags[3];
flags[0] = false;
flags[1] = false;
flags[2] = false;
bool valid = false;
vector<string> files;
parse(pch, cmd);
valid = ls_parse(cmd, flags, files);
if(!valid){
cerr << "Invalid flag" << endl;
exit(1);
}
else{
cout << flags[0] << " " << flags[1] << " " << flags[2] << endl;
for(unsigned int i = 0; i < files.size(); i++){
cout << files.at(i) << endl;
}
status = 0;
}
cmd.clear();
files.clear();
flags[0] = false;
flags[1] = false;
flags[2] = false;
exit(0);
}
else{
waitpid(-1, &status, 0);
}
}
else{
//fork the programm
int pid = fork();
//if pid is -1 the fork failed so exit
if(pid == -1){
perror("fork");
exit(1);
}
//if the pid is 0 the current id the current process is the child
else if(pid == 0){
//call the parsing function on the command and the cmd vector
//to break it up into command and params
parse(pch, cmd);
//set the size of the dynamic char** that will be passed into execvp
int cmd_size = cmd.size() + 1;
char** argc = new char*[cmd_size];
//for each string in cmd copy it into argc, which will be passed
//into execvp
for(unsigned int i = 0 ; i < cmd.size(); i++ ){
argc[i] = new char[cmd.at(i).size()];
strcpy(argc[i], cmd.at(i).c_str());
}
//set the last value of argc to be NULL so that execvp will work properly
argc[cmd.size()] = NULL;
//call execvp on the first element of argc and the entirety of it
//if it returns -1 it has failed fo print an error and delete
//the dynamically allocated memory
if(-1 == execvp(argc[0], argc)){
perror("execvp");
delete[] argc;
exit(1);
}
}
//otherwise it is the parrent process
else{
//wait for any process to exit, in this case I only created on,
//and store its exit code in status
if(-1 == waitpid(-1, &status, 0)){
perror("waitpid");
exit(1);
}
}
}
//if the value of status is larger than 0
//it failed
if(status > 0){
sucs = false;
}
//otherwise if succeeded
else{
sucs = true;
}
//clear the vector holding the command to execute
cmd.clear();
//run the next command if the connector logic and value of sucs allow it
if((connector=="&&" && sucs) || (connector=="||" && !sucs) || (connector==";")){
pch = strtok(NULL, connector.c_str());
}
//otherwise return
else{
return;
}
//if the next command is not NULL and is exit exit the program
if(pch != NULL && isExit(pch)){
exit(0);
}
}
//if there are no more commands to execute/parse return
return;
}
//main takes in commands and passes them to run to execute
int main(){
//continue until terminated by a conditional branch within run
while(true){
//retrieves the login name
//and checks to make sure there was no error
char* login = getlogin();
if(login == NULL){
perror("getlogin");
}
//sets up the host name variable, maximum of 128 chars
char host[128];
//holds return value of gethostname
int hostFlag;
//sets up input var
string input;
//retrieves the host name and checks for errors
if((hostFlag = gethostname(host, sizeof(host))) == -1){
perror("gethostname");
}
//if both login and gethostname rerurned without error
//cout the login@host
if(login != NULL && hostFlag != -1){
cout << login << "@" << host << "$ ";
}
//otherwise cout vanilla prompt
else{
cout << "$ ";
}
//retrieve user input including spaces
getline(cin, input);
//remove anything that is a comment from the users input
input = commentRemoval(input);
//check for multiple connectors
if(!multiConn(input)){
//determines the size of the input
int input_size = input.size()+1;
//dynamically allocates a char*[] of the size of the input + 1
char* str = new char[input_size];
//copies the input into the char* str[]
strcpy(str, input.c_str());
//calls run on the users entered commands
run(str);
//after running the dynamically allocated memory is deleted
delete[] str;
}
//if there are more than one connector do not run commands
//and cerr error
}
return 0;
}
<commit_msg>fixed ls parsing bug<commit_after>#include <iostream>
#include <stdio.h>
#include <ctype.h>
#include <cstring>
#include <vector>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <sys/wait.h>
using namespace std;
//parses the entered command putting each string seperated
//by spaces into a vector passed in by reference
//the function utilizes strtok to do this
void parse(char x[], vector<string> &v){
char* tmp;
//separates the string by spaces
tmp = strtok(x, " ");
while(tmp != NULL){
//stores in the vector
v.push_back(tmp);
//searches for the next " " character
tmp = strtok(NULL, " ");
}
}
//the function returns false if the command passed in
//is "exit" or any spaced variation of it.
//returnd false otherwise
bool isExit(char x[]){
//sets up vars necessary for comparison
string tmp = x;
string hold = "exit";
char spc = ' ';
unsigned int k = 0;
//if the size of the passed in char[] is less than that
//necessary for it to be exit return false
if(tmp.size() < hold.size()){
return false;
}
//check each non-space character if within the first
//four characters any of the characters dont align with "exit" return false
//otherwise count how many more characters there are in the passed in string
//if there are more than 4 return false otherwise return true
//if a space appears when k is > 0 but < 4 return false, this prevents
//bugs like "exi t" from working
for(unsigned int i = 0; i < tmp.size(); i++){
if(tmp.at(i) != spc){
if(k < hold.size() && tmp.at(i) != hold.at(k)){
return false;
}
k++;
}
else if(k > 0 && k < hold.size()){
return false;
}
}
if(k != hold.size()){
return false;
}
else{
return true;
}
}
//traverses the entered list of commands
//and checks to see how many different kinds of
//connectors there are, if there are more than one
//it returns true else returns false
bool multiConn(string x){
int amp = 0;
int ln = 0;
int semi = 0;
int total = 0;
//if any part of the string does not
//align with "exit" returns false, otherwise counts
//all characters after the passed in command
for(unsigned int i = 0; i < x.size(); i++){
if(x.at(i) == '&' && i != x.size()-1){
if(x.at(i+1) == '&'){
amp++;
}
}
if(x.at(i) == '|' && i != x.size()-1){
if(x.at(i+1) == '|'){
ln++;
}
}
if(x.at(i) == ';'){
semi++;
}
}
//calculates the total amount of different connectors
if(amp > 0){
total++;
}
if(semi > 0){
total++;
}
if(ln > 0){
total++;
}
//if more than one return true
if(total > 1){
cerr << "Multiple connector types forbidden" << endl;
return true;
}
//else false
else{
return false;
}
}
//the function searches for the '#' and
//removes anything after that character
string commentRemoval(string x){
int comm = x.find('#');
//if no '#' is found return the entire string
if(comm == -1){
return x;
}
//if the '#' is the first character return nothing
else if(comm == 0){
return "";
}
//otherwise return every thing up to the '#'
else{
return x.substr(0, comm);
}
}
bool isls(char x[]){
string tmp = x;
if(tmp.size() < 2){
return false;
}
if(tmp.at(0) == 'l' && tmp.at(1) == 's'){
return true;
}
return false;
}
bool multiCheck(string x, bool flags[]){
string chk = "alR";
for(unsigned int i = 1; i < x.size(); i++){
if(chk.find(x.at(i)) < 0 || chk.find(x.at(i)) >= x.size()){
return false;
}
else if(x.at(i) == 'a'){
flags[0] = true;
}
else if(x.at(i) == 'l'){
flags[1] = true;
}
else if(x.at(i) == 'R'){
flags[2] = true;
}
}
return true;
}
bool ls_parse(vector<string> cmd, bool flags[], vector<string> &files){
if(cmd.size() < 0){
return false;
}
if(cmd.at(0) != "ls"){
return false;
}
for(unsigned int i = 1; i < cmd.size(); i++){
if(cmd.at(i) == "-a"){
flags[0] = true;
}
else if(cmd.at(i) == "-l"){
flags[1] = true;
}
else if(cmd.at(i) == "-R"){
flags[2] = true;
}
else if(cmd.at(i) == "-"){
return false;
}
else if(cmd.at(i).at(0) == '-'){
if(!multiCheck(cmd.at(i), flags)){
return false;
}
}
else{
files.push_back(cmd.at(i));
}
}
return true;
}
//this function runs the command using fork and execvp
//and returns once all commands from the entered char[]
//have been executed
void run(char str[]){
//needed to parse with strtok
char* pch;
//holds the bool of if a command executed properly
bool sucs = true;
//holds the return status of a fork/execvp
int status = 0;
//holds the connector used for the current list of comamnds
string connector;
//holds a string version of the passed in char[] for later
//comparing
string strz = str;
//the vector that holds the commands to be converted and executed
vector<string> cmd;
//cbegins breaking the entered commands up by connector
pch = strtok(str, ";");
//if the command is empty return
if(pch==NULL){
return;
}
//if using strtok with ";" changed the strz
//set the connector to be ";"
else if(pch != strz){
connector = ";";
}
//else if strz was unchanged use strtok with "&&"
//if this changes the string is NULL return
//of if strtok changed from the original value of strz set the connector
if(pch == strz){
pch = strtok(str, "&&");
if(pch == NULL){
return;
}
if(pch != strz){
connector = "&&";
}
}
//repeat the above process but with "||" instead of "&&"
if(pch == strz){
pch = strtok(str, "||");
if(pch == NULL){
return;
}
if(pch != strz){
connector = "||";
}
}
//if the pch is not NULL and is the exit command exit the programm
if(pch != NULL && isExit(pch)){
exit(0);
}
//this while loop is where fork and execvp execute commands
while(pch != NULL){
if(isls(pch)){
int pid = fork();
if(pid == 0){
bool flags[3];
flags[0] = false;
flags[1] = false;
flags[2] = false;
bool valid = false;
vector<string> files;
parse(pch, cmd);
valid = ls_parse(cmd, flags, files);
if(!valid){
cerr << "Invalid flag" << endl;
exit(1);
}
else{
cout << flags[0] << " " << flags[1] << " " << flags[2] << endl;
for(unsigned int i = 0; i < files.size(); i++){
cout << files.at(i) << endl;
}
status = 0;
}
cmd.clear();
files.clear();
flags[0] = false;
flags[1] = false;
flags[2] = false;
exit(0);
}
else{
waitpid(-1, &status, 0);
}
}
else{
//fork the programm
int pid = fork();
//if pid is -1 the fork failed so exit
if(pid == -1){
perror("fork");
exit(1);
}
//if the pid is 0 the current id the current process is the child
else if(pid == 0){
//call the parsing function on the command and the cmd vector
//to break it up into command and params
parse(pch, cmd);
//set the size of the dynamic char** that will be passed into execvp
int cmd_size = cmd.size() + 1;
char** argc = new char*[cmd_size];
//for each string in cmd copy it into argc, which will be passed
//into execvp
for(unsigned int i = 0 ; i < cmd.size(); i++ ){
argc[i] = new char[cmd.at(i).size()];
strcpy(argc[i], cmd.at(i).c_str());
}
//set the last value of argc to be NULL so that execvp will work properly
argc[cmd.size()] = NULL;
//call execvp on the first element of argc and the entirety of it
//if it returns -1 it has failed fo print an error and delete
//the dynamically allocated memory
if(-1 == execvp(argc[0], argc)){
perror("execvp");
delete[] argc;
exit(1);
}
}
//otherwise it is the parrent process
else{
//wait for any process to exit, in this case I only created on,
//and store its exit code in status
if(-1 == waitpid(-1, &status, 0)){
perror("waitpid");
exit(1);
}
}
}
//if the value of status is larger than 0
//it failed
if(status > 0){
sucs = false;
}
//otherwise if succeeded
else{
sucs = true;
}
//clear the vector holding the command to execute
cmd.clear();
//run the next command if the connector logic and value of sucs allow it
if((connector=="&&" && sucs) || (connector=="||" && !sucs) || (connector==";")){
pch = strtok(NULL, connector.c_str());
}
//otherwise return
else{
return;
}
//if the next command is not NULL and is exit exit the program
if(pch != NULL && isExit(pch)){
exit(0);
}
}
//if there are no more commands to execute/parse return
return;
}
//main takes in commands and passes them to run to execute
int main(){
//continue until terminated by a conditional branch within run
while(true){
//retrieves the login name
//and checks to make sure there was no error
char* login = getlogin();
if(login == NULL){
perror("getlogin");
}
//sets up the host name variable, maximum of 128 chars
char host[128];
//holds return value of gethostname
int hostFlag;
//sets up input var
string input;
//retrieves the host name and checks for errors
if((hostFlag = gethostname(host, sizeof(host))) == -1){
perror("gethostname");
}
//if both login and gethostname rerurned without error
//cout the login@host
if(login != NULL && hostFlag != -1){
cout << login << "@" << host << "$ ";
}
//otherwise cout vanilla prompt
else{
cout << "$ ";
}
//retrieve user input including spaces
getline(cin, input);
//remove anything that is a comment from the users input
input = commentRemoval(input);
//check for multiple connectors
if(!multiConn(input)){
//determines the size of the input
int input_size = input.size()+1;
//dynamically allocates a char*[] of the size of the input + 1
char* str = new char[input_size];
//copies the input into the char* str[]
strcpy(str, input.c_str());
//calls run on the users entered commands
run(str);
//after running the dynamically allocated memory is deleted
delete[] str;
}
//if there are more than one connector do not run commands
//and cerr error
}
return 0;
}
<|endoftext|>
|
<commit_before>/****************************************************************************
* Copyright (c) 2012-2018 by the DataTransferKit authors *
* All rights reserved. *
* *
* This file is part of the DataTransferKit library. DataTransferKit is *
* distributed under a BSD 3-clause license. For the licensing terms see *
* the LICENSE file in the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#include <DTK_DetailsDistributedSearchTreeImpl.hpp>
#include <Teuchos_UnitTestHarness.hpp>
#include <algorithm> // fill
#include <set>
#include <vector>
TEUCHOS_UNIT_TEST_TEMPLATE_1_DECL( DetailsDistributedSearchTreeImpl,
sort_results, DeviceType )
{
std::vector<int> ids_ = {4, 3, 2, 1, 4, 3, 2, 4, 3, 4};
std::vector<int> sorted_ids = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4};
std::vector<int> offset = {0, 1, 3, 6, 10};
int const n = 10;
int const m = 4;
TEST_EQUALITY( ids_.size(), n );
TEST_EQUALITY( sorted_ids.size(), n );
TEST_EQUALITY( offset.size(), m + 1 );
std::vector<int> results_ = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
std::vector<std::set<int>> sorted_results = {
{3},
{6, 2},
{8, 5, 1},
{9, 7, 4, 0},
};
std::vector<int> ranks_ = {10, 11, 12, 13, 14, 15, 16, 17, 18, 19};
std::vector<std::set<int>> sorted_ranks = {
{13},
{16, 12},
{18, 15, 11},
{19, 17, 14, 10},
};
TEST_EQUALITY( results_.size(), n );
TEST_EQUALITY( ranks_.size(), n );
Kokkos::View<int *, DeviceType> ids( "query_ids", n );
auto ids_host = Kokkos::create_mirror_view( ids );
for ( int i = 0; i < n; ++i )
ids_host( i ) = ids_[i];
Kokkos::deep_copy( ids, ids_host );
Kokkos::View<int *, DeviceType> results( "results", n );
auto results_host = Kokkos::create_mirror_view( results );
for ( int i = 0; i < n; ++i )
results_host( i ) = results_[i];
Kokkos::deep_copy( results, results_host );
Kokkos::View<int *, DeviceType> ranks( "ranks", n );
auto ranks_host = Kokkos::create_mirror_view( ranks );
for ( int i = 0; i < n; ++i )
ranks_host( i ) = ranks_[i];
Kokkos::deep_copy( ranks, ranks_host );
DataTransferKit::Details::DistributedSearchTreeImpl<
DeviceType>::sortResults( ids, results, ranks );
// COMMENT: ids are untouched
Kokkos::deep_copy( ids_host, ids );
TEST_COMPARE_ARRAYS( ids_host, ids_ );
Kokkos::deep_copy( results_host, results );
Kokkos::deep_copy( ranks_host, ranks );
for ( int q = 0; q < m; ++q )
for ( int i = offset[q]; i < offset[q + 1]; ++i )
{
TEST_EQUALITY( sorted_results[q].count( results_host[i] ), 1 );
TEST_EQUALITY( sorted_ranks[q].count( ranks_host[i] ), 1 );
}
Kokkos::View<int *, DeviceType> not_sized_properly( "", m );
TEST_THROW( DataTransferKit::Details::DistributedSearchTreeImpl<
DeviceType>::sortResults( ids, not_sized_properly ),
DataTransferKit::DataTransferKitException );
}
TEUCHOS_UNIT_TEST_TEMPLATE_1_DECL( DetailsDistributedSearchTreeImpl,
count_results, DeviceType )
{
std::vector<int> ids_ref = {4, 3, 2, 1, 4, 3, 2, 4, 3, 4};
std::vector<int> offset_ref = {
0, 0, 1, 3, 6, 10,
};
int const m = 5;
int const nnz = 10;
TEST_EQUALITY( ids_ref.size(), nnz );
TEST_EQUALITY( offset_ref.size(), m + 1 );
Kokkos::View<int *, DeviceType> ids( "query_ids", nnz );
auto ids_host = Kokkos::create_mirror_view( ids );
for ( int i = 0; i < nnz; ++i )
ids_host( i ) = ids_ref[i];
Kokkos::deep_copy( ids, ids_host );
Kokkos::View<int *, DeviceType> offset( "offset" );
DataTransferKit::Details::DistributedSearchTreeImpl<
DeviceType>::countResults( m, ids, offset );
auto offset_host = Kokkos::create_mirror_view( offset );
Kokkos::deep_copy( offset_host, offset );
TEST_COMPARE_ARRAYS( offset_host, offset_ref );
}
template <typename View1, typename View2>
inline void checkViewWasNotAllocated( View1 const &v1, View2 const &v2,
bool &success,
Teuchos::FancyOStream &out )
{
// NOTE: cannot use operator== here because array layout may "change" for
// rank-1 views
TEST_EQUALITY( v1.data(), v2.data() );
TEST_EQUALITY( v1.span(), v2.span() );
TEST_EQUALITY( (int)View1::rank, (int)View2::rank );
TEST_ASSERT( ( std::is_same<typename View1::const_value_type,
typename View2::const_value_type>::value ) );
TEST_ASSERT( ( std::is_same<typename View1::memory_space,
typename View2::memory_space>::value ) );
TEST_EQUALITY( v1.dimension_0(), v2.dimension_0() );
TEST_EQUALITY( v1.dimension_1(), v2.dimension_1() );
TEST_EQUALITY( v1.dimension_2(), v2.dimension_2() );
TEST_EQUALITY( v1.dimension_3(), v2.dimension_3() );
TEST_EQUALITY( v1.dimension_4(), v2.dimension_4() );
TEST_EQUALITY( v1.dimension_5(), v2.dimension_5() );
TEST_EQUALITY( v1.dimension_6(), v2.dimension_6() );
TEST_EQUALITY( v1.dimension_7(), v2.dimension_7() );
}
template <typename View1, typename View2>
inline void checkNewViewWasAllocated( View1 const &v1, View2 const &v2,
bool &success,
Teuchos::FancyOStream &out )
{
TEST_INEQUALITY( v1.data(), v2.data() );
TEST_EQUALITY( (int)View1::rank, (int)View2::rank );
TEST_ASSERT( ( std::is_same<typename View1::const_value_type,
typename View2::const_value_type>::value ) );
TEST_EQUALITY( v1.dimension_0(), v2.dimension_0() );
TEST_EQUALITY( v1.dimension_1(), v2.dimension_1() );
TEST_EQUALITY( v1.dimension_2(), v2.dimension_2() );
TEST_EQUALITY( v1.dimension_3(), v2.dimension_3() );
TEST_EQUALITY( v1.dimension_4(), v2.dimension_4() );
TEST_EQUALITY( v1.dimension_5(), v2.dimension_5() );
TEST_EQUALITY( v1.dimension_6(), v2.dimension_6() );
TEST_EQUALITY( v1.dimension_7(), v2.dimension_7() );
}
TEUCHOS_UNIT_TEST( DetailsDistributedSearchTreeImpl,
create_layout_right_mirror_view )
{
using DataTransferKit::Details::create_layout_right_mirror_view;
using Kokkos::ALL;
using Kokkos::LayoutLeft;
using Kokkos::LayoutRight;
using Kokkos::make_pair;
using Kokkos::subview;
using Kokkos::View;
// rank-1 and not strided -> do not allocate
View<int *, LayoutLeft> u( "u", 255 );
auto u_h = create_layout_right_mirror_view( u );
checkViewWasNotAllocated( u, u_h, success, out );
// right layout -> do not allocate
View<int **, LayoutRight> v( "v", 2, 3 );
auto v_h = create_layout_right_mirror_view( v );
checkViewWasNotAllocated( v, v_h, success, out );
// left layout and rank > 1 -> allocate
View<int **, LayoutLeft> w( "w", 4, 5 );
auto w_h = create_layout_right_mirror_view( w );
checkNewViewWasAllocated( w, w_h, success, out );
// strided layout -> allocate
auto x = subview( v, ALL, 0 );
auto x_h = create_layout_right_mirror_view( x );
checkNewViewWasAllocated( x, x_h, success, out );
// subview is rank-1 and not strided -> do not allocate
auto y = subview( u, make_pair( 8, 16 ) );
auto y_h = create_layout_right_mirror_view( y );
checkViewWasNotAllocated( y, y_h, success, out );
}
// Include the test macros.
#include "DataTransferKit_ETIHelperMacros.h"
// Create the test group
#define UNIT_TEST_GROUP( NODE ) \
using DeviceType##NODE = typename NODE::device_type; \
TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( DetailsDistributedSearchTreeImpl, \
sort_results, DeviceType##NODE ) \
TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( DetailsDistributedSearchTreeImpl, \
count_results, DeviceType##NODE )
// Demangle the types
DTK_ETI_MANGLING_TYPEDEFS()
// Instantiate the tests
DTK_INSTANTIATE_N( UNIT_TEST_GROUP )
<commit_msg>Add tests for sortAndDetermineBufferLayout()<commit_after>/****************************************************************************
* Copyright (c) 2012-2018 by the DataTransferKit authors *
* All rights reserved. *
* *
* This file is part of the DataTransferKit library. DataTransferKit is *
* distributed under a BSD 3-clause license. For the licensing terms see *
* the LICENSE file in the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#include <DTK_DetailsDistributedSearchTreeImpl.hpp>
#include <Teuchos_UnitTestHarness.hpp>
#include <algorithm> // fill
#include <set>
#include <vector>
TEUCHOS_UNIT_TEST_TEMPLATE_1_DECL( DetailsDistributedSearchTreeImpl,
sort_results, DeviceType )
{
std::vector<int> ids_ = {4, 3, 2, 1, 4, 3, 2, 4, 3, 4};
std::vector<int> sorted_ids = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4};
std::vector<int> offset = {0, 1, 3, 6, 10};
int const n = 10;
int const m = 4;
TEST_EQUALITY( ids_.size(), n );
TEST_EQUALITY( sorted_ids.size(), n );
TEST_EQUALITY( offset.size(), m + 1 );
std::vector<int> results_ = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
std::vector<std::set<int>> sorted_results = {
{3},
{6, 2},
{8, 5, 1},
{9, 7, 4, 0},
};
std::vector<int> ranks_ = {10, 11, 12, 13, 14, 15, 16, 17, 18, 19};
std::vector<std::set<int>> sorted_ranks = {
{13},
{16, 12},
{18, 15, 11},
{19, 17, 14, 10},
};
TEST_EQUALITY( results_.size(), n );
TEST_EQUALITY( ranks_.size(), n );
Kokkos::View<int *, DeviceType> ids( "query_ids", n );
auto ids_host = Kokkos::create_mirror_view( ids );
for ( int i = 0; i < n; ++i )
ids_host( i ) = ids_[i];
Kokkos::deep_copy( ids, ids_host );
Kokkos::View<int *, DeviceType> results( "results", n );
auto results_host = Kokkos::create_mirror_view( results );
for ( int i = 0; i < n; ++i )
results_host( i ) = results_[i];
Kokkos::deep_copy( results, results_host );
Kokkos::View<int *, DeviceType> ranks( "ranks", n );
auto ranks_host = Kokkos::create_mirror_view( ranks );
for ( int i = 0; i < n; ++i )
ranks_host( i ) = ranks_[i];
Kokkos::deep_copy( ranks, ranks_host );
DataTransferKit::Details::DistributedSearchTreeImpl<
DeviceType>::sortResults( ids, results, ranks );
// COMMENT: ids are untouched
Kokkos::deep_copy( ids_host, ids );
TEST_COMPARE_ARRAYS( ids_host, ids_ );
Kokkos::deep_copy( results_host, results );
Kokkos::deep_copy( ranks_host, ranks );
for ( int q = 0; q < m; ++q )
for ( int i = offset[q]; i < offset[q + 1]; ++i )
{
TEST_EQUALITY( sorted_results[q].count( results_host[i] ), 1 );
TEST_EQUALITY( sorted_ranks[q].count( ranks_host[i] ), 1 );
}
Kokkos::View<int *, DeviceType> not_sized_properly( "", m );
TEST_THROW( DataTransferKit::Details::DistributedSearchTreeImpl<
DeviceType>::sortResults( ids, not_sized_properly ),
DataTransferKit::DataTransferKitException );
}
TEUCHOS_UNIT_TEST_TEMPLATE_1_DECL( DetailsDistributedSearchTreeImpl,
count_results, DeviceType )
{
std::vector<int> ids_ref = {4, 3, 2, 1, 4, 3, 2, 4, 3, 4};
std::vector<int> offset_ref = {
0, 0, 1, 3, 6, 10,
};
int const m = 5;
int const nnz = 10;
TEST_EQUALITY( ids_ref.size(), nnz );
TEST_EQUALITY( offset_ref.size(), m + 1 );
Kokkos::View<int *, DeviceType> ids( "query_ids", nnz );
auto ids_host = Kokkos::create_mirror_view( ids );
for ( int i = 0; i < nnz; ++i )
ids_host( i ) = ids_ref[i];
Kokkos::deep_copy( ids, ids_host );
Kokkos::View<int *, DeviceType> offset( "offset" );
DataTransferKit::Details::DistributedSearchTreeImpl<
DeviceType>::countResults( m, ids, offset );
auto offset_host = Kokkos::create_mirror_view( offset );
Kokkos::deep_copy( offset_host, offset );
TEST_COMPARE_ARRAYS( offset_host, offset_ref );
}
template <typename View1, typename View2>
inline void checkViewWasNotAllocated( View1 const &v1, View2 const &v2,
bool &success,
Teuchos::FancyOStream &out )
{
// NOTE: cannot use operator== here because array layout may "change" for
// rank-1 views
TEST_EQUALITY( v1.data(), v2.data() );
TEST_EQUALITY( v1.span(), v2.span() );
TEST_EQUALITY( (int)View1::rank, (int)View2::rank );
TEST_ASSERT( ( std::is_same<typename View1::const_value_type,
typename View2::const_value_type>::value ) );
TEST_ASSERT( ( std::is_same<typename View1::memory_space,
typename View2::memory_space>::value ) );
TEST_EQUALITY( v1.dimension_0(), v2.dimension_0() );
TEST_EQUALITY( v1.dimension_1(), v2.dimension_1() );
TEST_EQUALITY( v1.dimension_2(), v2.dimension_2() );
TEST_EQUALITY( v1.dimension_3(), v2.dimension_3() );
TEST_EQUALITY( v1.dimension_4(), v2.dimension_4() );
TEST_EQUALITY( v1.dimension_5(), v2.dimension_5() );
TEST_EQUALITY( v1.dimension_6(), v2.dimension_6() );
TEST_EQUALITY( v1.dimension_7(), v2.dimension_7() );
}
template <typename View1, typename View2>
inline void checkNewViewWasAllocated( View1 const &v1, View2 const &v2,
bool &success,
Teuchos::FancyOStream &out )
{
TEST_INEQUALITY( v1.data(), v2.data() );
TEST_EQUALITY( (int)View1::rank, (int)View2::rank );
TEST_ASSERT( ( std::is_same<typename View1::const_value_type,
typename View2::const_value_type>::value ) );
TEST_EQUALITY( v1.dimension_0(), v2.dimension_0() );
TEST_EQUALITY( v1.dimension_1(), v2.dimension_1() );
TEST_EQUALITY( v1.dimension_2(), v2.dimension_2() );
TEST_EQUALITY( v1.dimension_3(), v2.dimension_3() );
TEST_EQUALITY( v1.dimension_4(), v2.dimension_4() );
TEST_EQUALITY( v1.dimension_5(), v2.dimension_5() );
TEST_EQUALITY( v1.dimension_6(), v2.dimension_6() );
TEST_EQUALITY( v1.dimension_7(), v2.dimension_7() );
}
TEUCHOS_UNIT_TEST( DetailsDistributedSearchTreeImpl,
create_layout_right_mirror_view )
{
using DataTransferKit::Details::create_layout_right_mirror_view;
using Kokkos::ALL;
using Kokkos::LayoutLeft;
using Kokkos::LayoutRight;
using Kokkos::make_pair;
using Kokkos::subview;
using Kokkos::View;
// rank-1 and not strided -> do not allocate
View<int *, LayoutLeft> u( "u", 255 );
auto u_h = create_layout_right_mirror_view( u );
checkViewWasNotAllocated( u, u_h, success, out );
// right layout -> do not allocate
View<int **, LayoutRight> v( "v", 2, 3 );
auto v_h = create_layout_right_mirror_view( v );
checkViewWasNotAllocated( v, v_h, success, out );
// left layout and rank > 1 -> allocate
View<int **, LayoutLeft> w( "w", 4, 5 );
auto w_h = create_layout_right_mirror_view( w );
checkNewViewWasAllocated( w, w_h, success, out );
// strided layout -> allocate
auto x = subview( v, ALL, 0 );
auto x_h = create_layout_right_mirror_view( x );
checkNewViewWasAllocated( x, x_h, success, out );
// subview is rank-1 and not strided -> do not allocate
auto y = subview( u, make_pair( 8, 16 ) );
auto y_h = create_layout_right_mirror_view( y );
checkViewWasNotAllocated( y, y_h, success, out );
}
void checkBufferLayout( std::vector<int> const &ranks,
std::vector<int> const &permute_ref,
std::vector<int> const &unique_ref,
std::vector<int> const &counts_ref,
std::vector<int> const &offsets_ref, bool &success,
Teuchos::FancyOStream &out )
{
std::vector<int> permute( ranks.size() );
std::vector<int> unique;
std::vector<int> counts;
std::vector<int> offsets;
DataTransferKit::Details::sortAndDetermineBufferLayout(
Kokkos::View<int const *, Kokkos::HostSpace,
Kokkos::MemoryTraits<Kokkos::Unmanaged>>( ranks.data(),
ranks.size() ),
Kokkos::View<int *, Kokkos::HostSpace,
Kokkos::MemoryTraits<Kokkos::Unmanaged>>( permute.data(),
permute.size() ),
unique, counts, offsets );
TEST_COMPARE_ARRAYS( permute_ref, permute );
TEST_COMPARE_ARRAYS( unique_ref, unique );
TEST_COMPARE_ARRAYS( counts_ref, counts );
TEST_COMPARE_ARRAYS( offsets_ref, offsets );
}
TEUCHOS_UNIT_TEST( DetailsDistributor, sort_and_determine_buffer_layout )
{
checkBufferLayout( {}, {}, {}, {}, {0}, success, out );
checkBufferLayout( {2, 2}, {0, 1}, {2}, {2}, {0, 2}, success, out );
checkBufferLayout( {3, 3, 2, 3, 2, 1}, {0, 1, 3, 2, 4, 5}, {3, 2, 1},
{3, 2, 1}, {0, 3, 5, 6}, success, out );
checkBufferLayout( {1, 2, 3, 2, 3, 3}, {5, 3, 0, 4, 1, 2}, {3, 2, 1},
{3, 2, 1}, {0, 3, 5, 6}, success, out );
checkBufferLayout( {0, 1, 2, 3}, {3, 2, 1, 0}, {3, 2, 1, 0}, {1, 1, 1, 1},
{0, 1, 2, 3, 4}, success, out );
}
// Include the test macros.
#include "DataTransferKit_ETIHelperMacros.h"
// Create the test group
#define UNIT_TEST_GROUP( NODE ) \
using DeviceType##NODE = typename NODE::device_type; \
TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( DetailsDistributedSearchTreeImpl, \
sort_results, DeviceType##NODE ) \
TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( DetailsDistributedSearchTreeImpl, \
count_results, DeviceType##NODE )
// Demangle the types
DTK_ETI_MANGLING_TYPEDEFS()
// Instantiate the tests
DTK_INSTANTIATE_N( UNIT_TEST_GROUP )
<|endoftext|>
|
<commit_before>#include "sendcoinsdialog.h"
#include "ui_sendcoinsdialog.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "addressbookpage.h"
#include "optionsmodel.h"
#include "sendcoinsentry.h"
#include "guiutil.h"
#include "askpassphrasedialog.h"
#include "base58.h"
#include <QMessageBox>
#include <QLocale>
#include <QTextDocument>
#include <QScrollBar>
SendCoinsDialog::SendCoinsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SendCoinsDialog),
model(0)
{
ui->setupUi(this);
#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
ui->addButton->setIcon(QIcon());
ui->clearButton->setIcon(QIcon());
ui->sendButton->setIcon(QIcon());
#endif
addEntry();
connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry()));
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
fNewRecipientAllowed = true;
}
void SendCoinsDialog::setModel(WalletModel *model)
{
this->model = model;
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
entry->setModel(model);
}
}
if(model && model->getOptionsModel())
{
setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance());
connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64)));
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
}
}
SendCoinsDialog::~SendCoinsDialog()
{
delete ui;
}
void SendCoinsDialog::on_sendButton_clicked()
{
QList<SendCoinsRecipient> recipients;
bool valid = true;
if(!model)
return;
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
if(entry->validate())
{
recipients.append(entry->getValue());
}
else
{
valid = false;
}
}
}
if(!valid || recipients.isEmpty())
{
return;
}
// Format confirmation message
QStringList formatted;
foreach(const SendCoinsRecipient &rcp, recipients)
{
formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), Qt::escape(rcp.label), rcp.address));
}
fNewRecipientAllowed = false;
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"),
tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval != QMessageBox::Yes)
{
fNewRecipientAllowed = true;
return;
}
WalletModel::UnlockContext ctx(model->requestUnlock());
if(!ctx.isValid())
{
// Unlock wallet was cancelled
fNewRecipientAllowed = true;
return;
}
WalletModel::SendCoinsReturn sendstatus = model->sendCoins(recipients);
switch(sendstatus.status)
{
case WalletModel::InvalidAddress:
QMessageBox::warning(this, tr("Send Coins"),
tr("The recipient address is not valid, please recheck."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::InvalidAmount:
QMessageBox::warning(this, tr("Send Coins"),
tr("The amount to pay must be larger than 0."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::AmountExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("The amount exceeds your balance."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::AmountWithFeeExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("The total exceeds your balance when the %1 transaction fee is included.").
arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, sendstatus.fee)),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::DuplicateAddress:
QMessageBox::warning(this, tr("Send Coins"),
tr("Duplicate address found, can only send to each address once per send operation."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::TransactionCreationFailed:
QMessageBox::warning(this, tr("Send Coins"),
tr("Error: Transaction creation failed."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::TransactionCommitFailed:
QMessageBox::warning(this, tr("Send Coins"),
tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::Aborted: // User aborted, nothing to do
break;
case WalletModel::OK:
accept();
break;
}
fNewRecipientAllowed = true;
}
void SendCoinsDialog::clear()
{
// Remove entries until only one left
while(ui->entries->count())
{
delete ui->entries->takeAt(0)->widget();
}
addEntry();
updateRemoveEnabled();
ui->sendButton->setDefault(true);
}
void SendCoinsDialog::reject()
{
clear();
}
void SendCoinsDialog::accept()
{
clear();
}
SendCoinsEntry *SendCoinsDialog::addEntry()
{
SendCoinsEntry *entry = new SendCoinsEntry(this);
entry->setModel(model);
ui->entries->addWidget(entry);
connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*)));
updateRemoveEnabled();
// Focus the field, so that entry can start immediately
entry->clear();
entry->setFocus();
ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint());
QCoreApplication::instance()->processEvents();
QScrollBar* bar = ui->scrollArea->verticalScrollBar();
if(bar)
bar->setSliderPosition(bar->maximum());
return entry;
}
void SendCoinsDialog::updateRemoveEnabled()
{
// Remove buttons are enabled as soon as there is more than one send-entry
bool enabled = (ui->entries->count() > 1);
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
entry->setRemoveEnabled(enabled);
}
}
setupTabChain(0);
}
void SendCoinsDialog::removeEntry(SendCoinsEntry* entry)
{
delete entry;
updateRemoveEnabled();
}
QWidget *SendCoinsDialog::setupTabChain(QWidget *prev)
{
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
prev = entry->setupTabChain(prev);
}
}
QWidget::setTabOrder(prev, ui->addButton);
QWidget::setTabOrder(ui->addButton, ui->sendButton);
return ui->sendButton;
}
void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv)
{
if(!fNewRecipientAllowed)
return;
SendCoinsEntry *entry = 0;
// Replace the first entry if it is still unused
if(ui->entries->count() == 1)
{
SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());
if(first->isClear())
{
entry = first;
}
}
if(!entry)
{
entry = addEntry();
}
entry->setValue(rv);
}
bool SendCoinsDialog::handleURI(const QString &uri)
{
SendCoinsRecipient rv;
// URI has to be valid
if (GUIUtil::parseBitcoinURI(uri, &rv))
{
CBitcoinAddress address(rv.address.toStdString());
if (!address.IsValid())
return false;
pasteEntry(rv);
return true;
}
return false;
}
void SendCoinsDialog::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance)
{
Q_UNUSED(stake);
Q_UNUSED(unconfirmedBalance);
Q_UNUSED(immatureBalance);
if(!model || !model->getOptionsModel())
return;
int unit = model->getOptionsModel()->getDisplayUnit();
ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance));
}
void SendCoinsDialog::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update labelBalance with the current balance and the current unit
ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->getBalance()));
}
}
<commit_msg>Update sendcoinsdialog.cpp<commit_after>#include "sendcoinsdialog.h"
#include "ui_sendcoinsdialog.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "addressbookpage.h"
#include "optionsmodel.h"
#include "sendcoinsentry.h"
#include "guiutil.h"
#include "askpassphrasedialog.h"
#include "base58.h"
#include <QMessageBox>
#include <QLocale>
#include <QTextDocument>
#include <QScrollBar>
SendCoinsDialog::SendCoinsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SendCoinsDialog),
model(0)
{
ui->setupUi(this);
#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
ui->addButton->setIcon(QIcon());
ui->clearButton->setIcon(QIcon());
ui->sendButton->setIcon(QIcon());
#endif
addEntry();
connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry()));
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
fNewRecipientAllowed = true;
}
void SendCoinsDialog::setModel(WalletModel *model)
{
this->model = model;
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
entry->setModel(model);
}
}
if(model && model->getOptionsModel())
{
setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance());
connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64)));
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
}
}
SendCoinsDialog::~SendCoinsDialog()
{
delete ui;
}
void SendCoinsDialog::on_sendButton_clicked()
{
QList<SendCoinsRecipient> recipients;
bool valid = true;
if(!model)
return;
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
if(entry->validate())
{
recipients.append(entry->getValue());
}
else
{
valid = false;
}
}
}
if(!valid || recipients.isEmpty())
{
return;
}
// Format confirmation message
QStringList formatted;
foreach(const SendCoinsRecipient &rcp, recipients)
{
#if QT_VERSION < 0x050000
formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), Qt::escape(rcp.label), rcp.address));
#else
formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), rcp.label.toHtmlEscaped(), rcp.address));
#endif
}
fNewRecipientAllowed = false;
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"),
tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval != QMessageBox::Yes)
{
fNewRecipientAllowed = true;
return;
}
WalletModel::UnlockContext ctx(model->requestUnlock());
if(!ctx.isValid())
{
// Unlock wallet was cancelled
fNewRecipientAllowed = true;
return;
}
WalletModel::SendCoinsReturn sendstatus = model->sendCoins(recipients);
switch(sendstatus.status)
{
case WalletModel::InvalidAddress:
QMessageBox::warning(this, tr("Send Coins"),
tr("The recipient address is not valid, please recheck."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::InvalidAmount:
QMessageBox::warning(this, tr("Send Coins"),
tr("The amount to pay must be larger than 0."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::AmountExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("The amount exceeds your balance."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::AmountWithFeeExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("The total exceeds your balance when the %1 transaction fee is included.").
arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, sendstatus.fee)),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::DuplicateAddress:
QMessageBox::warning(this, tr("Send Coins"),
tr("Duplicate address found, can only send to each address once per send operation."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::TransactionCreationFailed:
QMessageBox::warning(this, tr("Send Coins"),
tr("Error: Transaction creation failed."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::TransactionCommitFailed:
QMessageBox::warning(this, tr("Send Coins"),
tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::Aborted: // User aborted, nothing to do
break;
case WalletModel::OK:
accept();
break;
}
fNewRecipientAllowed = true;
}
void SendCoinsDialog::clear()
{
// Remove entries until only one left
while(ui->entries->count())
{
delete ui->entries->takeAt(0)->widget();
}
addEntry();
updateRemoveEnabled();
ui->sendButton->setDefault(true);
}
void SendCoinsDialog::reject()
{
clear();
}
void SendCoinsDialog::accept()
{
clear();
}
SendCoinsEntry *SendCoinsDialog::addEntry()
{
SendCoinsEntry *entry = new SendCoinsEntry(this);
entry->setModel(model);
ui->entries->addWidget(entry);
connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*)));
updateRemoveEnabled();
// Focus the field, so that entry can start immediately
entry->clear();
entry->setFocus();
ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint());
QCoreApplication::instance()->processEvents();
QScrollBar* bar = ui->scrollArea->verticalScrollBar();
if(bar)
bar->setSliderPosition(bar->maximum());
return entry;
}
void SendCoinsDialog::updateRemoveEnabled()
{
// Remove buttons are enabled as soon as there is more than one send-entry
bool enabled = (ui->entries->count() > 1);
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
entry->setRemoveEnabled(enabled);
}
}
setupTabChain(0);
}
void SendCoinsDialog::removeEntry(SendCoinsEntry* entry)
{
delete entry;
updateRemoveEnabled();
}
QWidget *SendCoinsDialog::setupTabChain(QWidget *prev)
{
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
prev = entry->setupTabChain(prev);
}
}
QWidget::setTabOrder(prev, ui->addButton);
QWidget::setTabOrder(ui->addButton, ui->sendButton);
return ui->sendButton;
}
void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv)
{
if(!fNewRecipientAllowed)
return;
SendCoinsEntry *entry = 0;
// Replace the first entry if it is still unused
if(ui->entries->count() == 1)
{
SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());
if(first->isClear())
{
entry = first;
}
}
if(!entry)
{
entry = addEntry();
}
entry->setValue(rv);
}
bool SendCoinsDialog::handleURI(const QString &uri)
{
SendCoinsRecipient rv;
// URI has to be valid
if (GUIUtil::parseBitcoinURI(uri, &rv))
{
CBitcoinAddress address(rv.address.toStdString());
if (!address.IsValid())
return false;
pasteEntry(rv);
return true;
}
return false;
}
void SendCoinsDialog::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance)
{
Q_UNUSED(stake);
Q_UNUSED(unconfirmedBalance);
Q_UNUSED(immatureBalance);
if(!model || !model->getOptionsModel())
return;
int unit = model->getOptionsModel()->getDisplayUnit();
ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance));
}
void SendCoinsDialog::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update labelBalance with the current balance and the current unit
ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->getBalance()));
}
}
<|endoftext|>
|
<commit_before>// Copyright 2017 The Ray Authors.
//
// 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 "ray/rpc/grpc_server.h"
#include <grpcpp/impl/service_type.h>
#include <boost/asio/detail/socket_holder.hpp>
#include "ray/common/ray_config.h"
namespace ray {
namespace rpc {
GrpcServer::GrpcServer(std::string name, const uint32_t port, int num_threads)
: name_(std::move(name)), port_(port), is_closed_(true), num_threads_(num_threads) {
cqs_.resize(num_threads_);
}
void GrpcServer::Run() {
uint32_t specified_port = port_;
std::string server_address("0.0.0.0:" + std::to_string(port_));
int num_retries = RayConfig::instance().grpc_server_num_retries();
while (num_retries >= 0) {
grpc::ServerBuilder builder;
// Disable the SO_REUSEPORT option. We don't need it in ray. If the option is enabled
// (default behavior in grpc), we may see multiple workers listen on the same port and
// the requests sent to this port may be handled by any of the workers.
builder.AddChannelArgument(GRPC_ARG_ALLOW_REUSEPORT, 0);
builder.AddChannelArgument(GRPC_ARG_MAX_SEND_MESSAGE_LENGTH,
RayConfig::instance().max_grpc_message_size());
builder.AddChannelArgument(GRPC_ARG_MAX_RECEIVE_MESSAGE_LENGTH,
RayConfig::instance().max_grpc_message_size());
// TODO(hchen): Add options for authentication.
builder.AddListeningPort(server_address, grpc::InsecureServerCredentials(), &port_);
// Register all the services to this server.
if (services_.empty()) {
RAY_LOG(WARNING) << "No service is found when start grpc server " << name_;
}
for (auto &entry : services_) {
builder.RegisterService(&entry.get());
}
// Get hold of the completion queue used for the asynchronous communication
// with the gRPC runtime.
for (int i = 0; i < num_threads_; i++) {
cqs_[i] = builder.AddCompletionQueue();
}
// Build and start server.
server_ = builder.BuildAndStart();
if (port_ > 0) {
break;
}
usleep(RayConfig::instance().grpc_server_retry_timeout_milliseconds() * 1000);
num_retries--;
}
// If the grpc server failed to bind the port, the `port_` will be set to 0.
RAY_CHECK(port_ > 0)
<< "Port " << specified_port
<< " specified by caller already in use. Try passing node_manager_port=... into "
"ray.init() to pick a specific port";
RAY_LOG(INFO) << name_ << " server started, listening on port " << port_ << ".";
// Create calls for all the server call factories.
for (auto &entry : server_call_factories_) {
for (int i = 0; i < num_threads_; i++) {
// Create a buffer of 100 calls for each RPC handler.
// TODO(edoakes): a small buffer should be fine and seems to have better
// performance, but we don't currently handle backpressure on the client.
for (int j = 0; j < 100; j++) {
entry->CreateCall();
}
}
}
// Start threads that polls incoming requests.
for (int i = 0; i < num_threads_; i++) {
polling_threads_.emplace_back(&GrpcServer::PollEventsFromCompletionQueue, this, i);
}
// Set the server as running.
is_closed_ = false;
}
void GrpcServer::RegisterService(GrpcService &service) {
services_.emplace_back(service.GetGrpcService());
for (int i = 0; i < num_threads_; i++) {
service.InitServerCallFactories(cqs_[i], &server_call_factories_);
}
}
void GrpcServer::PollEventsFromCompletionQueue(int index) {
void *tag;
bool ok;
// Keep reading events from the `CompletionQueue` until it's shutdown.
while (cqs_[index]->Next(&tag, &ok)) {
auto *server_call = static_cast<ServerCall *>(tag);
bool delete_call = false;
if (ok) {
switch (server_call->GetState()) {
case ServerCallState::PENDING:
// We've received a new incoming request. Now this call object is used to
// track this request.
server_call->SetState(ServerCallState::PROCESSING);
server_call->HandleRequest();
break;
case ServerCallState::SENDING_REPLY:
// GRPC has sent reply successfully, invoking the callback.
server_call->OnReplySent();
// The rpc call has finished and can be deleted now.
delete_call = true;
break;
default:
RAY_LOG(FATAL) << "Shouldn't reach here.";
break;
}
} else {
// `ok == false` will occur in two situations:
// First, the server has been shut down, the server call's status is PENDING
// Second, server has sent reply to client and failed, the server call's status is
// SENDING_REPLY
if (server_call->GetState() == ServerCallState::SENDING_REPLY) {
server_call->OnReplyFailed();
}
delete_call = true;
}
if (delete_call) {
delete server_call;
}
}
}
} // namespace rpc
} // namespace ray
<commit_msg>Fix Windows build (#8905)<commit_after>// Copyright 2017 The Ray Authors.
//
// 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 "ray/rpc/grpc_server.h"
#include <grpcpp/impl/service_type.h>
#include <unistd.h>
#include <boost/asio/detail/socket_holder.hpp>
#include "ray/common/ray_config.h"
namespace ray {
namespace rpc {
GrpcServer::GrpcServer(std::string name, const uint32_t port, int num_threads)
: name_(std::move(name)), port_(port), is_closed_(true), num_threads_(num_threads) {
cqs_.resize(num_threads_);
}
void GrpcServer::Run() {
uint32_t specified_port = port_;
std::string server_address("0.0.0.0:" + std::to_string(port_));
int num_retries = RayConfig::instance().grpc_server_num_retries();
while (num_retries >= 0) {
grpc::ServerBuilder builder;
// Disable the SO_REUSEPORT option. We don't need it in ray. If the option is enabled
// (default behavior in grpc), we may see multiple workers listen on the same port and
// the requests sent to this port may be handled by any of the workers.
builder.AddChannelArgument(GRPC_ARG_ALLOW_REUSEPORT, 0);
builder.AddChannelArgument(GRPC_ARG_MAX_SEND_MESSAGE_LENGTH,
RayConfig::instance().max_grpc_message_size());
builder.AddChannelArgument(GRPC_ARG_MAX_RECEIVE_MESSAGE_LENGTH,
RayConfig::instance().max_grpc_message_size());
// TODO(hchen): Add options for authentication.
builder.AddListeningPort(server_address, grpc::InsecureServerCredentials(), &port_);
// Register all the services to this server.
if (services_.empty()) {
RAY_LOG(WARNING) << "No service is found when start grpc server " << name_;
}
for (auto &entry : services_) {
builder.RegisterService(&entry.get());
}
// Get hold of the completion queue used for the asynchronous communication
// with the gRPC runtime.
for (int i = 0; i < num_threads_; i++) {
cqs_[i] = builder.AddCompletionQueue();
}
// Build and start server.
server_ = builder.BuildAndStart();
if (port_ > 0) {
break;
}
usleep(RayConfig::instance().grpc_server_retry_timeout_milliseconds() * 1000);
num_retries--;
}
// If the grpc server failed to bind the port, the `port_` will be set to 0.
RAY_CHECK(port_ > 0)
<< "Port " << specified_port
<< " specified by caller already in use. Try passing node_manager_port=... into "
"ray.init() to pick a specific port";
RAY_LOG(INFO) << name_ << " server started, listening on port " << port_ << ".";
// Create calls for all the server call factories.
for (auto &entry : server_call_factories_) {
for (int i = 0; i < num_threads_; i++) {
// Create a buffer of 100 calls for each RPC handler.
// TODO(edoakes): a small buffer should be fine and seems to have better
// performance, but we don't currently handle backpressure on the client.
for (int j = 0; j < 100; j++) {
entry->CreateCall();
}
}
}
// Start threads that polls incoming requests.
for (int i = 0; i < num_threads_; i++) {
polling_threads_.emplace_back(&GrpcServer::PollEventsFromCompletionQueue, this, i);
}
// Set the server as running.
is_closed_ = false;
}
void GrpcServer::RegisterService(GrpcService &service) {
services_.emplace_back(service.GetGrpcService());
for (int i = 0; i < num_threads_; i++) {
service.InitServerCallFactories(cqs_[i], &server_call_factories_);
}
}
void GrpcServer::PollEventsFromCompletionQueue(int index) {
void *tag;
bool ok;
// Keep reading events from the `CompletionQueue` until it's shutdown.
while (cqs_[index]->Next(&tag, &ok)) {
auto *server_call = static_cast<ServerCall *>(tag);
bool delete_call = false;
if (ok) {
switch (server_call->GetState()) {
case ServerCallState::PENDING:
// We've received a new incoming request. Now this call object is used to
// track this request.
server_call->SetState(ServerCallState::PROCESSING);
server_call->HandleRequest();
break;
case ServerCallState::SENDING_REPLY:
// GRPC has sent reply successfully, invoking the callback.
server_call->OnReplySent();
// The rpc call has finished and can be deleted now.
delete_call = true;
break;
default:
RAY_LOG(FATAL) << "Shouldn't reach here.";
break;
}
} else {
// `ok == false` will occur in two situations:
// First, the server has been shut down, the server call's status is PENDING
// Second, server has sent reply to client and failed, the server call's status is
// SENDING_REPLY
if (server_call->GetState() == ServerCallState::SENDING_REPLY) {
server_call->OnReplyFailed();
}
delete_call = true;
}
if (delete_call) {
delete server_call;
}
}
}
} // namespace rpc
} // namespace ray
<|endoftext|>
|
<commit_before>#include <iostream>
#include <vector>
#include <algorithm>
#include <cassert>
#include "viennautils/enum_pp.hpp"
VIENNAUTILS_ENUM_PP(element_tag, (edge,1),(triangle),(rectangle,4));
template <typename T>
void foo(T my_tag)
{
std::cout << "name of enum: " << viennautils::enum_pp::name<T>() << std::endl;
for ( element_tag::ToStringMap::const_iterator it = viennautils::enum_pp::to_string_map<T>().begin()
; it != viennautils::enum_pp::to_string_map<T>().end()
; ++it
)
{
std::cout << "value: " << it->first << " name: " << it->second << std::endl;
}
std::cout << "using value 'rectangle' to retrieve string: " << viennautils::enum_pp::to_string(my_tag) << std::endl;
std::cout << "using string \"rectangle\" to retrieve value: " << viennautils::enum_pp::from_string<T>("rectangle") << std::endl;
try
{
T fail = viennautils::enum_pp::from_string<T>("not a valid enum value");
}
catch(std::exception const & e)
{
std::cout << "caught expected exception: " << e.what() << std::endl;
}
}
int main()
{
//notice how T is of type element_tag::type in foo and not element_tag itself
//so the enum itself is associated with the functions that it needs
foo(element_tag::rectangle);
}
<commit_msg>enum_pp_demo example is now removed (forgot to stage it with previous checkin)<commit_after><|endoftext|>
|
<commit_before>#include "..\guid.h"
#include <cassert>
#include <string>
int main()
{
/* api documentation */
// create a guid using the static guid::create_new function
guid g = guid::create_new();
// check if empty
bool empty = g.empty();
// convert the guid to a string like xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
std::string s = g.to_string('a');
// Create a guid using guid::create member function
guid g2;
g2.create();
/* tests */
guid g3("2AC3E955-939F-4756-8BC1-940BB7C882C3");
assert(g3.empty() == false);
assert(g3 != g);
assert(!(g3 == g));
std::string s2 = g3.to_string();
assert(s2.compare("{2AC3E955-939F-4756-8BC1-940BB7C882C3}") == 0);
assert(g3.to_string(guid_format::uppercase_no_brackets).compare("2AC3E955-939F-4756-8BC1-940BB7C882C3") == 0);
guid g4(g3);
assert(g4 == g3);
guid g5 = g4;
assert(g5 == g4);
guid g6;
g6 = g5;
assert(g6 == g5);
g6.swap(g);
assert(g6 != g5);
assert(g == g3);
guid g7 = guid::create_new();
assert(g7.empty() == false);
guid g8;
assert(g8.empty());
g8.create();
assert(g8.empty() == false);
guid g9(g8);
assert(g9 == g8);
g9.create();
assert(g9 == g8);
guid g10("2AC3E955-939F-4756-8BC1-940BB7C882C3");
assert(g10.empty() == false);
}<commit_msg>space<commit_after>#include "..\guid.h"
#include <cassert>
#include <string>
int main()
{
/* api documentation */
// create a guid using the static guid::create_new function
guid g = guid::create_new();
// check if empty
bool empty = g.empty();
// convert the guid to a string like xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
std::string s = g.to_string('a');
// Create a guid using guid::create member function
guid g2;
g2.create();
/* tests */
guid g3("2AC3E955-939F-4756-8BC1-940BB7C882C3");
assert(g3.empty() == false);
assert(g3 != g);
assert(!(g3 == g));
std::string s2 = g3.to_string();
assert(s2.compare("{2AC3E955-939F-4756-8BC1-940BB7C882C3}") == 0);
assert(g3.to_string(guid_format::uppercase_no_brackets).compare("2AC3E955-939F-4756-8BC1-940BB7C882C3") == 0);
guid g4(g3);
assert(g4 == g3);
guid g5 = g4;
assert(g5 == g4);
guid g6;
g6 = g5;
assert(g6 == g5);
g6.swap(g);
assert(g6 != g5);
assert(g == g3);
guid g7 = guid::create_new();
assert(g7.empty() == false);
guid g8;
assert(g8.empty());
g8.create();
assert(g8.empty() == false);
guid g9(g8);
assert(g9 == g8);
g9.create();
assert(g9 == g8);
guid g10("2AC3E955-939F-4756-8BC1-940BB7C882C3");
assert(g10.empty() == false);
}<|endoftext|>
|
<commit_before>// belle http example
#include "../../../include/belle.hh"
namespace Belle = OB::Belle;
#include <ctime>
#include <string>
#include <sstream>
#include <iomanip>
#include <iostream>
// prototypes
std::string http_routes(Belle::Server::Http_Routes& routes);
// return string containing all http routes
std::string http_routes(Belle::Server::Http_Routes& routes)
{
std::stringstream res;
for (auto const& e : routes)
{
res << "Route: " << (*e).first << "\nMethod:";
for (auto const& m : (*e).second)
{
if (static_cast<Belle::Method>(m.first) == Belle::Method::unknown)
{
res << " All";
}
else
{
res << " " << Belle::http::to_string(static_cast<Belle::Method>(m.first));
}
}
res << "\n\n";
}
return res.str();
}
int main(int argc, char *argv[])
{
// init the server
Belle::Server app;
// set the listening address
std::string address {"127.0.0.1"};
app.address(address);
// set the listening port
int port {8080};
app.port(port);
// disable websocket upgrades
app.websocket(false);
// set the number of threads to 2
app.threads(2);
// enable serving static files from a public directory
// if the path is relative, make sure to run the program
// in the right working directory
app.public_dir("../public");
// set default http headers
Belle::Headers headers;
headers.set(Belle::Header::server, "Belle");
headers.set(Belle::Header::cache_control, "private; max-age=0");
app.http_headers(headers);
// handle the following signals
app.signals({SIGINT, SIGTERM});
// set the on signal callback
app.on_signal([&](auto ec, auto sig)
{
// print out the signal received
std::cerr << "\nSignal " << sig << "\n";
// get the io_context and safely stop the server
app.io().stop();
});
// handle route GET '/'
app.on_http("/", Belle::Method::get, [&](Belle::Server::Http_Ctx& ctx)
{
// the response string
std::string res {R"(
<a href="/">home</a><br>
<a href="/method">methods</a><br>
<a href="/params?key=value&blank=&query=test&page=2">query parameters</a><br>
<a href="/418">regex route</a><br>
<a href="/error">custom error</a><br>
<a href="/index.html">static page</a><br>
)"};
// set http response headers
ctx.res.set("content-type", "text/html");
// set the http status code
ctx.res.result(200);
// set the http body
ctx.res.body() = res;
});
// handle route '/method'
// matches all methods
app.on_http("/method", [](Belle::Server::Http_Ctx& ctx)
{
// set http response headers
ctx.res.set("content-type", "text/plain");
// set the http status code
ctx.res.result(200);
// get the request method type
std::string method {ctx.req.method_string()};
// echo back the matched http method
ctx.res.body() = "Method: " + method + "\n";
});
// handle route POST '/'
app.on_http("/post", Belle::Method::post, [](Belle::Server::Http_Ctx& ctx)
{
// set http response headers
ctx.res.set("content-type", "text/plain");
// set the http status code
ctx.res.result(200);
// echo back the request body
ctx.res.body() = "Body: " + ctx.req.body() + "\n";
});
// handle route GET '/params' with query parameters
// ex. http://localhost:8080/?q=test&page=2
app.on_http("/params", Belle::Method::get, [](Belle::Server::Http_Ctx& ctx)
{
// stringstream to hold the response
std::stringstream res;
res << "Query Parameters:\n";
// access the query parameters
for (auto const& e : ctx.req.params())
{
// add each key value pair to the response
res << e.first << " | " << e.second << "\n";
}
// set http response headers
ctx.res.set("content-type", "text/plain");
// set the http status code
ctx.res.result(200);
// echo back the query parameters
ctx.res.body() = res.str();
});
// handle route GET '/<400-500 errors>' with query parameters
// match a regex url
// ex. http://localhost:8080/404
app.on_http("^/([45]{1}[0-9]{2})$", Belle::Method::get, [](Belle::Server::Http_Ctx& ctx)
{
// access the url regex capture groups
// using req.url() which is a vector of strings
// index 0 contains the full matched url
// index 1 to n contain the value of the capture groups if any
std::string match {ctx.req.url().at(1)};
// set http response headers
ctx.res.set("content-type", "text/plain");
// set the http status code
ctx.res.result(200);
// echo back the captured url path
ctx.res.body() = "match: " + match;
});
// handle an error
app.on_http("/error", Belle::Method::get, [](Belle::Server::Http_Ctx& ctx)
{
// trigger the custom error callback
throw 500;
});
// set custom error callback
app.on_http_error([&](Belle::Server::Http_Ctx& ctx)
{
// stringstream to hold the response
std::stringstream res; res
<< "Status: " << ctx.res.result_int() << "\n"
<< "Reason: " << ctx.res.result() << "\n";
// set http response headers
ctx.res.set("content-type", "text/plain");
// echo the http status code
ctx.res.body() = res.str();
});
// set http connect callback
// called at the beginning of every request
app.on_http_connect([&](Belle::Server::Http_Ctx& ctx)
{
// print notification
std::cerr << "New Request!\n";
});
// set http disconnect callback
// called at the end of every request
app.on_http_disconnect([&](Belle::Server::Http_Ctx& ctx)
{
// access http request headers
std::string ip {std::string(ctx.req["X-Real-IP"]).empty() ? "localhost" : ctx.req["X-Real-IP"]};
std::string ua {std::string(ctx.req["user-agent"])};
std::string rf {std::string(ctx.req["referer"])};
// get the current time
std::time_t t {std::time(nullptr)};
std::tm tm {*std::localtime(&t)};
// log output
std::cerr
<< "[" << std::put_time(&tm, "%H:%M:%S %e %b %Y") << "] "
<< "[" << ip << "] "
<< "[" << ctx.res.result_int() << "] "
<< "[" << ctx.req.method() << "] "
<< "[" << ctx.req.target().to_string() << "] "
<< "[" << rf << "] "
<< "[" << ua << "]\n\n";
});
// print out the address and port
// along with all registered http routes
// followed by the log output
std::cout
<< "Server: " << address << ":" << port << "\n\n"
<< "Navigate to the following url:\n"
<< " http://127.0.0.1:8080/\n\n"
<< "Try running the following commands:\n"
<< " curl -X PUT http://127.0.0.1:8080/method\n"
<< " curl -X POST --data 'post body message here' http://127.0.0.1:8080/post\n\n"
<< "Begin Routes>\n\n"
<< http_routes(app.http_routes())
<< "Begin Log>\n\n";
// start the server
app.listen();
// the server blocks until a signal is received
return 0;
}
<commit_msg>update http example<commit_after>// belle http example
#include "../../../include/belle.hh"
namespace Belle = OB::Belle;
#include <ctime>
#include <string>
#include <sstream>
#include <iomanip>
#include <iostream>
// prototypes
std::string http_routes(Belle::Server::Http_Routes& routes);
// return string containing all http routes
std::string http_routes(Belle::Server::Http_Routes& routes)
{
std::stringstream res;
for (auto const& e : routes)
{
res << "Route: " << (*e).first << "\nMethod:";
for (auto const& m : (*e).second)
{
if (static_cast<Belle::Method>(m.first) == Belle::Method::unknown)
{
res << " ALL";
}
else
{
res << " " << Belle::http::to_string(static_cast<Belle::Method>(m.first));
}
}
res << "\n\n";
}
return res.str();
}
int main(int argc, char *argv[])
{
// init the server
Belle::Server app;
// set the listening address
std::string address {"127.0.0.1"};
app.address(address);
// set the listening port
int port {8080};
app.port(port);
// set the number of threads
// default value is 1 single thread
app.threads(std::thread::hardware_concurrency());
// multithreading can be enabled on an http only server
// websocket upgrades must be disabled to use multithreading
// the websocket channel implementation is not thread safe
// default value is true
app.websocket(false);
// enable serving static files from a public directory
// if the path is relative, make sure to run the program
// in the right working directory
app.public_dir("../public");
// set default http headers
Belle::Headers headers;
headers.set(Belle::Header::server, "Belle");
headers.set(Belle::Header::cache_control, "private; max-age=0");
app.http_headers(headers);
// handle the following signals
app.signals({SIGINT, SIGTERM});
// set the on signal callback
app.on_signal([&](auto ec, auto sig)
{
// print out the signal received
std::cerr << "\nSignal " << sig << "\n";
// get the io_context and safely stop the server
app.io().stop();
});
// handle route GET '/'
app.on_http("/", Belle::Method::get, [](Belle::Server::Http_Ctx& ctx)
{
// the response string
std::string res {R"(
<a href="/">home</a><br>
<a href="/method">methods</a><br>
<a href="/params?key=value&blank=&query=test&page=2">query parameters</a><br>
<a href="/regex/hello">regex route</a><br>
<a href="/error">custom error</a><br>
<a href="/index.html">static page</a><br>
)"};
// set http response headers
ctx.res.set("content-type", "text/html");
// set the http status code
// the http status code can be either an integer or
// its respective enum representation
// the default status is 200 OK
ctx.res.result(Belle::Status::ok);
// set the http body
ctx.res.body() = std::move(res);
});
// handle route ALL '/method'
// matches all methods
app.on_http("/method", [](Belle::Server::Http_Ctx& ctx)
{
// get the request method type as a string
std::stringstream res; res
<< "HTTP Method\n"
<< "method: " << ctx.req.method_string() << "\n";
// set http response headers
ctx.res.set("content-type", "text/plain");
// set the http status code
ctx.res.result(Belle::Status::ok);
// echo back the matched http method
ctx.res.body() = res.str();
});
// handle route POST '/post'
// echo back the posted data
app.on_http("/post", Belle::Method::post, [](Belle::Server::Http_Ctx& ctx)
{
// get the request body data
std::stringstream res; res
<< "Post Data\n"
<< "Body: " << ctx.req.body() << "\n";
// set http response headers
ctx.res.set("content-type", "text/plain");
// set the http status code
ctx.res.result(Belle::Status::ok);
// echo back the request body
ctx.res.body() = res.str();
});
// handle route GET '/params'
// with query parameters
// ex. http://localhost:8080/params?q=test&page=2
app.on_http("/params", Belle::Method::get, [](Belle::Server::Http_Ctx& ctx)
{
// stringstream to hold the response
std::stringstream res;
res << "Query Parameters\n";
// access the query parameters
for (auto const& [key, val] : ctx.req.params())
{
// add each key value pair to the response
res << key << " | " << val << "\n";
}
// set http response headers
ctx.res.set("content-type", "text/plain");
// set the http status code
ctx.res.result(Belle::Status::ok);
// echo back the query parameters
ctx.res.body() = res.str();
});
// handle route GET '/regex/([a-z]+)'
// match a regex url
// one or more lowercase characters in the range of a-z
// ex. http://localhost:8080/regex/hello
// ex. http://localhost:8080/regex/belle
app.on_http("^/regex/([a-z]+)$", Belle::Method::get, [](Belle::Server::Http_Ctx& ctx)
{
// access the url regex capture groups
// using req.url() which is a vector of strings
// index 0 contains the matched url, minus any query parameters
// index 1 to n contain the value of the capture groups if any
// the full url with query parameters is in req.target()
std::string url {ctx.req.url().at(0)};
std::string match {ctx.req.url().at(1)};
// stringstream to hold the response
std::stringstream res; res
<< "Regex Captures\n"
<< "url: " << url << "\n"
<< "match: " << match << "\n";
// set http response headers
ctx.res.set("content-type", "text/plain");
// set the http status code
ctx.res.result(Belle::Status::ok);
// echo back the captured url path
ctx.res.body() = res.str();
});
// trigger the custom error callback
app.on_http("/error", Belle::Method::get, [](Belle::Server::Http_Ctx& ctx)
{
// the thrown value sets the http status code and
// calls the Belle::Server::on_http_error callback
// the http status code can be either an integer or
// its respective enum representation
throw Belle::Status::internal_server_error;
});
// set custom error callback
app.on_http_error([](Belle::Server::Http_Ctx& ctx)
{
// stringstream to hold the response
// get the http status code represented as an int and string
std::stringstream res; res
<< "Custom Error\n"
<< "Status: " << ctx.res.result_int() << "\n"
<< "Reason: " << ctx.res.result() << "\n";
// set http response headers
ctx.res.set("content-type", "text/plain");
// send the custom error response
ctx.res.body() = res.str();
});
// set http connect callback
// called at the beginning of every request
app.on_http_connect([](Belle::Server::Http_Ctx& ctx)
{
// print notification
std::cerr << "New Request!\n";
});
// set http disconnect callback
// called at the end of every request
app.on_http_disconnect([](Belle::Server::Http_Ctx& ctx)
{
// access http request headers
std::string ip {std::string(ctx.req["X-Real-IP"]).empty() ? "localhost" : ctx.req["X-Real-IP"]};
std::string ua {std::string(ctx.req["user-agent"])};
std::string rf {std::string(ctx.req["referer"])};
// get the current time
std::time_t t {std::time(nullptr)};
std::tm tm {*std::localtime(&t)};
// log output
std::cerr
// the current timestamp
<< "[" << std::put_time(&tm, "%H:%M:%S %e %b %Y") << "] "
// the ip address
<< "[" << ip << "] "
// the http status code as an integer
<< "[" << ctx.res.result_int() << "] "
// the http method as a string
<< "[" << ctx.req.method_string() << "] "
// the full request url as a string
<< "[" << ctx.req.target().to_string() << "] "
// the http referer header
<< "[" << rf << "] "
// the http user-agent header
<< "[" << ua << "]\n\n";
});
// print out the address and port
// along with all registered http routes
// followed by the log output
std::cout
<< "Server: " << address << ":" << port << "\n\n"
<< "Navigate to the following url:\n"
<< " http://" << address << ":" << port << "/\n\n"
<< "Try running the following commands:\n"
<< " curl -X PUT http://" << address << ":" << port << "/method\n"
<< " curl -X POST --data 'post body message here' http://"
<< address << ":" << port << "/post\n\n"
<< "Begin Routes>\n\n"
<< http_routes(app.http_routes())
<< "Begin Log>\n\n";
// start the server
app.listen();
// the server blocks until a signal is received
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-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 "irc.h"
#include "net.h"
#include "strlcpy.h"
#include "base58.h"
using namespace std;
using namespace boost;
int nGotIRCAddresses = 0;
void ThreadIRCSeed2(void* parg);
#pragma pack(push, 1)
struct ircaddr
{
struct in_addr ip;
short port;
};
#pragma pack(pop)
string EncodeAddress(const CService& addr)
{
struct ircaddr tmp;
if (addr.GetInAddr(&tmp.ip))
{
tmp.port = htons(addr.GetPort());
vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp));
return string("u") + EncodeBase58Check(vch);
}
return "";
}
bool DecodeAddress(string str, CService& addr)
{
vector<unsigned char> vch;
if (!DecodeBase58Check(str.substr(1), vch))
return false;
struct ircaddr tmp;
if (vch.size() != sizeof(tmp))
return false;
memcpy(&tmp, &vch[0], sizeof(tmp));
addr = CService(tmp.ip, ntohs(tmp.port));
return true;
}
static bool Send(SOCKET hSocket, const char* pszSend)
{
if (strstr(pszSend, "PONG") != pszSend)
printf("IRC SENDING: %s\n", pszSend);
const char* psz = pszSend;
const char* pszEnd = psz + strlen(psz);
while (psz < pszEnd)
{
int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL);
if (ret < 0)
return false;
psz += ret;
}
return true;
}
bool RecvLineIRC(SOCKET hSocket, string& strLine)
{
loop
{
bool fRet = RecvLine(hSocket, strLine);
if (fRet)
{
if (fShutdown)
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() >= 1 && vWords[0] == "PING")
{
strLine[1] = 'O';
strLine += '\r';
Send(hSocket, strLine.c_str());
continue;
}
}
return fRet;
}
}
int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL)
{
loop
{
string strLine;
strLine.reserve(10000);
if (!RecvLineIRC(hSocket, strLine))
return 0;
printf("IRC %s\n", strLine.c_str());
if (psz1 && strLine.find(psz1) != string::npos)
return 1;
if (psz2 && strLine.find(psz2) != string::npos)
return 2;
if (psz3 && strLine.find(psz3) != string::npos)
return 3;
if (psz4 && strLine.find(psz4) != string::npos)
return 4;
}
}
bool Wait(int nSeconds)
{
if (fShutdown)
return false;
printf("IRC waiting %d seconds to reconnect\n", nSeconds);
for (int i = 0; i < nSeconds; i++)
{
if (fShutdown)
return false;
Sleep(1000);
}
return true;
}
bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet)
{
strRet.clear();
loop
{
string strLine;
if (!RecvLineIRC(hSocket, strLine))
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 2)
continue;
if (vWords[1] == psz1)
{
printf("IRC %s\n", strLine.c_str());
strRet = strLine;
return true;
}
}
}
bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet)
{
Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str());
string strLine;
if (!RecvCodeLine(hSocket, "302", strLine))
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 4)
return false;
string str = vWords[3];
if (str.rfind("@") == string::npos)
return false;
string strHost = str.substr(str.rfind("@")+1);
// Hybrid IRC used by lfnet always returns IP when you userhost yourself,
// but in case another IRC is ever used this should work.
printf("GetIPFromIRC() got userhost %s\n", strHost.c_str());
CNetAddr addr(strHost, true);
if (!addr.IsValid())
return false;
ipRet = addr;
return true;
}
void ThreadIRCSeed(void* parg)
{
// Make this thread recognisable as the IRC seeding thread
RenameThread("bitcoin-ircseed");
try
{
ThreadIRCSeed2(parg);
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "ThreadIRCSeed()");
} catch (...) {
PrintExceptionContinue(NULL, "ThreadIRCSeed()");
}
printf("ThreadIRCSeed exited\n");
}
void ThreadIRCSeed2(void* parg)
{
// Don't connect to IRC if we won't use IPv4 connections.
if (IsLimited(NET_IPV4))
return;
// ... or if we won't make outbound connections and won't accept inbound ones.
if (mapArgs.count("-connect") && fNoListen)
return;
// ... or if IRC is not enabled.
if (!GetBoolArg("-irc", true))
return;
printf("ThreadIRCSeed started\n");
int nErrorWait = 10;
int nRetryWait = 10;
int nNameRetry = 0;
while (!fShutdown)
{
CService addrConnect("188.122.74.140", 6667); // eu.undernet.org
CService addrIRC("irc.rizon.net", 6667, true);
if (addrIRC.IsValid())
addrConnect = addrIRC;
SOCKET hSocket;
if (!ConnectSocket(addrConnect, hSocket))
{
printf("IRC connect failed\n");
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname"))
{
closesocket(hSocket);
hSocket = INVALID_SOCKET;
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
CNetAddr addrIPv4("1.2.3.4"); // arbitrary IPv4 address to make GetLocal prefer IPv4 addresses
CService addrLocal;
string strMyName;
// Don't use our IP as our nick if we're not listening
// or if it keeps failing because the nick is already in use.
if (!fNoListen && GetLocal(addrLocal, &addrIPv4) && nNameRetry<3)
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
if (strMyName == "")
strMyName = strprintf("x%"PRI64u"", GetRand(1000000000));
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str());
int nRet = RecvUntil(hSocket, " 004 ", " 433 ");
if (nRet != 1)
{
closesocket(hSocket);
hSocket = INVALID_SOCKET;
if (nRet == 2)
{
printf("IRC name already in use\n");
nNameRetry++;
Wait(10);
continue;
}
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
nNameRetry = 0;
Sleep(500);
// Get our external IP from the IRC server and re-nick before joining the channel
CNetAddr addrFromIRC;
if (GetIPFromIRC(hSocket, strMyName, addrFromIRC))
{
printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToString().c_str());
// Don't use our IP as our nick if we're not listening
if (!fNoListen && addrFromIRC.IsRoutable())
{
// IRC lets you to re-nick
AddLocal(addrFromIRC, LOCAL_IRC);
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
}
}
if (fTestNet) {
Send(hSocket, "JOIN #CryptogenicBullionTEST2\r");
Send(hSocket, "WHO #CryptogenicBullionTEST2\r");
} else {
// randomly join #CryptogenicBullion00-#CryptogenicBullion05
// int channel_number = GetRandInt(5);
// Channel number is always 0 for initial release
int channel_number = 0;
Send(hSocket, strprintf("JOIN #CryptogenicBullion%02d\r", channel_number).c_str());
Send(hSocket, strprintf("WHO #CryptogenicBullion%02d\r", channel_number).c_str());
}
int64 nStart = GetTime();
string strLine;
strLine.reserve(10000);
while (!fShutdown && RecvLineIRC(hSocket, strLine))
{
if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':')
continue;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 2)
continue;
char pszName[10000];
pszName[0] = '\0';
if (vWords[1] == "352" && vWords.size() >= 8)
{
// index 7 is limited to 16 characters
// could get full length name at index 10, but would be different from join messages
strlcpy(pszName, vWords[7].c_str(), sizeof(pszName));
printf("IRC got who\n");
}
if (vWords[1] == "JOIN" && vWords[0].size() > 1)
{
// :username!username@50000007.F000000B.90000002.IP JOIN :#channelname
strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName));
if (strchr(pszName, '!'))
*strchr(pszName, '!') = '\0';
printf("IRC got join\n");
}
if (pszName[0] == 'u')
{
CAddress addr;
if (DecodeAddress(pszName, addr))
{
addr.nTime = GetAdjustedTime();
if (addrman.Add(addr, addrConnect, 51 * 60))
printf("IRC got new address: %s\n", addr.ToString().c_str());
nGotIRCAddresses++;
}
else
{
printf("IRC decode failed\n");
}
}
}
closesocket(hSocket);
hSocket = INVALID_SOCKET;
if (GetTime() - nStart > 20 * 60)
{
nErrorWait /= 3;
nRetryWait /= 3;
}
nRetryWait = nRetryWait * 11 / 10;
if (!Wait(nRetryWait += 60))
return;
}
}
#ifdef TEST
int main(int argc, char *argv[])
{
WSADATA wsadata;
if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR)
{
printf("Error at WSAStartup()\n");
return false;
}
ThreadIRCSeed(NULL);
WSACleanup();
return 0;
}
#endif
<commit_msg>Fix IRC Bans<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-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 "irc.h"
#include "net.h"
#include "strlcpy.h"
#include "base58.h"
using namespace std;
using namespace boost;
int nGotIRCAddresses = 0;
void ThreadIRCSeed2(void* parg);
#pragma pack(push, 1)
struct ircaddr
{
struct in_addr ip;
short port;
};
#pragma pack(pop)
string EncodeAddress(const CService& addr)
{
struct ircaddr tmp;
if (addr.GetInAddr(&tmp.ip))
{
tmp.port = htons(addr.GetPort());
vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp));
return string("u") + EncodeBase58Check(vch);
}
return "";
}
bool DecodeAddress(string str, CService& addr)
{
vector<unsigned char> vch;
if (!DecodeBase58Check(str.substr(1), vch))
return false;
struct ircaddr tmp;
if (vch.size() != sizeof(tmp))
return false;
memcpy(&tmp, &vch[0], sizeof(tmp));
addr = CService(tmp.ip, ntohs(tmp.port));
return true;
}
static bool Send(SOCKET hSocket, const char* pszSend)
{
if (strstr(pszSend, "PONG") != pszSend)
printf("IRC SENDING: %s\n", pszSend);
const char* psz = pszSend;
const char* pszEnd = psz + strlen(psz);
while (psz < pszEnd)
{
int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL);
if (ret < 0)
return false;
psz += ret;
}
return true;
}
bool RecvLineIRC(SOCKET hSocket, string& strLine)
{
loop
{
bool fRet = RecvLine(hSocket, strLine);
if (fRet)
{
if (fShutdown)
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() >= 1 && vWords[0] == "PING")
{
strLine[1] = 'O';
strLine += '\r';
Send(hSocket, strLine.c_str());
continue;
}
}
return fRet;
}
}
int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL)
{
loop
{
string strLine;
strLine.reserve(10000);
if (!RecvLineIRC(hSocket, strLine))
return 0;
printf("IRC %s\n", strLine.c_str());
if (psz1 && strLine.find(psz1) != string::npos)
return 1;
if (psz2 && strLine.find(psz2) != string::npos)
return 2;
if (psz3 && strLine.find(psz3) != string::npos)
return 3;
if (psz4 && strLine.find(psz4) != string::npos)
return 4;
}
}
bool Wait(int nSeconds)
{
if (fShutdown)
return false;
printf("IRC waiting %d seconds to reconnect\n", nSeconds);
for (int i = 0; i < nSeconds; i++)
{
if (fShutdown)
return false;
Sleep(1000);
}
return true;
}
bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet)
{
strRet.clear();
loop
{
string strLine;
if (!RecvLineIRC(hSocket, strLine))
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 2)
continue;
if (vWords[1] == psz1)
{
printf("IRC %s\n", strLine.c_str());
strRet = strLine;
return true;
}
}
}
bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet)
{
Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str());
string strLine;
if (!RecvCodeLine(hSocket, "302", strLine))
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 4)
return false;
string str = vWords[3];
if (str.rfind("@") == string::npos)
return false;
string strHost = str.substr(str.rfind("@")+1);
// Hybrid IRC used by lfnet always returns IP when you userhost yourself,
// but in case another IRC is ever used this should work.
printf("GetIPFromIRC() got userhost %s\n", strHost.c_str());
CNetAddr addr(strHost, true);
if (!addr.IsValid())
return false;
ipRet = addr;
return true;
}
void ThreadIRCSeed(void* parg)
{
// Make this thread recognisable as the IRC seeding thread
RenameThread("bitcoin-ircseed");
try
{
ThreadIRCSeed2(parg);
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "ThreadIRCSeed()");
} catch (...) {
PrintExceptionContinue(NULL, "ThreadIRCSeed()");
}
printf("ThreadIRCSeed exited\n");
}
void ThreadIRCSeed2(void* parg)
{
// Don't connect to IRC if we won't use IPv4 connections.
if (IsLimited(NET_IPV4))
return;
// ... or if we won't make outbound connections and won't accept inbound ones.
if (mapArgs.count("-connect") && fNoListen)
return;
// ... or if IRC is not enabled.
if (!GetBoolArg("-irc", true))
return;
printf("ThreadIRCSeed started\n");
int nErrorWait = 10;
int nRetryWait = 10;
int nNameRetry = 0;
while (!fShutdown)
{
CService addrConnect("173.246.103.92", 6667); // eu.undernet.org
CService addrIRC("pelican.heliacal.net", 6667, true);
if (addrIRC.IsValid())
addrConnect = addrIRC;
SOCKET hSocket;
if (!ConnectSocket(addrConnect, hSocket))
{
printf("IRC connect failed\n");
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname"))
{
closesocket(hSocket);
hSocket = INVALID_SOCKET;
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
CNetAddr addrIPv4("1.2.3.4"); // arbitrary IPv4 address to make GetLocal prefer IPv4 addresses
CService addrLocal;
string strMyName;
// Don't use our IP as our nick if we're not listening
// or if it keeps failing because the nick is already in use.
if (!fNoListen && GetLocal(addrLocal, &addrIPv4) && nNameRetry<3)
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
if (strMyName == "")
strMyName = strprintf("x%"PRI64u"", GetRand(1000000000));
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str());
int nRet = RecvUntil(hSocket, " 004 ", " 433 ");
if (nRet != 1)
{
closesocket(hSocket);
hSocket = INVALID_SOCKET;
if (nRet == 2)
{
printf("IRC name already in use\n");
nNameRetry++;
Wait(10);
continue;
}
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
nNameRetry = 0;
Sleep(500);
// Get our external IP from the IRC server and re-nick before joining the channel
CNetAddr addrFromIRC;
if (GetIPFromIRC(hSocket, strMyName, addrFromIRC))
{
printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToString().c_str());
// Don't use our IP as our nick if we're not listening
if (!fNoListen && addrFromIRC.IsRoutable())
{
// IRC lets you to re-nick
AddLocal(addrFromIRC, LOCAL_IRC);
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
}
}
if (fTestNet) {
Send(hSocket, "JOIN #CGBullionTEST2\r");
Send(hSocket, "WHO #CGBullionTEST2\r");
} else {
// randomly join #CryptogenicBullion00-#CryptogenicBullion05
// int channel_number = GetRandInt(5);
// Channel number is always 0 for initial release
int channel_number = 0;
Send(hSocket, strprintf("JOIN #CGBullion%02d\r", channel_number).c_str());
Send(hSocket, strprintf("WHO #CGBullion%02d\r", channel_number).c_str());
}
int64 nStart = GetTime();
string strLine;
strLine.reserve(10000);
while (!fShutdown && RecvLineIRC(hSocket, strLine))
{
if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':')
continue;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 2)
continue;
char pszName[10000];
pszName[0] = '\0';
if (vWords[1] == "352" && vWords.size() >= 8)
{
// index 7 is limited to 16 characters
// could get full length name at index 10, but would be different from join messages
strlcpy(pszName, vWords[7].c_str(), sizeof(pszName));
printf("IRC got who\n");
}
if (vWords[1] == "JOIN" && vWords[0].size() > 1)
{
// :username!username@50000007.F000000B.90000002.IP JOIN :#channelname
strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName));
if (strchr(pszName, '!'))
*strchr(pszName, '!') = '\0';
printf("IRC got join\n");
}
if (pszName[0] == 'u')
{
CAddress addr;
if (DecodeAddress(pszName, addr))
{
addr.nTime = GetAdjustedTime();
if (addrman.Add(addr, addrConnect, 51 * 60))
printf("IRC got new address: %s\n", addr.ToString().c_str());
nGotIRCAddresses++;
}
else
{
printf("IRC decode failed\n");
}
}
}
closesocket(hSocket);
hSocket = INVALID_SOCKET;
if (GetTime() - nStart > 20 * 60)
{
nErrorWait /= 3;
nRetryWait /= 3;
}
nRetryWait = nRetryWait * 11 / 10;
if (!Wait(nRetryWait += 60))
return;
}
}
#ifdef TEST
int main(int argc, char *argv[])
{
WSADATA wsadata;
if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR)
{
printf("Error at WSAStartup()\n");
return false;
}
ThreadIRCSeed(NULL);
WSACleanup();
return 0;
}
#endif
<|endoftext|>
|
<commit_before>/* RTcmix - Copyright (C) 2000 The RTcmix Development Team
See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
the license to this software and for a DISCLAIMER OF ALL WARRANTIES.
*/
#include <globals.h>
#include <ugens.h>
#include <iostream.h>
#include "../rtstuff/Instrument.h"
#include "../rtstuff/rtdefs.h"
#include "../H/dbug.h"
#include <stdlib.h>
//extern double schedtime;
int Instrument::rtsetoutput(float start, float dur, Instrument *theInst)
{
// I know this is silly, but I wanted nsamps and I wanted it to
// look like "setnote" in orig cmix insts
// DJT: then perhaps we should call it rtsetnote?
// DS: Adding check to be sure rtoutput() did not fail.
if (rtfileit < 0) {
die(theInst->name(), "rtsetoutput: No output file open for this instrument (rtoutput failed?)!");
}
// DJT: made change to increment schedtime here ... not sure how it will work
// if (rtInteractive) {
// #ifdef DBUG
// cout << "rtsetoutput(): rtInteractive mode set\n";
// #endif
// pthread_mutex_lock(&schedtime_lock);
// start += (float)schedtime;
// pthread_mutex_unlock(&schedtime_lock);
// }
theInst->_start = start;
theInst->_dur = dur;
theInst->nsamps = (int)(dur * SR);
return(theInst->nsamps);
}
<commit_msg>Removed unused schedtime code.<commit_after>/* RTcmix - Copyright (C) 2000 The RTcmix Development Team
See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
the license to this software and for a DISCLAIMER OF ALL WARRANTIES.
*/
#include <globals.h>
#include <ugens.h>
#include <iostream.h>
#include "../rtstuff/Instrument.h"
#include "../rtstuff/rtdefs.h"
#include "../H/dbug.h"
#include <stdlib.h>
//extern double schedtime;
int Instrument::rtsetoutput(float start, float dur, Instrument *theInst)
{
// I know this is silly, but I wanted nsamps and I wanted it to
// look like "setnote" in orig cmix insts
// DJT: then perhaps we should call it rtsetnote?
// DS: Adding check to be sure rtoutput() did not fail.
if (rtfileit < 0) {
die(theInst->name(), "rtsetoutput: No output file open for this instrument (rtoutput failed?)!");
}
theInst->_start = start;
theInst->_dur = dur;
theInst->nsamps = (int)(dur * SR);
return(theInst->nsamps);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-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 <map>
#include <openssl/ecdsa.h>
#include <openssl/obj_mac.h>
#include "key.h"
// Generate a private key from just the secret parameter
int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
{
int ok = 0;
BN_CTX *ctx = NULL;
EC_POINT *pub_key = NULL;
if (!eckey) return 0;
const EC_GROUP *group = EC_KEY_get0_group(eckey);
if ((ctx = BN_CTX_new()) == NULL)
goto err;
pub_key = EC_POINT_new(group);
if (pub_key == NULL)
goto err;
if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
goto err;
EC_KEY_set_private_key(eckey,priv_key);
EC_KEY_set_public_key(eckey,pub_key);
ok = 1;
err:
if (pub_key)
EC_POINT_free(pub_key);
if (ctx != NULL)
BN_CTX_free(ctx);
return(ok);
}
// Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
// recid selects which key is recovered
// if check is nonzero, additional checks are performed
int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
{
if (!eckey) return 0;
int ret = 0;
BN_CTX *ctx = NULL;
BIGNUM *x = NULL;
BIGNUM *e = NULL;
BIGNUM *order = NULL;
BIGNUM *sor = NULL;
BIGNUM *eor = NULL;
BIGNUM *field = NULL;
EC_POINT *R = NULL;
EC_POINT *O = NULL;
EC_POINT *Q = NULL;
BIGNUM *rr = NULL;
BIGNUM *zero = NULL;
int n = 0;
int i = recid / 2;
const EC_GROUP *group = EC_KEY_get0_group(eckey);
if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
BN_CTX_start(ctx);
order = BN_CTX_get(ctx);
if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
x = BN_CTX_get(ctx);
if (!BN_copy(x, order)) { ret=-1; goto err; }
if (!BN_mul_word(x, i)) { ret=-1; goto err; }
if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }
field = BN_CTX_get(ctx);
if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
if (check)
{
if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
}
if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
n = EC_GROUP_get_degree(group);
e = BN_CTX_get(ctx);
if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
zero = BN_CTX_get(ctx);
if (!BN_zero(zero)) { ret=-1; goto err; }
if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
rr = BN_CTX_get(ctx);
if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }
sor = BN_CTX_get(ctx);
if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }
eor = BN_CTX_get(ctx);
if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
ret = 1;
err:
if (ctx) {
BN_CTX_end(ctx);
BN_CTX_free(ctx);
}
if (R != NULL) EC_POINT_free(R);
if (O != NULL) EC_POINT_free(O);
if (Q != NULL) EC_POINT_free(Q);
return ret;
}
void CKey::SetCompressedPubKey()
{
EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);
fCompressedPubKey = true;
}
void CKey::Reset()
{
fCompressedPubKey = false;
pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
if (pkey == NULL)
throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed");
fSet = false;
}
CKey::CKey()
{
Reset();
}
CKey::CKey(const CKey& b)
{
pkey = EC_KEY_dup(b.pkey);
if (pkey == NULL)
throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
fSet = b.fSet;
}
CKey& CKey::operator=(const CKey& b)
{
if (!EC_KEY_copy(pkey, b.pkey))
throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed");
fSet = b.fSet;
return (*this);
}
CKey::~CKey()
{
EC_KEY_free(pkey);
}
bool CKey::IsNull() const
{
return !fSet;
}
bool CKey::IsCompressed() const
{
return fCompressedPubKey;
}
void CKey::MakeNewKey(bool fCompressed)
{
if (!EC_KEY_generate_key(pkey))
throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
if (fCompressed)
SetCompressedPubKey();
fSet = true;
}
bool CKey::SetPrivKey(const CPrivKey& vchPrivKey)
{
const unsigned char* pbegin = &vchPrivKey[0];
if (!d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
return false;
fSet = true;
return true;
}
bool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed)
{
EC_KEY_free(pkey);
pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
if (pkey == NULL)
throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed");
if (vchSecret.size() != 32)
throw key_error("CKey::SetSecret() : secret must be 32 bytes");
BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());
if (bn == NULL)
throw key_error("CKey::SetSecret() : BN_bin2bn failed");
if (!EC_KEY_regenerate_key(pkey,bn))
{
BN_clear_free(bn);
throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed");
}
BN_clear_free(bn);
fSet = true;
if (fCompressed || fCompressedPubKey)
SetCompressedPubKey();
return true;
}
CSecret CKey::GetSecret(bool &fCompressed) const
{
CSecret vchRet;
vchRet.resize(32);
const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
int nBytes = BN_num_bytes(bn);
if (bn == NULL)
throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed");
int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
if (n != nBytes)
throw key_error("CKey::GetSecret(): BN_bn2bin failed");
fCompressed = fCompressedPubKey;
return vchRet;
}
CPrivKey CKey::GetPrivKey() const
{
int nSize = i2d_ECPrivateKey(pkey, NULL);
if (!nSize)
throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed");
CPrivKey vchPrivKey(nSize, 0);
unsigned char* pbegin = &vchPrivKey[0];
if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)
throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size");
return vchPrivKey;
}
bool CKey::SetPubKey(const CPubKey& vchPubKey)
{
const unsigned char* pbegin = &vchPubKey.vchPubKey[0];
if (!o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.vchPubKey.size()))
return false;
fSet = true;
if (vchPubKey.vchPubKey.size() == 33)
SetCompressedPubKey();
return true;
}
CPubKey CKey::GetPubKey() const
{
int nSize = i2o_ECPublicKey(pkey, NULL);
if (!nSize)
throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
std::vector<unsigned char> vchPubKey(nSize, 0);
unsigned char* pbegin = &vchPubKey[0];
if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
return CPubKey(vchPubKey);
}
bool CKey::Sign(uint256 hash, std::vector<unsigned char>& vchSig)
{
unsigned int nSize = ECDSA_size(pkey);
vchSig.resize(nSize); // Make sure it is big enough
if (!ECDSA_sign(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], &nSize, pkey))
{
vchSig.clear();
return false;
}
vchSig.resize(nSize); // Shrink to fit actual size
return true;
}
// create a compact signature (65 bytes), which allows reconstructing the used public key
// The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
// The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
// 0x1D = second key with even y, 0x1E = second key with odd y
bool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
{
bool fOk = false;
ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
if (sig==NULL)
return false;
vchSig.clear();
vchSig.resize(65,0);
int nBitsR = BN_num_bits(sig->r);
int nBitsS = BN_num_bits(sig->s);
if (nBitsR <= 256 && nBitsS <= 256)
{
int nRecId = -1;
for (int i=0; i<4; i++)
{
CKey keyRec;
keyRec.fSet = true;
if (fCompressedPubKey)
keyRec.SetCompressedPubKey();
if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)
if (keyRec.GetPubKey() == this->GetPubKey())
{
nRecId = i;
break;
}
}
if (nRecId == -1)
throw key_error("CKey::SignCompact() : unable to construct recoverable key");
vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);
BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)/8]);
BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)/8]);
fOk = true;
}
ECDSA_SIG_free(sig);
return fOk;
}
// reconstruct public key from a compact signature
// This is only slightly more CPU intensive than just verifying it.
// If this function succeeds, the recovered public key is guaranteed to be valid
// (the signature is a valid signature of the given data for that key)
bool CKey::SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
{
if (vchSig.size() != 65)
return false;
int nV = vchSig[0];
if (nV<27 || nV>=35)
return false;
ECDSA_SIG *sig = ECDSA_SIG_new();
BN_bin2bn(&vchSig[1],32,sig->r);
BN_bin2bn(&vchSig[33],32,sig->s);
EC_KEY_free(pkey);
pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
if (nV >= 31)
{
SetCompressedPubKey();
nV -= 4;
}
if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) == 1)
{
fSet = true;
ECDSA_SIG_free(sig);
return true;
}
return false;
}
bool CKey::Verify(uint256 hash, const std::vector<unsigned char>& vchSig)
{
// -1 = error, 0 = bad sig, 1 = good
if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1)
return false;
return true;
}
bool CKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
{
CKey key;
if (!key.SetCompactSignature(hash, vchSig))
return false;
if (GetPubKey() != key.GetPubKey())
return false;
return true;
}
bool CKey::IsValid()
{
if (!fSet)
return false;
bool fCompr;
CSecret secret = GetSecret(fCompr);
CKey key2;
key2.SetSecret(secret, fCompr);
return GetPubKey() == key2.GetPubKey();
}
<commit_msg>fix a memory leak in key.cpp<commit_after>// Copyright (c) 2009-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 <map>
#include <openssl/ecdsa.h>
#include <openssl/obj_mac.h>
#include "key.h"
// Generate a private key from just the secret parameter
int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
{
int ok = 0;
BN_CTX *ctx = NULL;
EC_POINT *pub_key = NULL;
if (!eckey) return 0;
const EC_GROUP *group = EC_KEY_get0_group(eckey);
if ((ctx = BN_CTX_new()) == NULL)
goto err;
pub_key = EC_POINT_new(group);
if (pub_key == NULL)
goto err;
if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
goto err;
EC_KEY_set_private_key(eckey,priv_key);
EC_KEY_set_public_key(eckey,pub_key);
ok = 1;
err:
if (pub_key)
EC_POINT_free(pub_key);
if (ctx != NULL)
BN_CTX_free(ctx);
return(ok);
}
// Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
// recid selects which key is recovered
// if check is nonzero, additional checks are performed
int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
{
if (!eckey) return 0;
int ret = 0;
BN_CTX *ctx = NULL;
BIGNUM *x = NULL;
BIGNUM *e = NULL;
BIGNUM *order = NULL;
BIGNUM *sor = NULL;
BIGNUM *eor = NULL;
BIGNUM *field = NULL;
EC_POINT *R = NULL;
EC_POINT *O = NULL;
EC_POINT *Q = NULL;
BIGNUM *rr = NULL;
BIGNUM *zero = NULL;
int n = 0;
int i = recid / 2;
const EC_GROUP *group = EC_KEY_get0_group(eckey);
if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
BN_CTX_start(ctx);
order = BN_CTX_get(ctx);
if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
x = BN_CTX_get(ctx);
if (!BN_copy(x, order)) { ret=-1; goto err; }
if (!BN_mul_word(x, i)) { ret=-1; goto err; }
if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }
field = BN_CTX_get(ctx);
if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
if (check)
{
if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
}
if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
n = EC_GROUP_get_degree(group);
e = BN_CTX_get(ctx);
if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
zero = BN_CTX_get(ctx);
if (!BN_zero(zero)) { ret=-1; goto err; }
if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
rr = BN_CTX_get(ctx);
if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }
sor = BN_CTX_get(ctx);
if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }
eor = BN_CTX_get(ctx);
if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
ret = 1;
err:
if (ctx) {
BN_CTX_end(ctx);
BN_CTX_free(ctx);
}
if (R != NULL) EC_POINT_free(R);
if (O != NULL) EC_POINT_free(O);
if (Q != NULL) EC_POINT_free(Q);
return ret;
}
void CKey::SetCompressedPubKey()
{
EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);
fCompressedPubKey = true;
}
void CKey::Reset()
{
fCompressedPubKey = false;
if (pkey != NULL)
EC_KEY_free(pkey);
pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
if (pkey == NULL)
throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed");
fSet = false;
}
CKey::CKey()
{
pkey = NULL;
Reset();
}
CKey::CKey(const CKey& b)
{
pkey = EC_KEY_dup(b.pkey);
if (pkey == NULL)
throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
fSet = b.fSet;
}
CKey& CKey::operator=(const CKey& b)
{
if (!EC_KEY_copy(pkey, b.pkey))
throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed");
fSet = b.fSet;
return (*this);
}
CKey::~CKey()
{
EC_KEY_free(pkey);
}
bool CKey::IsNull() const
{
return !fSet;
}
bool CKey::IsCompressed() const
{
return fCompressedPubKey;
}
void CKey::MakeNewKey(bool fCompressed)
{
if (!EC_KEY_generate_key(pkey))
throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
if (fCompressed)
SetCompressedPubKey();
fSet = true;
}
bool CKey::SetPrivKey(const CPrivKey& vchPrivKey)
{
const unsigned char* pbegin = &vchPrivKey[0];
if (!d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
return false;
fSet = true;
return true;
}
bool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed)
{
EC_KEY_free(pkey);
pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
if (pkey == NULL)
throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed");
if (vchSecret.size() != 32)
throw key_error("CKey::SetSecret() : secret must be 32 bytes");
BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());
if (bn == NULL)
throw key_error("CKey::SetSecret() : BN_bin2bn failed");
if (!EC_KEY_regenerate_key(pkey,bn))
{
BN_clear_free(bn);
throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed");
}
BN_clear_free(bn);
fSet = true;
if (fCompressed || fCompressedPubKey)
SetCompressedPubKey();
return true;
}
CSecret CKey::GetSecret(bool &fCompressed) const
{
CSecret vchRet;
vchRet.resize(32);
const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
int nBytes = BN_num_bytes(bn);
if (bn == NULL)
throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed");
int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
if (n != nBytes)
throw key_error("CKey::GetSecret(): BN_bn2bin failed");
fCompressed = fCompressedPubKey;
return vchRet;
}
CPrivKey CKey::GetPrivKey() const
{
int nSize = i2d_ECPrivateKey(pkey, NULL);
if (!nSize)
throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed");
CPrivKey vchPrivKey(nSize, 0);
unsigned char* pbegin = &vchPrivKey[0];
if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)
throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size");
return vchPrivKey;
}
bool CKey::SetPubKey(const CPubKey& vchPubKey)
{
const unsigned char* pbegin = &vchPubKey.vchPubKey[0];
if (!o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.vchPubKey.size()))
return false;
fSet = true;
if (vchPubKey.vchPubKey.size() == 33)
SetCompressedPubKey();
return true;
}
CPubKey CKey::GetPubKey() const
{
int nSize = i2o_ECPublicKey(pkey, NULL);
if (!nSize)
throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
std::vector<unsigned char> vchPubKey(nSize, 0);
unsigned char* pbegin = &vchPubKey[0];
if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
return CPubKey(vchPubKey);
}
bool CKey::Sign(uint256 hash, std::vector<unsigned char>& vchSig)
{
unsigned int nSize = ECDSA_size(pkey);
vchSig.resize(nSize); // Make sure it is big enough
if (!ECDSA_sign(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], &nSize, pkey))
{
vchSig.clear();
return false;
}
vchSig.resize(nSize); // Shrink to fit actual size
return true;
}
// create a compact signature (65 bytes), which allows reconstructing the used public key
// The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
// The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
// 0x1D = second key with even y, 0x1E = second key with odd y
bool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
{
bool fOk = false;
ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
if (sig==NULL)
return false;
vchSig.clear();
vchSig.resize(65,0);
int nBitsR = BN_num_bits(sig->r);
int nBitsS = BN_num_bits(sig->s);
if (nBitsR <= 256 && nBitsS <= 256)
{
int nRecId = -1;
for (int i=0; i<4; i++)
{
CKey keyRec;
keyRec.fSet = true;
if (fCompressedPubKey)
keyRec.SetCompressedPubKey();
if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)
if (keyRec.GetPubKey() == this->GetPubKey())
{
nRecId = i;
break;
}
}
if (nRecId == -1)
throw key_error("CKey::SignCompact() : unable to construct recoverable key");
vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);
BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)/8]);
BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)/8]);
fOk = true;
}
ECDSA_SIG_free(sig);
return fOk;
}
// reconstruct public key from a compact signature
// This is only slightly more CPU intensive than just verifying it.
// If this function succeeds, the recovered public key is guaranteed to be valid
// (the signature is a valid signature of the given data for that key)
bool CKey::SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
{
if (vchSig.size() != 65)
return false;
int nV = vchSig[0];
if (nV<27 || nV>=35)
return false;
ECDSA_SIG *sig = ECDSA_SIG_new();
BN_bin2bn(&vchSig[1],32,sig->r);
BN_bin2bn(&vchSig[33],32,sig->s);
EC_KEY_free(pkey);
pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
if (nV >= 31)
{
SetCompressedPubKey();
nV -= 4;
}
if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) == 1)
{
fSet = true;
ECDSA_SIG_free(sig);
return true;
}
return false;
}
bool CKey::Verify(uint256 hash, const std::vector<unsigned char>& vchSig)
{
// -1 = error, 0 = bad sig, 1 = good
if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1)
return false;
return true;
}
bool CKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
{
CKey key;
if (!key.SetCompactSignature(hash, vchSig))
return false;
if (GetPubKey() != key.GetPubKey())
return false;
return true;
}
bool CKey::IsValid()
{
if (!fSet)
return false;
bool fCompr;
CSecret secret = GetSecret(fCompr);
CKey key2;
key2.SetSecret(secret, fCompr);
return GetPubKey() == key2.GetPubKey();
}
<|endoftext|>
|
<commit_before>/**
* This file is part of Slideshow.
* Copyright (C) 2008-2012 David Sveningsson <ext@sidvind.com>
*
* Slideshow 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.
*
* Slideshow 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 Slideshow. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "log.hpp"
#include "ptr.h"
#include "exception.h"
#include <stdarg.h>
#include <cstdlib>
#include <cstring>
#include <memory> /* for auto_ptr */
#include <errno.h>
#include <time.h>
#include <sys/types.h>
#include <sys/un.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <portable/asprintf.h>
#include <portable/file.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef WIN32
# include "win32.h"
#endif
#ifdef HAVE_SYSLOG
# include <syslog.h>
int syslog_severity[5] = {
LOG_DEBUG,
LOG_INFO,
LOG_NOTICE,
LOG_WARNING,
LOG_ERR
};
#endif /* HAVE_SYSLOG */
typedef std::vector<std::pair<Destination*, Severity>> vector;
typedef vector::iterator iterator;
static vector destinations;
FileDestination::FileDestination(const char* filename)
: _fp(NULL)
, _autoclose(true) {
FILE* fp = fopen(filename, "a");
if ( !fp ){
fprintf(stderr, "Failed to open logfile '%s' ! Fatal error!\n", filename);
exit(1);
}
}
FileDestination::FileDestination(FILE* fp)
: _fp(fp)
, _autoclose(false) {
if ( !fp ){
fprintf(stderr, "Failed to read fp! Fatal error!\n");
exit(1);
}
}
FileDestination::~FileDestination(){
if ( _autoclose ){
fclose(_fp);
}
}
void FileDestination::write(const char* content, const char* decorated) const {
fputs(decorated, _fp);
fflush(_fp);
}
FIFODestination::FIFODestination(const char* filename)
: _filename(NULL)
, _fp(NULL) {
_filename = strdup(filename);
mkfifo(filename, 0600);
FILE* fp = fopen(filename, "w");
if ( !fp ){
fprintf(stderr, "Failed to open logfile '%s' ! Fatal error!\n", filename);
exit(1);
}
}
FIFODestination::~FIFODestination(){
fclose(_fp);
unlink(_filename);
free(_filename);
}
void FIFODestination::write(const char* content, const char* decorated) const {
fputs(decorated, _fp);
fflush(_fp);
}
SocketDestination::SocketDestination(int socket)
: _socket(socket) {
}
SocketDestination::~SocketDestination(){
close(_socket);
}
void SocketDestination::write(const char* content, const char* decorated) const {
send(_socket, decorated, strlen(decorated), 0);
}
#ifdef HAVE_SYSLOG
SyslogDestination::SyslogDestination(){
/* @todo only a single instance of syslog may be opened */
openlog(PACKAGE, 0, LOG_DAEMON);
}
SyslogDestination::~SyslogDestination(){
closelog();
}
void SyslogDestination::write(const char* content, const char* decorated) const {
syslog(syslog_severity[severity], content);
}
#endif /* HAVE_SYSLOG */
UDSServer::UDSServer(const char* filename)
: _filename(NULL)
, _socket(-1) {
_filename = strdup(filename);
struct sockaddr_un address;
socklen_t address_length;
_socket = socket(PF_UNIX, SOCK_STREAM, 0);
unlink(filename);
address.sun_family = AF_UNIX;
address_length = (socklen_t)sizeof(address.sun_family) +
(socklen_t)sprintf(address.sun_path, "%s", filename);
bind(_socket, (struct sockaddr *) &address, address_length);
listen(_socket, 5);
}
UDSServer::~UDSServer(){
unlink(_filename);
free(_filename);
}
bool UDSServer::accept(struct timeval *timeout) const {
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(_socket, &rfds);
if ( select(_socket+1, &rfds, NULL, NULL, timeout) <= 0 ){
return false;
}
int client = ::accept(_socket, NULL, NULL);
Log::add_destination(new SocketDestination(client));
return true;
}
namespace Log {
static char *timestring(char *buffer, int bufferlen);
static const char* severity_string(Severity severity);
void initialize(){
}
void cleanup(){
for ( iterator it = destinations.begin(); it != destinations.end(); ++it ){
delete it->first;
}
destinations.clear();
}
void add_destination(Destination* dst, Severity severity){
destinations.push_back(std::pair<Destination*, Severity>(dst, severity));
}
void message(Severity severity, const char* fmt, ...){
va_list ap;
va_start(ap, fmt);
vmessage(severity, fmt, ap);
va_end(ap);
}
void vmessage(Severity severity, const char* fmt, va_list ap){
static char buf[255]; /* this isn't thread-safe anyway, might as well make it static */
char* tmp;
vasprintf(&tmp, fmt, ap);
Ptr<char> content(tmp);
asprintf(&tmp, "(%s) [%s] %s", severity_string(severity), timestring(buf, 255), content.get());
Ptr<char> decorated(tmp);
for ( iterator it = destinations.begin(); it != destinations.end(); ++it ){
if ( severity < it->second ) continue;
Destination* dst = it->first;
dst->write(content.get(), decorated.get());
}
}
char* timestring(char *buffer, int bufferlen) {
time_t t = time(NULL);
struct tm* nt;
#ifdef WIN32
nt = new struct tm;
localtime_s(nt, &t);
#else
nt = localtime(&t);
#endif
strftime(buffer, bufferlen, "%Y-%m-%d %H:%M:%S", nt);
#ifdef WIN32
delete nt;
#endif
return buffer;
}
const char* severity_string(Severity severity){
switch ( severity ){
case Log_Debug: return "DD";
case Log_Verbose: return "--";
case Log_Info: return " ";
case Log_Warning: return "WW";
case Log_Fatal: return "!!";
}
return NULL;
}
void debug(const char* fmt, ...){
va_list ap;
va_start(ap, fmt);
vmessage(Log_Debug, fmt, ap);
va_end(ap);
}
void verbose(const char* fmt, ...){
va_list ap;
va_start(ap, fmt);
vmessage(Log_Verbose, fmt, ap);
va_end(ap);
}
void info(const char* fmt, ...){
va_list ap;
va_start(ap, fmt);
vmessage(Log_Info, fmt, ap);
va_end(ap);
}
void warning(const char* fmt, ...){
va_list ap;
va_start(ap, fmt);
vmessage(Log_Warning, fmt, ap);
va_end(ap);
}
void fatal(const char* fmt, ...){
va_list ap;
va_start(ap, fmt);
vmessage(Log_Fatal, fmt, ap);
va_end(ap);
}
}
extern "C" void log_message(enum Severity severity, const char* fmt, ...){
va_list ap;
va_start(ap, fmt);
log_vmessage(severity, fmt, ap);
va_end(ap);
}
extern "C" void log_vmessage(enum Severity severity, const char* fmt, va_list ap){
Log::vmessage(severity, fmt, ap);
}
<commit_msg>daemon: use a delegating constructor<commit_after>/**
* This file is part of Slideshow.
* Copyright (C) 2008-2012 David Sveningsson <ext@sidvind.com>
*
* Slideshow 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.
*
* Slideshow 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 Slideshow. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "log.hpp"
#include "ptr.h"
#include "exception.h"
#include <stdarg.h>
#include <cstdlib>
#include <cstring>
#include <memory> /* for auto_ptr */
#include <errno.h>
#include <time.h>
#include <sys/types.h>
#include <sys/un.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <portable/asprintf.h>
#include <portable/file.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef WIN32
# include "win32.h"
#endif
#ifdef HAVE_SYSLOG
# include <syslog.h>
int syslog_severity[5] = {
LOG_DEBUG,
LOG_INFO,
LOG_NOTICE,
LOG_WARNING,
LOG_ERR
};
#endif /* HAVE_SYSLOG */
typedef std::vector<std::pair<Destination*, Severity>> vector;
typedef vector::iterator iterator;
static vector destinations;
FileDestination::FileDestination(const char* filename)
: FileDestination(fopen(filename, "a")){
}
FileDestination::FileDestination(FILE* fp)
: _fp(fp)
, _autoclose(false) {
if ( !fp ){
fprintf(stderr, "Failed to read fp! Fatal error!\n");
exit(1);
}
}
FileDestination::~FileDestination(){
if ( _autoclose ){
fclose(_fp);
}
}
void FileDestination::write(const char* content, const char* decorated) const {
fputs(decorated, _fp);
fflush(_fp);
}
FIFODestination::FIFODestination(const char* filename)
: _filename(NULL)
, _fp(NULL) {
_filename = strdup(filename);
mkfifo(filename, 0600);
FILE* fp = fopen(filename, "w");
if ( !fp ){
fprintf(stderr, "Failed to open logfile '%s' ! Fatal error!\n", filename);
exit(1);
}
}
FIFODestination::~FIFODestination(){
fclose(_fp);
unlink(_filename);
free(_filename);
}
void FIFODestination::write(const char* content, const char* decorated) const {
fputs(decorated, _fp);
fflush(_fp);
}
SocketDestination::SocketDestination(int socket)
: _socket(socket) {
}
SocketDestination::~SocketDestination(){
close(_socket);
}
void SocketDestination::write(const char* content, const char* decorated) const {
send(_socket, decorated, strlen(decorated), 0);
}
#ifdef HAVE_SYSLOG
SyslogDestination::SyslogDestination(){
/* @todo only a single instance of syslog may be opened */
openlog(PACKAGE, 0, LOG_DAEMON);
}
SyslogDestination::~SyslogDestination(){
closelog();
}
void SyslogDestination::write(const char* content, const char* decorated) const {
syslog(syslog_severity[severity], content);
}
#endif /* HAVE_SYSLOG */
UDSServer::UDSServer(const char* filename)
: _filename(NULL)
, _socket(-1) {
_filename = strdup(filename);
struct sockaddr_un address;
socklen_t address_length;
_socket = socket(PF_UNIX, SOCK_STREAM, 0);
unlink(filename);
address.sun_family = AF_UNIX;
address_length = (socklen_t)sizeof(address.sun_family) +
(socklen_t)sprintf(address.sun_path, "%s", filename);
bind(_socket, (struct sockaddr *) &address, address_length);
listen(_socket, 5);
}
UDSServer::~UDSServer(){
unlink(_filename);
free(_filename);
}
bool UDSServer::accept(struct timeval *timeout) const {
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(_socket, &rfds);
if ( select(_socket+1, &rfds, NULL, NULL, timeout) <= 0 ){
return false;
}
int client = ::accept(_socket, NULL, NULL);
Log::add_destination(new SocketDestination(client));
return true;
}
namespace Log {
static char *timestring(char *buffer, int bufferlen);
static const char* severity_string(Severity severity);
void initialize(){
}
void cleanup(){
for ( iterator it = destinations.begin(); it != destinations.end(); ++it ){
delete it->first;
}
destinations.clear();
}
void add_destination(Destination* dst, Severity severity){
destinations.push_back(std::pair<Destination*, Severity>(dst, severity));
}
void message(Severity severity, const char* fmt, ...){
va_list ap;
va_start(ap, fmt);
vmessage(severity, fmt, ap);
va_end(ap);
}
void vmessage(Severity severity, const char* fmt, va_list ap){
static char buf[255]; /* this isn't thread-safe anyway, might as well make it static */
char* tmp;
vasprintf(&tmp, fmt, ap);
Ptr<char> content(tmp);
asprintf(&tmp, "(%s) [%s] %s", severity_string(severity), timestring(buf, 255), content.get());
Ptr<char> decorated(tmp);
for ( iterator it = destinations.begin(); it != destinations.end(); ++it ){
if ( severity < it->second ) continue;
Destination* dst = it->first;
dst->write(content.get(), decorated.get());
}
}
char* timestring(char *buffer, int bufferlen) {
time_t t = time(NULL);
struct tm* nt;
#ifdef WIN32
nt = new struct tm;
localtime_s(nt, &t);
#else
nt = localtime(&t);
#endif
strftime(buffer, bufferlen, "%Y-%m-%d %H:%M:%S", nt);
#ifdef WIN32
delete nt;
#endif
return buffer;
}
const char* severity_string(Severity severity){
switch ( severity ){
case Log_Debug: return "DD";
case Log_Verbose: return "--";
case Log_Info: return " ";
case Log_Warning: return "WW";
case Log_Fatal: return "!!";
}
return NULL;
}
void debug(const char* fmt, ...){
va_list ap;
va_start(ap, fmt);
vmessage(Log_Debug, fmt, ap);
va_end(ap);
}
void verbose(const char* fmt, ...){
va_list ap;
va_start(ap, fmt);
vmessage(Log_Verbose, fmt, ap);
va_end(ap);
}
void info(const char* fmt, ...){
va_list ap;
va_start(ap, fmt);
vmessage(Log_Info, fmt, ap);
va_end(ap);
}
void warning(const char* fmt, ...){
va_list ap;
va_start(ap, fmt);
vmessage(Log_Warning, fmt, ap);
va_end(ap);
}
void fatal(const char* fmt, ...){
va_list ap;
va_start(ap, fmt);
vmessage(Log_Fatal, fmt, ap);
va_end(ap);
}
}
extern "C" void log_message(enum Severity severity, const char* fmt, ...){
va_list ap;
va_start(ap, fmt);
log_vmessage(severity, fmt, ap);
va_end(ap);
}
extern "C" void log_vmessage(enum Severity severity, const char* fmt, va_list ap){
Log::vmessage(severity, fmt, ap);
}
<|endoftext|>
|
<commit_before>/*
* Project: CommonLib
*
* Version: 1.0.0
* History: V1.0 07/12/2013 SP - created
*
* Copyright (C) 2013 Stefan Paproth <pappi-@gmx.de>
*
* 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/agpl.txt>.
*
*/
#include "log.h"
/*
#define DEFAULT "\e[39m"
#define BLACK "\e[30m"
#define RED "\e[31m"
#define GREEN "\e[32m"
#define YELLOW "\e[33m"
#define BLUE "\e[34m"
#define MAGENTA "\e[35m"
#define CYAN "\e[36m"
#define LIGHT_GRAY "\e[37m"
#define DARK_GRAY "\e[90m"
#define LIGHT_RED "\e[91m"
#define LIGHT_GREEN "\e[92m"
#define LIGHT_YELLOW "\e[93m"
#define LIGHT_BLUE "\e[94m"
#define LIGHT_MAGENTA "\e[95m"
#define LIGHT_CYAN "\e[96m"
#define WHITE "\e[97m"
#define BOLD_BRIGHT "\e[1m"
#define DIM "\e[2m"
#define UNDERLINED "\e[4m"
#define BLINK "\e[5m"
#define REVERSE "\e[7m"
#define HIDDEN "\e[8m"
#define RESET_ALL "\e[0m"
#define RESET_BOLD "\e[21m"
#define RESET_DIM "\e[22m"
#define RESET_UNDERLINDE "\e[24m"
#define RESET_BLINK "\e[25m"
#define RESET_REVERSE "\e[27m"
#define RESET_HIDDEN "\e[28m"
*/
namespace tlog {
CLogEntry::~CLogEntry() {
log_.write(buffer.str(), this->szFile_, this->iLine_, this->logLevel_ );
}
CLog& CLog::theLogger() {
static CLog instance;
return instance;
}
void CLog::write(
const std::string &strLogText, const char *szFile,
const int &iLine, const enuLogLevel &logLevel
) {
struct timeb sTimeB;
char buffer[25] = "";
ftime(&sTimeB);
strftime(buffer, 21, "%d.%m.%Y %H:%M:%S.", localtime(&sTimeB.time));
std::cerr <<
buffer << std::setw(3) << std::setfill('0') << sTimeB.millitm <<
" " << std::setw(12) << std::setfill(' ') << szFile <<
":" << std::setw(4) << std::setfill('0') << iLine;
switch(logLevel) {
case Emerg:
std::cerr << " Emerg.: ";
break;
case Alert:
std::cerr << " Alert: ";
break;
case Error:
std::cerr << " Error: ";
break;
case Warning:
std::cerr << " Warning: ";
break;
case Info:
std::cerr << " Info: ";
break;
case Notice:
std::cerr << " Debug: ";
break;
}
std::cerr << strLogText << std::endl;
}
}
<commit_msg>typo fixed<commit_after>/*
* Project: CommonLib
*
* Version: 1.0.0
* History: V1.0 07/12/2013 SP - created
*
* Copyright (C) 2013 Stefan Paproth <pappi-@gmx.de>
*
* 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/agpl.txt>.
*
*/
#include "log.h"
/*
#define DEFAULT "\e[39m"
#define BLACK "\e[30m"
#define RED "\e[31m"
#define GREEN "\e[32m"
#define YELLOW "\e[33m"
#define BLUE "\e[34m"
#define MAGENTA "\e[35m"
#define CYAN "\e[36m"
#define LIGHT_GRAY "\e[37m"
#define DARK_GRAY "\e[90m"
#define LIGHT_RED "\e[91m"
#define LIGHT_GREEN "\e[92m"
#define LIGHT_YELLOW "\e[93m"
#define LIGHT_BLUE "\e[94m"
#define LIGHT_MAGENTA "\e[95m"
#define LIGHT_CYAN "\e[96m"
#define WHITE "\e[97m"
#define BOLD_BRIGHT "\e[1m"
#define DIM "\e[2m"
#define UNDERLINED "\e[4m"
#define BLINK "\e[5m"
#define REVERSE "\e[7m"
#define HIDDEN "\e[8m"
#define RESET_ALL "\e[0m"
#define RESET_BOLD "\e[21m"
#define RESET_DIM "\e[22m"
#define RESET_UNDERLINDE "\e[24m"
#define RESET_BLINK "\e[25m"
#define RESET_REVERSE "\e[27m"
#define RESET_HIDDEN "\e[28m"
*/
namespace tlog {
CLogEntry::~CLogEntry() {
log_.write(buffer.str(), this->szFile_, this->iLine_, this->logLevel_ );
}
CLog& CLog::theLogger() {
static CLog instance;
return instance;
}
void CLog::write(
const std::string &strLogText, const char *szFile,
const int &iLine, const enuLogLevel &logLevel
) {
struct timeb sTimeB;
char buffer[25] = "";
ftime(&sTimeB);
strftime(buffer, 21, "%d.%m.%Y %H:%M:%S.", localtime(&sTimeB.time));
std::cerr <<
buffer << std::setw(3) << std::setfill('0') << sTimeB.millitm <<
" " << std::setw(12) << std::setfill(' ') << szFile <<
":" << std::setw(4) << std::setfill('0') << iLine;
switch(logLevel) {
case Emerg:
std::cerr << " Emerg.: ";
break;
case Alert:
std::cerr << " Alert: ";
break;
case Error:
std::cerr << " Error: ";
break;
case Warning:
std::cerr << " Warning: ";
break;
case Info:
std::cerr << " Info: ";
break;
case Notice:
std::cerr << " Notice: ";
break;
}
std::cerr << strLogText << std::endl;
}
}
<|endoftext|>
|
<commit_before>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#include"ork/ork.hpp"
#define ORK_STL_INC_FILE <fstream>
#include"ork/core/stl_include.inl"
#define ORK_STL_INC_FILE <iostream>
#include"ork/core/stl_include.inl"
#define ORK_STL_INC_FILE <mutex>
#include"ork/core/stl_include.inl"
#define ORK_STL_INC_FILE <sstream>
#include"ork/core/stl_include.inl"
#include"ork/memory.hpp"
namespace ork {
const ork::string debug_trace(ORK("debug_trace"));
const ork::string output_data(ORK("output_data"));
const ork::string&to_string(const log_channel val) {
switch(val) {
case log_channel::debug_trace:
return debug_trace;
case log_channel::output_data:
return output_data;
};
ORK_UNREACHABLE
}
log_channel string2log_channel(const ork::string&str) {
if(str == output_data) {
return log_channel::output_data;
}
if(str == output_data) {
return log_channel::output_data;
}
ORK_THROW(ORK("Invalid log_channel: ") << str);
}
const ork::string trace(ORK("trace"));
const ork::string debug(ORK("debug"));
const ork::string info(ORK("info"));
const ork::string warning(ORK("warning"));
const ork::string error(ORK("error"));
const ork::string fatal(ORK("fatal"));
const ork::string&to_string(const severity_level val) {
switch(val) {
case severity_level::trace:
return trace;
case severity_level::debug:
return debug;
case severity_level::info:
return info;
case severity_level::warning:
return warning;
case severity_level::error:
return error;
case severity_level::fatal:
return fatal;
};
ORK_UNREACHABLE
}
severity_level string2severity_level(const ork::string&str) {
if(str == trace) {
return severity_level::trace;
}
if(str == debug) {
return severity_level::debug;
}
if(str == info) {
return severity_level::info;
}
if(str == warning) {
return severity_level::warning;
}
if(str == error) {
return severity_level::error;
}
if(str == fatal) {
return severity_level::fatal;
}
ORK_THROW(ORK("Invalid severity_level: ") << str);
}
//This is little more than a synchronous wrapper around an o_stream
class log_stream {
public:
using stream_ptr = std::shared_ptr<o_stream>;
private:
stream_ptr _stream;
std::mutex _mutex;
public:
explicit log_stream(stream_ptr stream_) : _stream{stream_}, _mutex{} {}
~log_stream() {
flush();
}
ORK_NON_COPYABLE(log_stream)
public:
void log(const string&message) {
std::lock_guard<std::mutex>lock(_mutex);
*_stream << message << ORK('\n');
}
void flush() {
_stream->flush();
}
};
class log_sink {
public:
using stream_ptr = std::shared_ptr<log_stream>;
private:
std::vector<stream_ptr>_streams = {};
bool _auto_flush = false;
public:
log_sink() {}
log_sink(const bool auto_flush) : _auto_flush{auto_flush} {}
ORK_NON_COPYABLE(log_sink)
public:
void insert(const stream_ptr&ptr) {
_streams.push_back(ptr);
}
void log(const string&message) {
for(auto&stream : _streams) {
stream->log(message);
if(_auto_flush) {
stream->flush();
}
}
}
void set_auto_flush(const bool auto_flush) {
_auto_flush = auto_flush;
}
void flush() {
for(auto&stream : _streams) {
stream->flush();
}
}
};
std::shared_ptr<log_stream>open_file_log_stream(const file::path&file_name) {
if(!file::ensure_directory(file_name)) {
ORK_THROW(ORK("Could not create directory : ") << file_name.ORK_GEN_STR())
}
of_stream* p_stream = new of_stream();
p_stream->open(file_name);//std::ios::app | std::ios::ate
if(p_stream->fail()) {
ORK_THROW(ORK("Error opening log : ") << file_name)
}
//p_stream->rdbuf()->pubsetbuf(0, 0);//Less performance, more likely to catch error messages
return std::shared_ptr<log_stream>(new log_stream(log_stream::stream_ptr(p_stream)));
}
//This is where our logging system falls short of a generic filter system; try to hide it somewhat in one place
class log_multiplexer {
private:
using sink_ptr = std::unique_ptr<log_sink>;
private:
std::vector<sink_ptr> _severity_sinks = {};
log_sink _data_sink = {};
public:
log_multiplexer(const file::path&root_directory){
auto lout = log_sink::stream_ptr{new log_stream{log_stream::stream_ptr{&ORK_CLOG, singleton_deleter<o_stream>()}}};
auto lerr = log_sink::stream_ptr{new log_stream{log_stream::stream_ptr{&ORK_CERR, singleton_deleter<o_stream>()}}};
auto flog = open_file_log_stream(root_directory / ORK("trace.log"));
auto fdata = open_file_log_stream(root_directory / ORK("output.log"));
for(const auto sv : severity_levels) {
sink_ptr sink{};
if(sv < severity_level::error) {
sink.reset(new log_sink{false});
sink->insert(lout);
}
else {
sink.reset(new log_sink{true});
sink->insert(lerr);
}
sink->insert(flog);
_severity_sinks.emplace_back(std::move(sink));
}
_data_sink.insert(lout);
_data_sink.insert(fdata);
}
ORK_NON_COPYABLE(log_multiplexer)
public:
void log(const log_channel channel, const severity_level severity, const o_string_stream&stream) {
const string message = stream.str();
switch(channel) {
case log_channel::debug_trace:
log_severity(severity, message);
break;
case log_channel::output_data:
_data_sink.log(stream.str());
break;
default:
ORK_UNREACHABLE
};
}
void flush_all() {
for(auto&sink : _severity_sinks) {
sink->flush();
}
_data_sink.flush();
}
private:
void log_severity(const severity_level severity, const string&message) {
const bool do_it = ORK_DEBUG || severity > severity_level::debug;
if ORK_CONSTEXPR(do_it || true) {
_severity_sinks[static_cast<size_t>(severity)]->log(message);
}
}
};
class message_guard {
private:
ork::string _message = {};
int _stage = 0;
mutable std::mutex _mutex = {};
public:
ORK_NON_COPYABLE(message_guard)
public:
// This should be called to check if the message is ready to be cleared
bool done() const {
std::scoped_lock<std::mutex> lock(_mutex);
return _stage > 0;
}
// This should be called once to complete the message
void log(const o_string_stream&stream) {
std::scoped_lock<std::mutex> lock(_mutex);
if(_stage != 0) {
ORK_THROW(ORK("Message pump called in wrong order"));
}
_message = stream.str();
_stage = 1;
}
// This should be called once after completion
std::string clear_message() {
std::scoped_lock<std::mutex> lock(_mutex);
if(_stage != 1) {
ORK_THROW(ORK("Message pump called in wrong order"));
}
_stage = 2;
return std::move(_message);
}
};
struct log_scope::impl {
public:
std::shared_ptr<log_multiplexer>multiplexer;
log_channel channel;
severity_level severity;
o_string_stream stream;
public:
impl(std::shared_ptr<log_multiplexer>&mp, const log_channel lc, const severity_level sv)
: multiplexer{mp}
, channel{lc}
, severity{sv}
, stream{}
{}
~impl() {
multiplexer->log(channel, severity, stream);
}
ORK_MOVE_ONLY(impl)
};
log_scope::log_scope(std::unique_ptr<impl>&&ptr) : _pimpl{ std::move(ptr) } {}
log_scope::~log_scope() {}
#define LOG_STREAM_OPERATOR(TYPE) \
log_scope& log_scope::operator<< (const TYPE val) {\
_pimpl->stream << val;\
return *this;\
}
LOG_STREAM_OPERATOR(bool)
LOG_STREAM_OPERATOR(short)
LOG_STREAM_OPERATOR(unsigned short)
LOG_STREAM_OPERATOR(int)
LOG_STREAM_OPERATOR(unsigned)
LOG_STREAM_OPERATOR(long)
LOG_STREAM_OPERATOR(unsigned long)
LOG_STREAM_OPERATOR(long long)
LOG_STREAM_OPERATOR(unsigned long long)
LOG_STREAM_OPERATOR(float)
LOG_STREAM_OPERATOR(double)
LOG_STREAM_OPERATOR(long double)
#undef LOG_STREAM_OPERATOR
#define LOG_STREAM_OPERATOR(TYPE) \
log_scope& log_scope::operator<< (const TYPE val) {\
_pimpl->stream << ORK_BYTE_2_STR(val);\
return *this;\
}
LOG_STREAM_OPERATOR(char)
LOG_STREAM_OPERATOR(char*)
LOG_STREAM_OPERATOR(bstring&)
#undef LOG_STREAM_OPERATOR
#define LOG_STREAM_OPERATOR(TYPE) \
log_scope& log_scope::operator<< (const TYPE val) {\
_pimpl->stream << ORK_WIDE_2_STR(val);\
return *this;\
}
LOG_STREAM_OPERATOR(wchar_t)
LOG_STREAM_OPERATOR(wchar_t*)
LOG_STREAM_OPERATOR(wstring&)
log_scope& log_scope::operator<< (const void* val) {
_pimpl->stream << val;
return *this;
}
log_scope& log_scope::operator<< (const std::streambuf* sb) {
_pimpl->stream << sb;
return *this;
}
log_scope& log_scope::operator<< (std::ostream& (*pf)(std::ostream&)) {
_pimpl->stream << pf;
return *this;
}
log_scope& log_scope::operator<< (std::ios& (*pf)(std::ios&)) {
_pimpl->stream << pf;
return *this;
}
log_scope& log_scope::operator<< (std::ios_base& (*pf)(std::ios_base&)) {
_pimpl->stream << pf;
return *this;
}
const string&to_formatted_string(const severity_level sv) {
static const std::array<const string, severity_levels.size()>strings = {{
ORK("TRACE")
, ORK("DEBUG")
, ORK("INFO ")
, ORK("WARN ")
, ORK("ERROR")
, ORK("FATAL")
}};
return strings[static_cast<size_t>(sv)];
}
struct logger::impl {
public:
file::path root_directory;
std::shared_ptr<log_multiplexer>multiplexer;
public:
impl(const file::path&directory)
: root_directory(directory)
, multiplexer{new log_multiplexer(directory)}
{}
void flush_all() {
multiplexer->flush_all();
}
};
logger::logger(const file::path&log_directory) : _pimpl(new impl(log_directory)) {}
logger::~logger() {}
const file::path& logger::root_directory() {
return _pimpl->root_directory;
}
log_scope logger::get_log_scope(
const string&file_
, const string&line_
, const string&function_
, const log_channel channel
, const severity_level severity)
{
const file::path fullpath(file_);
string file(fullpath.filename().ORK_GEN_STR());
file.resize(24, ORK(' '));
string line(line_);
line.resize(4, ORK(' '));
string function(function_);
function.resize(48, ORK(' '));
std::unique_ptr<log_scope::impl> ls_impl(new log_scope::impl(_pimpl->multiplexer, channel, severity));
log_scope scope(std::move(ls_impl));
//Output formatted context first
scope << ORK("[") << to_formatted_string(severity) << ORK("]:") << file << ORK("(") << line << ORK("):") << function << ORK("-- ");
//Finally, return the stream to the client
return std::move(scope);
}
void logger::flush_all() {
_pimpl->flush_all();
}
logger*_g_log = nullptr;
int make_global_log(const string&directory) {
static logger log(directory);
_g_log = &log;
return 0;
}
logger& get_global_log() {
return *_g_log;
}
}//namespace ork
<commit_msg>Now using message guards to order messages<commit_after>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#include"ork/ork.hpp"
#define ORK_STL_INC_FILE <fstream>
#include"ork/core/stl_include.inl"
#define ORK_STL_INC_FILE <iostream>
#include"ork/core/stl_include.inl"
#define ORK_STL_INC_FILE <mutex>
#include"ork/core/stl_include.inl"
#define ORK_STL_INC_FILE <sstream>
#include"ork/core/stl_include.inl"
#include"ork/memory.hpp"
namespace ork {
const ork::string debug_trace(ORK("debug_trace"));
const ork::string output_data(ORK("output_data"));
const ork::string&to_string(const log_channel val) {
switch(val) {
case log_channel::debug_trace:
return debug_trace;
case log_channel::output_data:
return output_data;
};
ORK_UNREACHABLE
}
log_channel string2log_channel(const ork::string&str) {
if(str == output_data) {
return log_channel::output_data;
}
if(str == output_data) {
return log_channel::output_data;
}
ORK_THROW(ORK("Invalid log_channel: ") << str);
}
const ork::string trace(ORK("trace"));
const ork::string debug(ORK("debug"));
const ork::string info(ORK("info"));
const ork::string warning(ORK("warning"));
const ork::string error(ORK("error"));
const ork::string fatal(ORK("fatal"));
const ork::string&to_string(const severity_level val) {
switch(val) {
case severity_level::trace:
return trace;
case severity_level::debug:
return debug;
case severity_level::info:
return info;
case severity_level::warning:
return warning;
case severity_level::error:
return error;
case severity_level::fatal:
return fatal;
};
ORK_UNREACHABLE
}
severity_level string2severity_level(const ork::string&str) {
if(str == trace) {
return severity_level::trace;
}
if(str == debug) {
return severity_level::debug;
}
if(str == info) {
return severity_level::info;
}
if(str == warning) {
return severity_level::warning;
}
if(str == error) {
return severity_level::error;
}
if(str == fatal) {
return severity_level::fatal;
}
ORK_THROW(ORK("Invalid severity_level: ") << str);
}
//This is little more than a synchronous wrapper around an o_stream
class log_stream {
public:
using stream_ptr = std::shared_ptr<o_stream>;
private:
stream_ptr _stream;
std::mutex _mutex;
public:
explicit log_stream(stream_ptr stream_) : _stream{stream_}, _mutex{} {}
~log_stream() {
flush();
}
ORK_NON_COPYABLE(log_stream)
public:
void log(const string&message) {
std::lock_guard<std::mutex>lock(_mutex);
*_stream << message << ORK('\n');
}
void flush() {
_stream->flush();
}
};
class log_sink {
public:
using stream_ptr = std::shared_ptr<log_stream>;
private:
std::vector<stream_ptr>_streams = {};
bool _auto_flush = false;
public:
log_sink() {}
log_sink(const bool auto_flush) : _auto_flush{auto_flush} {}
ORK_NON_COPYABLE(log_sink)
public:
void insert(const stream_ptr&ptr) {
_streams.push_back(ptr);
}
void log(const string&message) {
for(auto&stream : _streams) {
stream->log(message);
if(_auto_flush) {
stream->flush();
}
}
}
void set_auto_flush(const bool auto_flush) {
_auto_flush = auto_flush;
}
void flush() {
for(auto&stream : _streams) {
stream->flush();
}
}
};
std::shared_ptr<log_stream>open_file_log_stream(const file::path&file_name) {
if(!file::ensure_directory(file_name)) {
ORK_THROW(ORK("Could not create directory : ") << file_name.ORK_GEN_STR())
}
of_stream* p_stream = new of_stream();
p_stream->open(file_name);//std::ios::app | std::ios::ate
if(p_stream->fail()) {
ORK_THROW(ORK("Error opening log : ") << file_name)
}
//p_stream->rdbuf()->pubsetbuf(0, 0);//Less performance, more likely to catch error messages
return std::shared_ptr<log_stream>(new log_stream(log_stream::stream_ptr(p_stream)));
}
class message_guard {
private:
ork::string _message = {};
int _stage = 0;
mutable std::mutex _mutex = {};
log_channel _channel;
severity_level _severity;
public:
message_guard(
const log_channel lc,
const severity_level sv)
: _channel{lc}
, _severity{sv} {}
ORK_NON_COPYABLE(message_guard)
public:
log_channel channel() const {
return _channel;
}
severity_level severity() const {
return _severity;
}
// This should be called to check if the message is ready to be cleared
bool done() const {
std::scoped_lock<std::mutex> lock(_mutex);
return _stage > 0;
}
// This should be called once to complete the message
void log(const o_string_stream&stream) {
std::scoped_lock<std::mutex> lock(_mutex);
if(_stage != 0) {
ORK_THROW(ORK("Message pump called in wrong order"));
}
_message = stream.str();
_stage = 1;
}
// This should be called once after completion
std::string clear_message() {
std::scoped_lock<std::mutex> lock(_mutex);
if(_stage != 1) {
ORK_THROW(ORK("Message pump called in wrong order"));
}
_stage = 2;
return std::move(_message);
}
};
using guard_ptr = std::shared_ptr<message_guard>;
//This is where our logging system falls short of a generic filter system; try to hide it somewhat in one place
class log_multiplexer {
private:
using sink_ptr = std::unique_ptr<log_sink>;
private:
std::vector<sink_ptr> _severity_sinks = {};
log_sink _data_sink = {};
std::vector<guard_ptr>_messages = {};
size_t _message_index = 0;
std::mutex _mutex = {};
public:
log_multiplexer(const file::path&root_directory) {
auto lout = log_sink::stream_ptr{new log_stream{log_stream::stream_ptr{&ORK_CLOG, singleton_deleter<o_stream>()}}};
auto lerr = log_sink::stream_ptr{new log_stream{log_stream::stream_ptr{&ORK_CERR, singleton_deleter<o_stream>()}}};
auto flog = open_file_log_stream(root_directory / ORK("trace.log"));
auto fdata = open_file_log_stream(root_directory / ORK("output.log"));
for(const auto sv : severity_levels) {
sink_ptr sink{};
if(sv < severity_level::error) {
sink.reset(new log_sink{false});
sink->insert(lout);
}
else {
sink.reset(new log_sink{true});
sink->insert(lerr);
}
sink->insert(flog);
_severity_sinks.emplace_back(std::move(sink));
}
_data_sink.insert(lout);
_data_sink.insert(fdata);
}
ORK_NON_COPYABLE(log_multiplexer)
public:
guard_ptr get_message_guard(
const log_channel lc,
const severity_level sv
) {
std::scoped_lock<std::mutex> lock{_mutex};
_messages.emplace_back(new message_guard{lc, sv});
return _messages.back();
}
void on_scope_exit() {
std::scoped_lock<std::mutex> lock{_mutex};
while(_message_index < _messages.size() - 1 && _messages[_message_index]->done()) {
log(*_messages[_message_index]);
++_message_index;
}
}
void flush_all() {
std::scoped_lock<std::mutex> lock{_mutex};
for(auto&sink : _severity_sinks) {
sink->flush();
}
_data_sink.flush();
}
private:
void log(message_guard& message) {
const string msg{message.clear_message()};
switch(message.channel()) {
case log_channel::debug_trace:
log_severity(message.severity(), msg);
break;
case log_channel::output_data:
_data_sink.log(msg);
break;
default:
ORK_UNREACHABLE
};
}
void log_severity(
const severity_level severity,
const string&message
) {
const bool do_it = ORK_DEBUG || severity > severity_level::debug;
if ORK_CONSTEXPR(do_it || true) {
_severity_sinks[static_cast<size_t>(severity)]->log(message);
}
}
};
struct log_scope::impl {
public:
std::shared_ptr<message_guard>guard;
std::shared_ptr<log_multiplexer>multiplexer;
o_string_stream stream;
public:
impl(
const std::shared_ptr<message_guard>&mg,
const std::shared_ptr<log_multiplexer>&mp
)
: guard{mg}
, multiplexer{mp}
, stream{}
{}
~impl() {
guard->log(stream);
multiplexer->on_scope_exit();
}
ORK_MOVE_ONLY(impl)
};
log_scope::log_scope(std::unique_ptr<impl>&&ptr) : _pimpl{ std::move(ptr) } {}
log_scope::~log_scope() {}
#define LOG_STREAM_OPERATOR(TYPE) \
log_scope& log_scope::operator<< (const TYPE val) {\
_pimpl->stream << val;\
return *this;\
}
LOG_STREAM_OPERATOR(bool)
LOG_STREAM_OPERATOR(short)
LOG_STREAM_OPERATOR(unsigned short)
LOG_STREAM_OPERATOR(int)
LOG_STREAM_OPERATOR(unsigned)
LOG_STREAM_OPERATOR(long)
LOG_STREAM_OPERATOR(unsigned long)
LOG_STREAM_OPERATOR(long long)
LOG_STREAM_OPERATOR(unsigned long long)
LOG_STREAM_OPERATOR(float)
LOG_STREAM_OPERATOR(double)
LOG_STREAM_OPERATOR(long double)
#undef LOG_STREAM_OPERATOR
#define LOG_STREAM_OPERATOR(TYPE) \
log_scope& log_scope::operator<< (const TYPE val) {\
_pimpl->stream << ORK_BYTE_2_STR(val);\
return *this;\
}
LOG_STREAM_OPERATOR(char)
LOG_STREAM_OPERATOR(char*)
LOG_STREAM_OPERATOR(bstring&)
#undef LOG_STREAM_OPERATOR
#define LOG_STREAM_OPERATOR(TYPE) \
log_scope& log_scope::operator<< (const TYPE val) {\
_pimpl->stream << ORK_WIDE_2_STR(val);\
return *this;\
}
LOG_STREAM_OPERATOR(wchar_t)
LOG_STREAM_OPERATOR(wchar_t*)
LOG_STREAM_OPERATOR(wstring&)
log_scope& log_scope::operator<< (const void* val) {
_pimpl->stream << val;
return *this;
}
log_scope& log_scope::operator<< (const std::streambuf* sb) {
_pimpl->stream << sb;
return *this;
}
log_scope& log_scope::operator<< (std::ostream& (*pf)(std::ostream&)) {
_pimpl->stream << pf;
return *this;
}
log_scope& log_scope::operator<< (std::ios& (*pf)(std::ios&)) {
_pimpl->stream << pf;
return *this;
}
log_scope& log_scope::operator<< (std::ios_base& (*pf)(std::ios_base&)) {
_pimpl->stream << pf;
return *this;
}
const string&to_formatted_string(const severity_level sv) {
static const std::array<const string, severity_levels.size()>strings = {{
ORK("TRACE")
, ORK("DEBUG")
, ORK("INFO ")
, ORK("WARN ")
, ORK("ERROR")
, ORK("FATAL")
}};
return strings[static_cast<size_t>(sv)];
}
struct logger::impl {
public:
file::path root_directory;
std::shared_ptr<log_multiplexer>multiplexer;
public:
impl(const file::path&directory)
: root_directory(directory)
, multiplexer{new log_multiplexer(directory)}
{}
void flush_all() {
multiplexer->flush_all();
}
};
logger::logger(const file::path&log_directory) : _pimpl(new impl(log_directory)) {}
logger::~logger() {}
const file::path& logger::root_directory() {
return _pimpl->root_directory;
}
log_scope logger::get_log_scope(
const string&file_
, const string&line_
, const string&function_
, const log_channel channel
, const severity_level severity)
{
const file::path fullpath(file_);
string file(fullpath.filename().ORK_GEN_STR());
file.resize(24, ORK(' '));
string line(line_);
line.resize(4, ORK(' '));
string function(function_);
function.resize(48, ORK(' '));
guard_ptr guard{_pimpl->multiplexer->get_message_guard(channel, severity)};
std::unique_ptr<log_scope::impl> ls_impl(new log_scope::impl(guard, _pimpl->multiplexer));
log_scope scope(std::move(ls_impl));
//Output formatted context first
scope << ORK("[") << to_formatted_string(severity) << ORK("]:") << file << ORK("(") << line << ORK("):") << function << ORK("-- ");
//Finally, return the stream to the client
return std::move(scope);
}
void logger::flush_all() {
_pimpl->flush_all();
}
logger*_g_log = nullptr;
int make_global_log(const string&directory) {
static logger log(directory);
_g_log = &log;
return 0;
}
logger& get_global_log() {
return *_g_log;
}
}//namespace ork
<|endoftext|>
|
<commit_before>#include <iostream>
#include <fstream>
#include <cstdarg>
#include <uv.h>
#include "log.h"
using std::endl;
using std::ostream;
using std::ofstream;
class NullLogger : public Logger {
public:
virtual Logger* prefix(const char *file, int line) override
{
return this;
}
virtual ostream& stream() override
{
return unopened;
}
private:
ofstream unopened;
};
class FileLogger : public Logger {
public:
FileLogger(const char *filename) :
logStream{filename, std::ios::out | std::ios::app}
{
prefix(__FILE__, __LINE__);
logStream << "FileLogger opened." << endl;
}
virtual Logger* prefix(const char *file, int line) override
{
logStream << "[" << file << ":" << line << "] ";
return this;
}
virtual ostream& stream() override
{
return logStream;
}
private:
ofstream logStream;
};
static uv_key_t current_logger_key;
static const NullLogger theNullLogger;
static uv_once_t make_key_once = UV_ONCE_INIT;
static void make_key()
{
uv_key_create(¤t_logger_key);
}
Logger* Logger::current()
{
uv_once(&make_key_once, &make_key);
Logger* logger = (Logger*) uv_key_get(¤t_logger_key);
if (logger == nullptr) {
uv_key_set(¤t_logger_key, (void*) &theNullLogger);
}
return logger;
}
static void replaceLogger(const Logger *newLogger)
{
Logger *prior = Logger::current();
if (prior != &theNullLogger) {
delete prior;
}
uv_key_set(¤t_logger_key, (void*) newLogger);
}
void Logger::toFile(const char *filename)
{
replaceLogger(new FileLogger(filename));
}
void Logger::disable()
{
replaceLogger(&theNullLogger);
}
<commit_msg>User-provided default constructor for NullLogger<commit_after>#include <iostream>
#include <fstream>
#include <cstdarg>
#include <uv.h>
#include "log.h"
using std::endl;
using std::ostream;
using std::ofstream;
class NullLogger : public Logger {
public:
NullLogger()
{
//
}
virtual Logger* prefix(const char *file, int line) override
{
return this;
}
virtual ostream& stream() override
{
return unopened;
}
private:
ofstream unopened;
};
class FileLogger : public Logger {
public:
FileLogger(const char *filename) :
logStream{filename, std::ios::out | std::ios::app}
{
prefix(__FILE__, __LINE__);
logStream << "FileLogger opened." << endl;
}
virtual Logger* prefix(const char *file, int line) override
{
logStream << "[" << file << ":" << line << "] ";
return this;
}
virtual ostream& stream() override
{
return logStream;
}
private:
ofstream logStream;
};
static uv_key_t current_logger_key;
static const NullLogger theNullLogger;
static uv_once_t make_key_once = UV_ONCE_INIT;
static void make_key()
{
uv_key_create(¤t_logger_key);
}
Logger* Logger::current()
{
uv_once(&make_key_once, &make_key);
Logger* logger = (Logger*) uv_key_get(¤t_logger_key);
if (logger == nullptr) {
uv_key_set(¤t_logger_key, (void*) &theNullLogger);
}
return logger;
}
static void replaceLogger(const Logger *newLogger)
{
Logger *prior = Logger::current();
if (prior != &theNullLogger) {
delete prior;
}
uv_key_set(¤t_logger_key, (void*) newLogger);
}
void Logger::toFile(const char *filename)
{
replaceLogger(new FileLogger(filename));
}
void Logger::disable()
{
replaceLogger(&theNullLogger);
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of 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 "libtorrent/pch.hpp"
#include "libtorrent/lsd.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/http_tracker_connection.hpp"
#include "libtorrent/buffer.hpp"
#include "libtorrent/http_parser.hpp"
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#if BOOST_VERSION < 103500
#include <asio/ip/host_name.hpp>
#include <asio/ip/multicast.hpp>
#else
#include <boost/asio/ip/host_name.hpp>
#include <boost/asio/ip/multicast.hpp>
#endif
#include <boost/thread/mutex.hpp>
#include <cstdlib>
#include <boost/config.hpp>
using boost::bind;
using namespace libtorrent;
namespace libtorrent
{
// defined in broadcast_socket.cpp
address guess_local_address(io_service&);
}
static error_code ec;
lsd::lsd(io_service& ios, address const& listen_interface
, peer_callback_t const& cb)
: m_callback(cb)
, m_retry_count(1)
, m_socket(ios, udp::endpoint(address_v4::from_string("239.192.152.143", ec), 6771)
, bind(&lsd::on_announce, self(), _1, _2, _3))
, m_broadcast_timer(ios)
, m_disabled(false)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log.open("lsd.log", std::ios::in | std::ios::out | std::ios::trunc);
#endif
}
lsd::~lsd() {}
void lsd::announce(sha1_hash const& ih, int listen_port)
{
if (m_disabled) return;
std::stringstream btsearch;
btsearch << "BT-SEARCH * HTTP/1.1\r\n"
"Host: 239.192.152.143:6771\r\n"
"Port: " << listen_port << "\r\n"
"Infohash: " << ih << "\r\n"
"\r\n\r\n";
std::string const& msg = btsearch.str();
m_retry_count = 1;
error_code ec;
m_socket.send(msg.c_str(), int(msg.size()), ec);
if (ec)
{
m_disabled = true;
return;
}
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " ==> announce: ih: " << ih << " port: " << listen_port << std::endl;
#endif
m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec);
m_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));
}
void lsd::resend_announce(error_code const& e, std::string msg)
{
if (e) return;
error_code ec;
m_socket.send(msg.c_str(), int(msg.size()), ec);
++m_retry_count;
if (m_retry_count >= 5)
return;
m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec);
m_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));
}
void lsd::on_announce(udp::endpoint const& from, char* buffer
, std::size_t bytes_transferred)
{
using namespace libtorrent::detail;
http_parser p;
bool error = false;
p.incoming(buffer::const_interval(buffer, buffer + bytes_transferred)
, error);
if (!p.header_finished() || error)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: incomplete HTTP message\n";
#endif
return;
}
if (p.method() != "bt-search")
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: invalid HTTP method: " << p.method() << std::endl;
#endif
return;
}
std::string const& port_str = p.header("port");
if (port_str.empty())
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: invalid BT-SEARCH, missing port" << std::endl;
#endif
return;
}
std::string const& ih_str = p.header("infohash");
if (ih_str.empty())
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: invalid BT-SEARCH, missing infohash" << std::endl;
#endif
return;
}
sha1_hash ih(0);
std::istringstream ih_sstr(ih_str);
ih_sstr >> ih;
int port = std::atoi(port_str.c_str());
if (!ih.is_all_zeros() && port != 0)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " *** incoming local announce " << from.address()
<< ":" << port << " ih: " << ih << std::endl;
#endif
// we got an announce, pass it on through the callback
#ifndef BOOST_NO_EXCEPTIONS
try {
#endif
m_callback(tcp::endpoint(from.address(), port), ih);
#ifndef BOOST_NO_EXCEPTIONS
}
catch (std::exception&) {}
#endif
}
}
void lsd::close()
{
m_socket.close();
error_code ec;
m_broadcast_timer.cancel(ec);
m_disabled = true;
m_callback.clear();
}
<commit_msg>fixed locale dependence in lsd.cpp<commit_after>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of 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 "libtorrent/pch.hpp"
#include "libtorrent/lsd.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/http_tracker_connection.hpp"
#include "libtorrent/buffer.hpp"
#include "libtorrent/http_parser.hpp"
#include "libtorrent/escape_string.hpp"
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#if BOOST_VERSION < 103500
#include <asio/ip/host_name.hpp>
#include <asio/ip/multicast.hpp>
#else
#include <boost/asio/ip/host_name.hpp>
#include <boost/asio/ip/multicast.hpp>
#endif
#include <boost/thread/mutex.hpp>
#include <cstdlib>
#include <boost/config.hpp>
using boost::bind;
using namespace libtorrent;
namespace libtorrent
{
// defined in broadcast_socket.cpp
address guess_local_address(io_service&);
}
static error_code ec;
lsd::lsd(io_service& ios, address const& listen_interface
, peer_callback_t const& cb)
: m_callback(cb)
, m_retry_count(1)
, m_socket(ios, udp::endpoint(address_v4::from_string("239.192.152.143", ec), 6771)
, bind(&lsd::on_announce, self(), _1, _2, _3))
, m_broadcast_timer(ios)
, m_disabled(false)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log.open("lsd.log", std::ios::in | std::ios::out | std::ios::trunc);
#endif
}
lsd::~lsd() {}
void lsd::announce(sha1_hash const& ih, int listen_port)
{
if (m_disabled) return;
std::stringstream btsearch;
btsearch << "BT-SEARCH * HTTP/1.1\r\n"
"Host: 239.192.152.143:6771\r\n"
"Port: " << to_string(listen_port).elems << "\r\n"
"Infohash: " << ih << "\r\n"
"\r\n\r\n";
std::string const& msg = btsearch.str();
m_retry_count = 1;
error_code ec;
m_socket.send(msg.c_str(), int(msg.size()), ec);
if (ec)
{
m_disabled = true;
return;
}
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " ==> announce: ih: " << ih << " port: " << to_string(listen_port).elems << std::endl;
#endif
m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec);
m_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));
}
void lsd::resend_announce(error_code const& e, std::string msg)
{
if (e) return;
error_code ec;
m_socket.send(msg.c_str(), int(msg.size()), ec);
++m_retry_count;
if (m_retry_count >= 5)
return;
m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec);
m_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));
}
void lsd::on_announce(udp::endpoint const& from, char* buffer
, std::size_t bytes_transferred)
{
using namespace libtorrent::detail;
http_parser p;
bool error = false;
p.incoming(buffer::const_interval(buffer, buffer + bytes_transferred)
, error);
if (!p.header_finished() || error)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: incomplete HTTP message\n";
#endif
return;
}
if (p.method() != "bt-search")
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: invalid HTTP method: " << p.method() << std::endl;
#endif
return;
}
std::string const& port_str = p.header("port");
if (port_str.empty())
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: invalid BT-SEARCH, missing port" << std::endl;
#endif
return;
}
std::string const& ih_str = p.header("infohash");
if (ih_str.empty())
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: invalid BT-SEARCH, missing infohash" << std::endl;
#endif
return;
}
sha1_hash ih(0);
std::istringstream ih_sstr(ih_str);
ih_sstr >> ih;
int port = std::atoi(port_str.c_str());
if (!ih.is_all_zeros() && port != 0)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " *** incoming local announce " << from.address()
<< ":" << to_string(port).elems << " ih: " << ih << std::endl;
#endif
// we got an announce, pass it on through the callback
#ifndef BOOST_NO_EXCEPTIONS
try {
#endif
m_callback(tcp::endpoint(from.address(), port), ih);
#ifndef BOOST_NO_EXCEPTIONS
}
catch (std::exception&) {}
#endif
}
}
void lsd::close()
{
m_socket.close();
error_code ec;
m_broadcast_timer.cancel(ec);
m_disabled = true;
m_callback.clear();
}
<|endoftext|>
|
<commit_before>#include "opencv2/video/tracking.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdio.h>
using namespace cv;
static inline Point calcPoint(Point2f center, double R, double angle)
{
return center + Point2f((float)cos(angle), (float)-sin(angle))*(float)R;
}
static void help()
{
printf( "\nExamle of c calls to OpenCV's Kalman filter.\n"
" Tracking of rotating point.\n"
" Rotation speed is constant.\n"
" Both state and measurements vectors are 1D (a point angle),\n"
" Measurement is the real point angle + gaussian noise.\n"
" The real and the estimated points are connected with yellow line segment,\n"
" the real and the measured points are connected with red line segment.\n"
" (if Kalman filter works correctly,\n"
" the yellow segment should be shorter than the red one).\n"
"\n"
" Pressing any key (except ESC) will reset the tracking with a different speed.\n"
" Pressing ESC will stop the program.\n"
);
}
int main(int, char**)
{
help();
Mat img(500, 500, CV_8UC3);
KalmanFilter KF(2, 1, 0);
Mat state(2, 1, CV_32F); /* (phi, delta_phi) */
Mat processNoise(2, 1, CV_32F);
Mat measurement = Mat::zeros(1, 1, CV_32F);
char code = (char)-1;
for(;;)
{
randn( state, Scalar::all(0), Scalar::all(0.1) );
KF.transitionMatrix = *(Mat_<float>(2, 2) << 1, 1, 0, 1);
setIdentity(KF.measurementMatrix);
setIdentity(KF.processNoiseCov, Scalar::all(1e-5));
setIdentity(KF.measurementNoiseCov, Scalar::all(1e-1));
setIdentity(KF.errorCovPost, Scalar::all(1));
randn(KF.statePost, Scalar::all(0), Scalar::all(0.1));
for(;;)
{
Point2f center(img.cols*0.5f, img.rows*0.5f);
float R = img.cols/3.f;
double stateAngle = state.at<float>(0);
Point statePt = calcPoint(center, R, stateAngle);
Mat prediction = KF.predict();
double predictAngle = prediction.at<float>(0);
Point predictPt = calcPoint(center, R, predictAngle);
randn( measurement, Scalar::all(0), Scalar::all(KF.measurementNoiseCov.at<float>(0)));
// generate measurement
measurement += KF.measurementMatrix*state;
double measAngle = measurement.at<float>(0);
Point measPt = calcPoint(center, R, measAngle);
// plot points
#define drawCross( center, color, d ) \
line( img, Point( center.x - d, center.y - d ), \
Point( center.x + d, center.y + d ), color, 1, CV_AA, 0); \
line( img, Point( center.x + d, center.y - d ), \
Point( center.x - d, center.y + d ), color, 1, CV_AA, 0 )
img = Scalar::all(0);
drawCross( statePt, Scalar(255,255,255), 3 );
drawCross( measPt, Scalar(0,0,255), 3 );
drawCross( predictPt, Scalar(0,255,0), 3 );
line( img, statePt, measPt, Scalar(0,0,255), 3, CV_AA, 0 );
line( img, statePt, predictPt, Scalar(0,255,255), 3, CV_AA, 0 );
if(theRNG().uniform(0,4) != 0)
KF.correct(measurement);
randn( processNoise, Scalar(0), Scalar::all(sqrt(KF.processNoiseCov.at<float>(0, 0))));
state = KF.transitionMatrix*state + processNoise;
imshow( "Kalman", img );
code = (char)waitKey(100);
if( code > 0 )
break;
}
if( code == 27 || code == 'q' || code == 'Q' )
break;
}
return 0;
}
<commit_msg>Fixed typo<commit_after>#include "opencv2/video/tracking.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdio.h>
using namespace cv;
static inline Point calcPoint(Point2f center, double R, double angle)
{
return center + Point2f((float)cos(angle), (float)-sin(angle))*(float)R;
}
static void help()
{
printf( "\nExample of c calls to OpenCV's Kalman filter.\n"
" Tracking of rotating point.\n"
" Rotation speed is constant.\n"
" Both state and measurements vectors are 1D (a point angle),\n"
" Measurement is the real point angle + gaussian noise.\n"
" The real and the estimated points are connected with yellow line segment,\n"
" the real and the measured points are connected with red line segment.\n"
" (if Kalman filter works correctly,\n"
" the yellow segment should be shorter than the red one).\n"
"\n"
" Pressing any key (except ESC) will reset the tracking with a different speed.\n"
" Pressing ESC will stop the program.\n"
);
}
int main(int, char**)
{
help();
Mat img(500, 500, CV_8UC3);
KalmanFilter KF(2, 1, 0);
Mat state(2, 1, CV_32F); /* (phi, delta_phi) */
Mat processNoise(2, 1, CV_32F);
Mat measurement = Mat::zeros(1, 1, CV_32F);
char code = (char)-1;
for(;;)
{
randn( state, Scalar::all(0), Scalar::all(0.1) );
KF.transitionMatrix = *(Mat_<float>(2, 2) << 1, 1, 0, 1);
setIdentity(KF.measurementMatrix);
setIdentity(KF.processNoiseCov, Scalar::all(1e-5));
setIdentity(KF.measurementNoiseCov, Scalar::all(1e-1));
setIdentity(KF.errorCovPost, Scalar::all(1));
randn(KF.statePost, Scalar::all(0), Scalar::all(0.1));
for(;;)
{
Point2f center(img.cols*0.5f, img.rows*0.5f);
float R = img.cols/3.f;
double stateAngle = state.at<float>(0);
Point statePt = calcPoint(center, R, stateAngle);
Mat prediction = KF.predict();
double predictAngle = prediction.at<float>(0);
Point predictPt = calcPoint(center, R, predictAngle);
randn( measurement, Scalar::all(0), Scalar::all(KF.measurementNoiseCov.at<float>(0)));
// generate measurement
measurement += KF.measurementMatrix*state;
double measAngle = measurement.at<float>(0);
Point measPt = calcPoint(center, R, measAngle);
// plot points
#define drawCross( center, color, d ) \
line( img, Point( center.x - d, center.y - d ), \
Point( center.x + d, center.y + d ), color, 1, CV_AA, 0); \
line( img, Point( center.x + d, center.y - d ), \
Point( center.x - d, center.y + d ), color, 1, CV_AA, 0 )
img = Scalar::all(0);
drawCross( statePt, Scalar(255,255,255), 3 );
drawCross( measPt, Scalar(0,0,255), 3 );
drawCross( predictPt, Scalar(0,255,0), 3 );
line( img, statePt, measPt, Scalar(0,0,255), 3, CV_AA, 0 );
line( img, statePt, predictPt, Scalar(0,255,255), 3, CV_AA, 0 );
if(theRNG().uniform(0,4) != 0)
KF.correct(measurement);
randn( processNoise, Scalar(0), Scalar::all(sqrt(KF.processNoiseCov.at<float>(0, 0))));
state = KF.transitionMatrix*state + processNoise;
imshow( "Kalman", img );
code = (char)waitKey(100);
if( code > 0 )
break;
}
if( code == 27 || code == 'q' || code == 'Q' )
break;
}
return 0;
}
<|endoftext|>
|
<commit_before>
#include <ugdk/system/engine.h>
#include <ugdk/action/3D/camera.h>
#include <ugdk/input/events.h>
#include <ugdk/input/module.h>
#include <bulletworks/object.h>
#include <bulletworks/physicscene.h>
#include <bulletworks/manager.h>
#include <BtOgreGP.h>
#include <memory>
#include <OgreCamera.h>
#include <OgreEntity.h>
#include <OgreLogManager.h>
#include <OgreRoot.h>
#include <OgreViewport.h>
#include <OgreSceneManager.h>
#include <OgreRenderWindow.h>
#include <OgreConfigFile.h>
#include <OgreMeshManager.h>
#define AREA_RANGE 200.0
using std::unique_ptr;
bulletworks::PhysicScene *ourscene;
#define BIT(x) (1<<(x))
enum CollisionGroup {
HEADS = BIT(6),
WALLS = BIT(7),
WAT2 = BIT(8),
WAT3 = BIT(9),
WAT4 = BIT(10)
};
bulletworks::Object* createOgreHead(const std::string& name, bool useBox=false) {
Ogre::SceneManager *mSceneMgr = ourscene->manager();
bulletworks::Object::PhysicsData headData;
auto headEnt = mSceneMgr->createEntity(name, "Cube.mesh");
auto meshShapeConv = BtOgre::StaticMeshToShapeConverter(headEnt);
if (useBox)
headData.shape = meshShapeConv.createBox();
else
headData.shape = meshShapeConv.createSphere();
headData.mass = 80;
headData.collision_group = CollisionGroup::HEADS;
headData.collides_with = CollisionGroup::WALLS | CollisionGroup::HEADS;
auto head = new bulletworks::Object(*ourscene, headEnt, headData);
head->AddToScene(ourscene);
head->body()->setDamping(.4, .4);
return head;
}
bulletworks::Object* createWall(const std::string& name, const Ogre::Vector3& dir, double dist,
double width = AREA_RANGE, double height = AREA_RANGE) {
Ogre::SceneManager *mSceneMgr = ourscene->manager();
Ogre::Plane plane(dir, dist);
Ogre::MeshManager::getSingleton().createPlane(
name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, plane, width, height,
5, 5, true, 1, 5, 5, dir.perpendicular());
const std::string wat = name + "Entity";
Ogre::Entity* wallEnt = mSceneMgr->createEntity(wat, name);
wallEnt->setMaterialName("Ogre/Tusks");
bulletworks::Object::PhysicsData wallData;
wallData.shape = new btStaticPlaneShape(btVector3(dir.x, dir.y, dir.z), dist);
wallData.mass = 0;
wallData.collision_group = CollisionGroup::WALLS;
wallData.collides_with = CollisionGroup::HEADS;
auto wall = new bulletworks::Object(*ourscene, wallEnt, wallData);
wall->AddToScene(ourscene);
wall->body()->setFriction(1.7);
return wall;
}
int main(int argc, char* argv[]) {
ugdk::system::Configuration config;
config.base_path = "assets/";
ugdk::system::Initialize(config);
ourscene = new bulletworks::PhysicScene(btVector3(0, -10, 0));
ourscene->physics_manager()->set_debug_draw_enabled(true);
ourscene->ShowFrameStats();
auto head1 = createOgreHead("Head");
auto head2 = createOgreHead("Head2", true);
head2->Translate(0, 0, 80);
head2->body()->setAngularFactor(btVector3(0.0, 0.0, 0.0));
ourscene->camera()->AttachTo(*head2);
ourscene->camera()->SetParameters(Ogre::Vector3::ZERO, 5000);
ourscene->camera()->SetDistance(10);
createWall("ground", Ogre::Vector3::UNIT_Y, -(AREA_RANGE / 2));
ourscene->AddTask(ugdk::system::Task(
[head2](double dt) {
auto& keyboard = ugdk::input::manager()->keyboard();
Ogre::Vector3 move = Ogre::Vector3::ZERO;
if (keyboard.IsDown(ugdk::input::Scancode::D))
move.x += 1.0;
else if (keyboard.IsDown(ugdk::input::Scancode::A))
move.x += -1.0;
if (keyboard.IsDown(ugdk::input::Scancode::W))
move.z += -1.0;
else if (keyboard.IsDown(ugdk::input::Scancode::S))
move.z += 1.0;
move.normalise();
move = ourscene->camera()->actual_orientation() * move;
move.y = 0.0;
move.normalise();
head2->Move( move * 20 );
}
));
ourscene->event_handler().AddListener<ugdk::input::KeyPressedEvent>(
[head2] (const ugdk::input::KeyPressedEvent& ev) -> void {
if (ev.scancode == ugdk::input::Scancode::ESCAPE)
ourscene->Finish();
});
ourscene->event_handler().AddListener<ugdk::input::MouseMotionEvent>(
[](const ugdk::input::MouseMotionEvent& ev) -> void {
ourscene->camera()->Rotate(-ev.motion.x, -ev.motion.y);
});
ourscene->manager()->setAmbientLight(Ogre::ColourValue(.4, .4, .4));
ugdk::system::PushScene(unique_ptr<ugdk::action::Scene>(ourscene));
ugdk::system::Run();
ugdk::system::Release();
return 0;
}
<commit_msg>Following ugdk-3d's<commit_after>
#include <ugdk/system/engine.h>
#include <ugdk/action/3D/camera.h>
#include <ugdk/input/events.h>
#include <ugdk/input/module.h>
#include <bulletworks/object.h>
#include <bulletworks/physicscene.h>
#include <bulletworks/manager.h>
#include <bulletworks/component/physicsbody.h>
#include <BtOgreGP.h>
#include <memory>
#include <OgreCamera.h>
#include <OgreEntity.h>
#include <OgreLogManager.h>
#include <OgreRoot.h>
#include <OgreViewport.h>
#include <OgreSceneManager.h>
#include <OgreRenderWindow.h>
#include <OgreConfigFile.h>
#include <OgreMeshManager.h>
#define AREA_RANGE 200.0
using std::unique_ptr;
using std::shared_ptr;
using std::make_shared;
using bulletworks::component::PhysicsBody;
using bulletworks::component::Body;
bulletworks::PhysicScene *ourscene;
#define BIT(x) (1<<(x))
enum CollisionGroup {
HEADS = BIT(6),
WALLS = BIT(7),
WAT2 = BIT(8),
WAT3 = BIT(9),
WAT4 = BIT(10)
};
bulletworks::Object* createOgreHead(const std::string& name, bool useBox=false) {
Ogre::SceneManager *mSceneMgr = ourscene->manager();
bulletworks::component::PhysicsBody::PhysicsData headData;
auto headEnt = mSceneMgr->createEntity(name, "Cube.mesh");
auto meshShapeConv = BtOgre::StaticMeshToShapeConverter(headEnt);
if (useBox)
headData.shape = meshShapeConv.createBox();
else
headData.shape = meshShapeConv.createSphere();
headData.mass = 80;
headData.collision_group = CollisionGroup::HEADS;
headData.collides_with = CollisionGroup::WALLS | CollisionGroup::HEADS;
auto head = new bulletworks::Object(*ourscene, headEnt);
head->AddComponent(make_shared<PhysicsBody>(ourscene->physics_manager(), headData));
head->AddToScene(ourscene);
head->body()->setDamping(.4, .4);
return head;
}
bulletworks::Object* createWall(const std::string& name, const Ogre::Vector3& dir, double dist,
double width = AREA_RANGE, double height = AREA_RANGE) {
Ogre::SceneManager *mSceneMgr = ourscene->manager();
Ogre::Plane plane(dir, dist);
Ogre::MeshManager::getSingleton().createPlane(
name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, plane, width, height,
5, 5, true, 1, 5, 5, dir.perpendicular());
const std::string wat = name + "Entity";
Ogre::Entity* wallEnt = mSceneMgr->createEntity(wat, name);
wallEnt->setMaterialName("Ogre/Tusks");
bulletworks::component::PhysicsBody::PhysicsData wallData;
wallData.shape = new btStaticPlaneShape(btVector3(dir.x, dir.y, dir.z), dist);
wallData.mass = 0;
wallData.collision_group = CollisionGroup::WALLS;
wallData.collides_with = CollisionGroup::HEADS;
auto wall = new bulletworks::Object(*ourscene, wallEnt);
wall->AddComponent(make_shared<PhysicsBody>(ourscene->physics_manager(), wallData));
wall->AddToScene(ourscene);
wall->body()->setFriction(1.7);
return wall;
}
int main(int argc, char* argv[]) {
ugdk::system::Configuration config;
config.base_path = "assets/";
ugdk::system::Initialize(config);
ourscene = new bulletworks::PhysicScene(btVector3(0, -10, 0));
ourscene->physics_manager().set_debug_draw_enabled(true);
ourscene->ShowFrameStats();
auto head1 = createOgreHead("Head");
auto head2 = createOgreHead("Head2", true);
auto body2 = head2->GetComponent<PhysicsBody>();
body2->Translate(0, 0, 80);
body2->set_angular_factor(0.0, 0.0, 0.0);
ourscene->camera()->AttachTo(*head2);
ourscene->camera()->SetParameters(Ogre::Vector3::ZERO, 5000);
ourscene->camera()->SetDistance(10);
createWall("ground", Ogre::Vector3::UNIT_Y, -(AREA_RANGE / 2));
ourscene->AddTask(ugdk::system::Task(
[body2](double dt) {
auto& keyboard = ugdk::input::manager()->keyboard();
Ogre::Vector3 move = Ogre::Vector3::ZERO;
if (keyboard.IsDown(ugdk::input::Scancode::D))
move.x += 1.0;
else if (keyboard.IsDown(ugdk::input::Scancode::A))
move.x += -1.0;
if (keyboard.IsDown(ugdk::input::Scancode::W))
move.z += -1.0;
else if (keyboard.IsDown(ugdk::input::Scancode::S))
move.z += 1.0;
move.normalise();
move = ourscene->camera()->actual_orientation() * move;
move.y = 0.0;
move.normalise();
body2->bulletworks::component::Body::Move((move * 10));
}
));
ourscene->event_handler().AddListener<ugdk::input::KeyPressedEvent>(
[head2] (const ugdk::input::KeyPressedEvent& ev) -> void {
if (ev.scancode == ugdk::input::Scancode::ESCAPE)
ourscene->Finish();
});
ourscene->event_handler().AddListener<ugdk::input::MouseMotionEvent>(
[](const ugdk::input::MouseMotionEvent& ev) -> void {
ourscene->camera()->Rotate(-ev.motion.x, -ev.motion.y);
});
ourscene->manager()->setAmbientLight(Ogre::ColourValue(.4, .4, .4));
ugdk::system::PushScene(unique_ptr<ugdk::action::Scene>(ourscene));
ugdk::system::Run();
ugdk::system::Release();
return 0;
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2014, Intel Corporation
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 Intel Corporation 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.
*/
#define DBG(x)
#include <omp.h>
#include <malloc.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <algorithm>
// Signature of ispc-generated 'task' functions
typedef void (*TaskFuncType)(void *data, int threadIndex, int threadCount,
int taskIndex, int taskCount,
int taskIndex0, int taskIndex1, int taskIndex2,
int taskCount0, int taskCount1, int taskCount2);
// Small structure used to hold the data for each task
#ifdef _MSC_VER
__declspec(align(16))
#endif
struct TaskInfo {
TaskFuncType func;
void *data;
int taskIndex;
int taskCount3d[3];
#if defined(ISPC_IS_WINDOWS)
event taskEvent;
#endif
int taskCount() const { return taskCount3d[0]*taskCount3d[1]*taskCount3d[2]; }
int taskIndex0() const
{
return taskIndex % taskCount3d[0];
}
int taskIndex1() const
{
return ( taskIndex / taskCount3d[0] ) % taskCount3d[1];
}
int taskIndex2() const
{
return taskIndex / ( taskCount3d[0]*taskCount3d[1] );
}
int taskCount0() const { return taskCount3d[0]; }
int taskCount1() const { return taskCount3d[1]; }
int taskCount2() const { return taskCount3d[2]; }
TaskInfo() { assert(sizeof(TaskInfo) % 32 == 0); }
}
#ifndef _MSC_VER
__attribute__((aligned(32)));
#endif
;
// ispc expects these functions to have C linkage / not be mangled
extern "C" {
void ISPCLaunch(void **handlePtr, void *f, void *data, int countx, int county, int countz);
void *ISPCAlloc(void **handlePtr, int64_t size, int32_t alignment);
void ISPCSync(void *handle);
}
///////////////////////////////////////////////////////////////////////////
// TaskGroupBase
#define LOG_TASK_QUEUE_CHUNK_SIZE 14
#define MAX_TASK_QUEUE_CHUNKS 8
#define TASK_QUEUE_CHUNK_SIZE (1<<LOG_TASK_QUEUE_CHUNK_SIZE)
#define MAX_LAUNCHED_TASKS (MAX_TASK_QUEUE_CHUNKS * TASK_QUEUE_CHUNK_SIZE)
#define NUM_MEM_BUFFERS 16
class TaskGroup;
/** The TaskGroupBase structure provides common functionality for "task
groups"; a task group is the set of tasks launched from within a single
ispc function. When the function is ready to return, it waits for all
of the tasks in its task group to finish before it actually returns.
*/
class TaskGroupBase {
public:
void Reset();
int AllocTaskInfo(int count);
TaskInfo *GetTaskInfo(int index);
void *AllocMemory(int64_t size, int32_t alignment);
protected:
TaskGroupBase();
~TaskGroupBase();
int nextTaskInfoIndex;
private:
/* We allocate blocks of TASK_QUEUE_CHUNK_SIZE TaskInfo structures as
needed by the calling function. We hold up to MAX_TASK_QUEUE_CHUNKS
of these (and then exit at runtime if more than this many tasks are
launched.)
*/
TaskInfo *taskInfo[MAX_TASK_QUEUE_CHUNKS];
/* We also allocate chunks of memory to service ISPCAlloc() calls. The
memBuffers[] array holds pointers to this memory. The first element
of this array is initialized to point to mem and then any subsequent
elements required are initialized with dynamic allocation.
*/
int curMemBuffer, curMemBufferOffset;
int memBufferSize[NUM_MEM_BUFFERS];
char *memBuffers[NUM_MEM_BUFFERS];
char mem[256];
};
inline TaskGroupBase::TaskGroupBase() {
nextTaskInfoIndex = 0;
curMemBuffer = 0;
curMemBufferOffset = 0;
memBuffers[0] = mem;
memBufferSize[0] = sizeof(mem) / sizeof(mem[0]);
for (int i = 1; i < NUM_MEM_BUFFERS; ++i) {
memBuffers[i] = NULL;
memBufferSize[i] = 0;
}
for (int i = 0; i < MAX_TASK_QUEUE_CHUNKS; ++i)
taskInfo[i] = NULL;
}
inline TaskGroupBase::~TaskGroupBase() {
// Note: don't delete memBuffers[0], since it points to the start of
// the "mem" member!
for (int i = 1; i < NUM_MEM_BUFFERS; ++i)
delete[](memBuffers[i]);
}
inline void
TaskGroupBase::Reset() {
nextTaskInfoIndex = 0;
curMemBuffer = 0;
curMemBufferOffset = 0;
}
inline int
TaskGroupBase::AllocTaskInfo(int count) {
int ret = nextTaskInfoIndex;
nextTaskInfoIndex += count;
return ret;
}
inline TaskInfo *
TaskGroupBase::GetTaskInfo(int index) {
int chunk = (index >> LOG_TASK_QUEUE_CHUNK_SIZE);
int offset = index & (TASK_QUEUE_CHUNK_SIZE-1);
if (chunk == MAX_TASK_QUEUE_CHUNKS) {
fprintf(stderr, "A total of %d tasks have been launched from the "
"current function--the simple built-in task system can handle "
"no more. You can increase the values of TASK_QUEUE_CHUNK_SIZE "
"and LOG_TASK_QUEUE_CHUNK_SIZE to work around this limitation. "
"Sorry! Exiting.\n", index);
exit(1);
}
if (taskInfo[chunk] == NULL)
taskInfo[chunk] = new TaskInfo[TASK_QUEUE_CHUNK_SIZE];
return &taskInfo[chunk][offset];
}
inline void *
TaskGroupBase::AllocMemory(int64_t size, int32_t alignment) {
char *basePtr = memBuffers[curMemBuffer];
intptr_t iptr = (intptr_t)(basePtr + curMemBufferOffset);
iptr = (iptr + (alignment-1)) & ~(alignment-1);
int newOffset = int(iptr - (intptr_t)basePtr + size);
if (newOffset < memBufferSize[curMemBuffer]) {
curMemBufferOffset = newOffset;
return (char *)iptr;
}
++curMemBuffer;
curMemBufferOffset = 0;
assert(curMemBuffer < NUM_MEM_BUFFERS);
int allocSize = 1 << (12 + curMemBuffer);
allocSize = std::max(int(size+alignment), allocSize);
char *newBuf = new char[allocSize];
memBufferSize[curMemBuffer] = allocSize;
memBuffers[curMemBuffer] = newBuf;
return AllocMemory(size, alignment);
}
///////////////////////////////////////////////////////////////////////////
// Atomics and the like
static inline void
lMemFence() {
// Windows atomic functions already contain the fence
// KNC doesn't need the memory barrier
#if !defined ISPC_IS_KNC && !defined ISPC_IS_WINDOWS
__sync_synchronize();
#endif
}
static void *
lAtomicCompareAndSwapPointer(void **v, void *newValue, void *oldValue) {
#ifdef ISPC_IS_WINDOWS
return InterlockedCompareExchangePointer(v, newValue, oldValue);
#else
void *result = __sync_val_compare_and_swap(v, oldValue, newValue);
lMemFence();
return result;
#endif // ISPC_IS_WINDOWS
}
#if 0
static int32_t
lAtomicCompareAndSwap32(volatile int32_t *v, int32_t newValue, int32_t oldValue) {
#ifdef ISPC_IS_WINDOWS
return InterlockedCompareExchange((volatile LONG *)v, newValue, oldValue);
#else
int32_t result = __sync_val_compare_and_swap(v, oldValue, newValue);
lMemFence();
return result;
#endif // ISPC_IS_WINDOWS
}
#endif
static inline int32_t
lAtomicAdd(volatile int32_t *v, int32_t delta) {
#ifdef ISPC_IS_WINDOWS
return InterlockedExchangeAdd((volatile LONG *)v, delta)+delta;
#else
return __sync_fetch_and_add(v, delta);
#endif
}
///////////////////////////////////////////////////////////////////////////
class TaskGroup : public TaskGroupBase {
public:
void Launch(int baseIndex, int count);
void Sync();
};
///////////////////////////////////////////////////////////////////////////
// OpenMP
static void
InitTaskSystem() {
// No initialization needed
}
inline void
TaskGroup::Launch(int baseIndex, int count) {
#pragma omp parallel
{
const int threadIndex = omp_get_thread_num();
const int threadCount = omp_get_num_threads();
TaskInfo ti = *GetTaskInfo(baseIndex);
#pragma omp for schedule(runtime)
for(int i = 0; i < count; i++)
{
ti.taskIndex = i;
// Actually run the task.
ti.func(ti.data, threadIndex, threadCount, ti.taskIndex, ti.taskCount(),
ti.taskIndex0(), ti.taskIndex1(), ti.taskIndex2(),
ti.taskCount0(), ti.taskCount1(), ti.taskCount2());
}
}
}
inline void
TaskGroup::Sync() {
}
///////////////////////////////////////////////////////////////////////////
#define MAX_FREE_TASK_GROUPS 64
static TaskGroup *freeTaskGroups[MAX_FREE_TASK_GROUPS];
static inline TaskGroup *
AllocTaskGroup()
{
for (int i = 0; i < MAX_FREE_TASK_GROUPS; ++i) {
TaskGroup *tg = freeTaskGroups[i];
if (tg != NULL) {
void *ptr = lAtomicCompareAndSwapPointer((void **)(&freeTaskGroups[i]), NULL, tg);
if (ptr != NULL) {
return (TaskGroup *)ptr;
}
}
}
return new TaskGroup;
}
static inline void
FreeTaskGroup(TaskGroup *tg)
{
tg->Reset();
for (int i = 0; i < MAX_FREE_TASK_GROUPS; ++i) {
if (freeTaskGroups[i] == NULL) {
void *ptr = lAtomicCompareAndSwapPointer((void **)&freeTaskGroups[i], tg, NULL);
if (ptr == NULL)
return;
}
}
delete tg;
}
void
ISPCLaunch(void **taskGroupPtr, void *func, void *data, int count0, int count1, int count2)
{
const int count = count0*count1*count2;
TaskGroup *taskGroup;
if (*taskGroupPtr == NULL) {
InitTaskSystem();
taskGroup = AllocTaskGroup();
*taskGroupPtr = taskGroup;
}
else
taskGroup = (TaskGroup *)(*taskGroupPtr);
int baseIndex = taskGroup->AllocTaskInfo(count);
for (int i = 0; i < 1; ++i) {
TaskInfo *ti = taskGroup->GetTaskInfo(baseIndex+i);
ti->func = (TaskFuncType)func;
ti->data = data;
ti->taskIndex = i;
ti->taskCount3d[0] = count0;
ti->taskCount3d[1] = count1;
ti->taskCount3d[2] = count2;
}
taskGroup->Launch(baseIndex, count);
}
void
ISPCSync(void *h)
{
TaskGroup *taskGroup = (TaskGroup *)h;
if (taskGroup != NULL) {
taskGroup->Sync();
FreeTaskGroup(taskGroup);
}
}
void *
ISPCAlloc(void **taskGroupPtr, int64_t size, int32_t alignment)
{
TaskGroup *taskGroup;
if (*taskGroupPtr == NULL) {
InitTaskSystem();
taskGroup = AllocTaskGroup();
*taskGroupPtr = taskGroup;
}
else
taskGroup = (TaskGroup *)(*taskGroupPtr);
return taskGroup->AllocMemory(size, alignment);
}
<commit_msg>fix OSX compilation<commit_after>/*
Copyright (c) 2014, Intel Corporation
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 Intel Corporation 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.
*/
#define DBG(x)
#include <omp.h>
//#include <malloc.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <algorithm>
// Signature of ispc-generated 'task' functions
typedef void (*TaskFuncType)(void *data, int threadIndex, int threadCount,
int taskIndex, int taskCount,
int taskIndex0, int taskIndex1, int taskIndex2,
int taskCount0, int taskCount1, int taskCount2);
// Small structure used to hold the data for each task
#ifdef _MSC_VER
__declspec(align(16))
#endif
struct TaskInfo {
TaskFuncType func;
void *data;
int taskIndex;
int taskCount3d[3];
#if defined(ISPC_IS_WINDOWS)
event taskEvent;
#endif
int taskCount() const { return taskCount3d[0]*taskCount3d[1]*taskCount3d[2]; }
int taskIndex0() const
{
return taskIndex % taskCount3d[0];
}
int taskIndex1() const
{
return ( taskIndex / taskCount3d[0] ) % taskCount3d[1];
}
int taskIndex2() const
{
return taskIndex / ( taskCount3d[0]*taskCount3d[1] );
}
int taskCount0() const { return taskCount3d[0]; }
int taskCount1() const { return taskCount3d[1]; }
int taskCount2() const { return taskCount3d[2]; }
TaskInfo() { assert(sizeof(TaskInfo) % 32 == 0); }
}
#ifndef _MSC_VER
__attribute__((aligned(32)));
#endif
;
// ispc expects these functions to have C linkage / not be mangled
extern "C" {
void ISPCLaunch(void **handlePtr, void *f, void *data, int countx, int county, int countz);
void *ISPCAlloc(void **handlePtr, int64_t size, int32_t alignment);
void ISPCSync(void *handle);
}
///////////////////////////////////////////////////////////////////////////
// TaskGroupBase
#define LOG_TASK_QUEUE_CHUNK_SIZE 14
#define MAX_TASK_QUEUE_CHUNKS 8
#define TASK_QUEUE_CHUNK_SIZE (1<<LOG_TASK_QUEUE_CHUNK_SIZE)
#define MAX_LAUNCHED_TASKS (MAX_TASK_QUEUE_CHUNKS * TASK_QUEUE_CHUNK_SIZE)
#define NUM_MEM_BUFFERS 16
class TaskGroup;
/** The TaskGroupBase structure provides common functionality for "task
groups"; a task group is the set of tasks launched from within a single
ispc function. When the function is ready to return, it waits for all
of the tasks in its task group to finish before it actually returns.
*/
class TaskGroupBase {
public:
void Reset();
int AllocTaskInfo(int count);
TaskInfo *GetTaskInfo(int index);
void *AllocMemory(int64_t size, int32_t alignment);
protected:
TaskGroupBase();
~TaskGroupBase();
int nextTaskInfoIndex;
private:
/* We allocate blocks of TASK_QUEUE_CHUNK_SIZE TaskInfo structures as
needed by the calling function. We hold up to MAX_TASK_QUEUE_CHUNKS
of these (and then exit at runtime if more than this many tasks are
launched.)
*/
TaskInfo *taskInfo[MAX_TASK_QUEUE_CHUNKS];
/* We also allocate chunks of memory to service ISPCAlloc() calls. The
memBuffers[] array holds pointers to this memory. The first element
of this array is initialized to point to mem and then any subsequent
elements required are initialized with dynamic allocation.
*/
int curMemBuffer, curMemBufferOffset;
int memBufferSize[NUM_MEM_BUFFERS];
char *memBuffers[NUM_MEM_BUFFERS];
char mem[256];
};
inline TaskGroupBase::TaskGroupBase() {
nextTaskInfoIndex = 0;
curMemBuffer = 0;
curMemBufferOffset = 0;
memBuffers[0] = mem;
memBufferSize[0] = sizeof(mem) / sizeof(mem[0]);
for (int i = 1; i < NUM_MEM_BUFFERS; ++i) {
memBuffers[i] = NULL;
memBufferSize[i] = 0;
}
for (int i = 0; i < MAX_TASK_QUEUE_CHUNKS; ++i)
taskInfo[i] = NULL;
}
inline TaskGroupBase::~TaskGroupBase() {
// Note: don't delete memBuffers[0], since it points to the start of
// the "mem" member!
for (int i = 1; i < NUM_MEM_BUFFERS; ++i)
delete[](memBuffers[i]);
}
inline void
TaskGroupBase::Reset() {
nextTaskInfoIndex = 0;
curMemBuffer = 0;
curMemBufferOffset = 0;
}
inline int
TaskGroupBase::AllocTaskInfo(int count) {
int ret = nextTaskInfoIndex;
nextTaskInfoIndex += count;
return ret;
}
inline TaskInfo *
TaskGroupBase::GetTaskInfo(int index) {
int chunk = (index >> LOG_TASK_QUEUE_CHUNK_SIZE);
int offset = index & (TASK_QUEUE_CHUNK_SIZE-1);
if (chunk == MAX_TASK_QUEUE_CHUNKS) {
fprintf(stderr, "A total of %d tasks have been launched from the "
"current function--the simple built-in task system can handle "
"no more. You can increase the values of TASK_QUEUE_CHUNK_SIZE "
"and LOG_TASK_QUEUE_CHUNK_SIZE to work around this limitation. "
"Sorry! Exiting.\n", index);
exit(1);
}
if (taskInfo[chunk] == NULL)
taskInfo[chunk] = new TaskInfo[TASK_QUEUE_CHUNK_SIZE];
return &taskInfo[chunk][offset];
}
inline void *
TaskGroupBase::AllocMemory(int64_t size, int32_t alignment) {
char *basePtr = memBuffers[curMemBuffer];
intptr_t iptr = (intptr_t)(basePtr + curMemBufferOffset);
iptr = (iptr + (alignment-1)) & ~(alignment-1);
int newOffset = int(iptr - (intptr_t)basePtr + size);
if (newOffset < memBufferSize[curMemBuffer]) {
curMemBufferOffset = newOffset;
return (char *)iptr;
}
++curMemBuffer;
curMemBufferOffset = 0;
assert(curMemBuffer < NUM_MEM_BUFFERS);
int allocSize = 1 << (12 + curMemBuffer);
allocSize = std::max(int(size+alignment), allocSize);
char *newBuf = new char[allocSize];
memBufferSize[curMemBuffer] = allocSize;
memBuffers[curMemBuffer] = newBuf;
return AllocMemory(size, alignment);
}
///////////////////////////////////////////////////////////////////////////
// Atomics and the like
static inline void
lMemFence() {
// Windows atomic functions already contain the fence
// KNC doesn't need the memory barrier
#if !defined ISPC_IS_KNC && !defined ISPC_IS_WINDOWS
__sync_synchronize();
#endif
}
static void *
lAtomicCompareAndSwapPointer(void **v, void *newValue, void *oldValue) {
#ifdef ISPC_IS_WINDOWS
return InterlockedCompareExchangePointer(v, newValue, oldValue);
#else
void *result = __sync_val_compare_and_swap(v, oldValue, newValue);
lMemFence();
return result;
#endif // ISPC_IS_WINDOWS
}
#if 0
static int32_t
lAtomicCompareAndSwap32(volatile int32_t *v, int32_t newValue, int32_t oldValue) {
#ifdef ISPC_IS_WINDOWS
return InterlockedCompareExchange((volatile LONG *)v, newValue, oldValue);
#else
int32_t result = __sync_val_compare_and_swap(v, oldValue, newValue);
lMemFence();
return result;
#endif // ISPC_IS_WINDOWS
}
#endif
static inline int32_t
lAtomicAdd(volatile int32_t *v, int32_t delta) {
#ifdef ISPC_IS_WINDOWS
return InterlockedExchangeAdd((volatile LONG *)v, delta)+delta;
#else
return __sync_fetch_and_add(v, delta);
#endif
}
///////////////////////////////////////////////////////////////////////////
class TaskGroup : public TaskGroupBase {
public:
void Launch(int baseIndex, int count);
void Sync();
};
///////////////////////////////////////////////////////////////////////////
// OpenMP
static void
InitTaskSystem() {
// No initialization needed
}
inline void
TaskGroup::Launch(int baseIndex, int count) {
#pragma omp parallel
{
const int threadIndex = omp_get_thread_num();
const int threadCount = omp_get_num_threads();
TaskInfo ti = *GetTaskInfo(baseIndex);
#pragma omp for schedule(runtime)
for(int i = 0; i < count; i++)
{
ti.taskIndex = i;
// Actually run the task.
ti.func(ti.data, threadIndex, threadCount, ti.taskIndex, ti.taskCount(),
ti.taskIndex0(), ti.taskIndex1(), ti.taskIndex2(),
ti.taskCount0(), ti.taskCount1(), ti.taskCount2());
}
}
}
inline void
TaskGroup::Sync() {
}
///////////////////////////////////////////////////////////////////////////
#define MAX_FREE_TASK_GROUPS 64
static TaskGroup *freeTaskGroups[MAX_FREE_TASK_GROUPS];
static inline TaskGroup *
AllocTaskGroup()
{
for (int i = 0; i < MAX_FREE_TASK_GROUPS; ++i) {
TaskGroup *tg = freeTaskGroups[i];
if (tg != NULL) {
void *ptr = lAtomicCompareAndSwapPointer((void **)(&freeTaskGroups[i]), NULL, tg);
if (ptr != NULL) {
return (TaskGroup *)ptr;
}
}
}
return new TaskGroup;
}
static inline void
FreeTaskGroup(TaskGroup *tg)
{
tg->Reset();
for (int i = 0; i < MAX_FREE_TASK_GROUPS; ++i) {
if (freeTaskGroups[i] == NULL) {
void *ptr = lAtomicCompareAndSwapPointer((void **)&freeTaskGroups[i], tg, NULL);
if (ptr == NULL)
return;
}
}
delete tg;
}
void
ISPCLaunch(void **taskGroupPtr, void *func, void *data, int count0, int count1, int count2)
{
const int count = count0*count1*count2;
TaskGroup *taskGroup;
if (*taskGroupPtr == NULL) {
InitTaskSystem();
taskGroup = AllocTaskGroup();
*taskGroupPtr = taskGroup;
}
else
taskGroup = (TaskGroup *)(*taskGroupPtr);
int baseIndex = taskGroup->AllocTaskInfo(count);
for (int i = 0; i < 1; ++i) {
TaskInfo *ti = taskGroup->GetTaskInfo(baseIndex+i);
ti->func = (TaskFuncType)func;
ti->data = data;
ti->taskIndex = i;
ti->taskCount3d[0] = count0;
ti->taskCount3d[1] = count1;
ti->taskCount3d[2] = count2;
}
taskGroup->Launch(baseIndex, count);
}
void
ISPCSync(void *h)
{
TaskGroup *taskGroup = (TaskGroup *)h;
if (taskGroup != NULL) {
taskGroup->Sync();
FreeTaskGroup(taskGroup);
}
}
void *
ISPCAlloc(void **taskGroupPtr, int64_t size, int32_t alignment)
{
TaskGroup *taskGroup;
if (*taskGroupPtr == NULL) {
InitTaskSystem();
taskGroup = AllocTaskGroup();
*taskGroupPtr = taskGroup;
}
else
taskGroup = (TaskGroup *)(*taskGroupPtr);
return taskGroup->AllocMemory(size, alignment);
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ssbase_type.h"
void InitLinkList(LinkList* pList)
{
pList->pHead = NULL;
pList->pTail = NULL;
}
void FreeLinkList(LinkList* pList)
{
if (!pList)
return;
if (pList->iNodeCount)
{
LinkListNode* pCurrentNode;
LinkListNode* pNextNode;
pCurrentNode = pList->pHead;
while (TRUE)
{
pNextNode = pCurrentNode->pNext;
//free the data of current node
if (pCurrentNode->pData)
free(pCurrentNode->pData);
//free the current node
if (pCurrentNode)
free(pCurrentNode);
//if pNextNode is NULL, then the list is at the end. If not, set it to currnet node
if (pNextNode)
pCurrentNode = pNextNode;
else
break;
}
}
}
int AddNode(LinkList* pList, void* pData)
{
LinkListNode* pNewNode = (LinkListNode*)malloc(sizeof(LinkListNode));
pNewNode->pData = pData;
pNewNode->pNext = NULL;
if (!pList->iNodeCount)
{
pList->pHead = pNewNode;
pList->pTail = pNewNode;
}
else
{
pList->pTail->pNext = pNewNode;
pList->pTail = pNewNode;
}
pList->iNodeCount++;
//return NewNode's index
return pList->iNodeCount - 1;
}
int AddString(LinkList* pList, char* str)
{
LinkListNode* pNode = pList->pHead;
for (int i = 0; i < pList->iNodeCount; i++)
{
if (strcmp((char*)pNode->pData, str) == 0)
return i;
pNode = pNode->pNext;
}
char* newStr =(char*) malloc(strlen(str) + 1);
strcpy(newStr, str);
return AddNode(pList, newStr);
}
<commit_msg>doxygen comment<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ssbase_type.h"
#include "sstype.h"
/*
* @author Yang Kaidi
* @version 1.0
* @date 2015-02-16
* @{
*/
extern LinkList g_FunctionTable;
extern LinkList g_StringTable;
extern LinkList g_LabelTable;
extern LinkList g_SymbolTable;
/*
* @defgroup
* @{
*/
/*
* Add string into linklist
* @param [out] pList the linklist which will be inserted into
* @param [in] str a string to be inserted
* @return if str has bean already in the linklist, return the index of the string in the list.
* Otherwise, insert the string and return the new index;
*/
int AddString(LinkList* pList, char* str)
{
//Look through the linklist to find whether the string has been already in the list.
LinkListNode* pNode = pList->pHead;
for (int i = 0; i < pList->iNodeCount; i++)
{
if (strcmp((char*)pNode->pData, str) == 0)
return i;
pNode = pNode->pNext;
}
//Not in the list, so allocate space and add string into the list.
char* newStr =(char*) malloc(strlen(str) + 1);
strcpy(newStr, str);
return AddNode(pList, newStr);
}
/*
* Get a function's name according to its name
* @param [in] name function's name
* @return function node represented by the name
*/
FuncNode* GetFunctionByName(char* name)
{
if (g_FunctionTable.iNodeCount == 0)
return NULL;
//Look through the function table to find the specific function
LinkListNode* pCurrentNode = g_FunctionTable.pHead;
for (int i = 0; i < g_FunctionTable.iNodeCount; i++)
{
FuncNode* pCurrentFunc = (FuncNode*)pCurrentNode->pNext;
if (strcpy(pCurrentFunc->strName, name) == 0)
return pCurrentFunc;
//Move to next node in table
pCurrentNode = pCurrentNode->pNext;
}
//Can not find the specific function
return NULL;
}
/*
* Add Function into the global function table
* @param [in] name function's name
* @param [in] entryPoint function's entryPoint
* @return if the function has bean already in the table, return -1.
* Otherwise, insert a new function according to the name and entryPoint,
* and return the new index;
*/
int AddFunction(char* name, int entryPoint)
{
//if the function already exists in table, return -1
if (GetFunctionByName(name))
return -1;
//create a new function according to the name and entryPoint;
FuncNode* newFunc = (FuncNode*) malloc(sizeof(FuncNode));
strcpy(newFunc->strName, name);
newFunc->iEntryPoint = entryPoint;
//Get the index of the function in the global function table;
int index = AddNode(&g_FunctionTable, newFunc);
newFunc->iIndex = index;
return index;
}
/*
* Set the other info of a function node
* @param [in] name function's name
* @param [in] paramNum number of the function's parameter
* @param [in] function's data size
* @return void
*/
void SetFunctionInfo(char* name, int paramNum, int localDataSize)
{
//Get the function according to the name;
FuncNode* funcNode = GetFunctionByName(name);
funcNode->iParamCount = paramNum;
funcNode->iLocalDataSize = localDataSize;
}
/** @}*/ // Function Definition
/** @}*/ // File Type End
<|endoftext|>
|
<commit_before>#include "scope.h"
#include "details/grammar/nany.h"
#include "details/ir/emit.h"
using namespace Yuni;
namespace ny::ir::Producer {
bool Scope::visitASTExprTypeDecl(AST::Node& node, uint32_t& localvar) {
assert(node.rule == AST::rgTypeDecl);
localvar = 0;
if (node.children.size() == 1) {
auto& identifier = node.children[0];
if (identifier.children.empty()) {
if (identifier.text == "any") { // no real information, already 'any'
localvar = uint32_t(-1);
return true;
}
if (identifier.text == "void") {
localvar = 0;
return true;
}
}
else {
// anonymous / inline class definitnio
if (identifier.rule == AST::rgClass) {
//error(identifier) << "anonymous classes are not supported yet";
//return false;
return visitASTClass(identifier, &localvar);
}
}
}
ir::Producer::Scope scope{*this};
ir::emit::CodegenLocker codegenDisabler{ircode()};
return scope.visitASTExpr(node, localvar);
}
bool Scope::visitASTType(AST::Node& node, uint32_t& localvar) {
assert(node.rule == AST::rgType);
assert(not node.children.empty());
bool success = true;
bool reallyVoid = false;
bool isRef = false;
bool isConst = false;
localvar = 0; // reset
for (auto& child : node.children) {
switch (child.rule) {
case AST::rgTypeDecl: {
if (unlikely(localvar != 0))
return unexpectedNode(child, "[ir/new/several calls]");
bool status = visitASTExprTypeDecl(child, localvar);
success &= status;
if (status and localvar == 0)
reallyVoid = true;
break;
}
case AST::rgTypeQualifier: {
for (auto& qualifier : child.children) {
switch (qualifier.rule) {
case AST::rgRef:
isRef = true;
break;
case AST::rgConst:
isConst = true;
break;
case AST::rgCref:
isRef = true;
isConst = true;
break;
default:
success = unexpectedNode(child, "[ir/type-qualifier]");
}
}
break;
}
case AST::rgClass: {
break;
}
default:
success = unexpectedNode(child, "[ir/type]");
}
}
emitDebugpos(node);
auto& irout = ircode();
// create a value even if nothing to always have an attached value
if (localvar == 0 and not reallyVoid /*any*/)
localvar = ir::emit::alloc(irout, nextvar());
if (0 != localvar) {
if (localvar == (uint32_t) - 1)
localvar = ir::emit::alloc(irout, reserveLocalVariable());
ir::emit::type::qualifierRef(irout, localvar, isRef);
ir::emit::type::qualifierConst(irout, localvar, isConst);
}
return success;
}
} // ny::ir::Producer
<commit_msg>ast2ir: type: convert if to switch (for future additions)<commit_after>#include "scope.h"
#include "details/grammar/nany.h"
#include "details/ir/emit.h"
using namespace Yuni;
namespace ny::ir::Producer {
bool Scope::visitASTExprTypeDecl(AST::Node& node, uint32_t& localvar) {
assert(node.rule == AST::rgTypeDecl);
localvar = 0;
if (node.children.size() == 1) {
auto& identifier = node.children[0];
if (identifier.children.empty()) {
if (identifier.text == "any") { // no real information, already 'any'
localvar = uint32_t(-1);
return true;
}
if (identifier.text == "void") {
localvar = 0;
return true;
}
}
else {
switch (identifier.rule) {
case AST::rgClass: { // anonymous / inline class definitnio
//error(identifier) << "anonymous classes are not supported yet";
//return false;
return visitASTClass(identifier, &localvar);
}
default:
break;
}
}
}
ir::Producer::Scope scope{*this};
ir::emit::CodegenLocker codegenDisabler{ircode()};
return scope.visitASTExpr(node, localvar);
}
bool Scope::visitASTType(AST::Node& node, uint32_t& localvar) {
assert(node.rule == AST::rgType);
assert(not node.children.empty());
bool success = true;
bool reallyVoid = false;
bool isRef = false;
bool isConst = false;
localvar = 0; // reset
for (auto& child : node.children) {
switch (child.rule) {
case AST::rgTypeDecl: {
if (unlikely(localvar != 0))
return unexpectedNode(child, "[ir/new/several calls]");
bool status = visitASTExprTypeDecl(child, localvar);
success &= status;
if (status and localvar == 0)
reallyVoid = true;
break;
}
case AST::rgTypeQualifier: {
for (auto& qualifier : child.children) {
switch (qualifier.rule) {
case AST::rgRef:
isRef = true;
break;
case AST::rgConst:
isConst = true;
break;
case AST::rgCref:
isRef = true;
isConst = true;
break;
default:
success = unexpectedNode(child, "[ir/type-qualifier]");
}
}
break;
}
case AST::rgClass: {
break;
}
default:
success = unexpectedNode(child, "[ir/type]");
}
}
emitDebugpos(node);
auto& irout = ircode();
// create a value even if nothing to always have an attached value
if (localvar == 0 and not reallyVoid /*any*/)
localvar = ir::emit::alloc(irout, nextvar());
if (0 != localvar) {
if (localvar == (uint32_t) - 1)
localvar = ir::emit::alloc(irout, reserveLocalVariable());
ir::emit::type::qualifierRef(irout, localvar, isRef);
ir::emit::type::qualifierConst(irout, localvar, isConst);
}
return success;
}
} // ny::ir::Producer
<|endoftext|>
|
<commit_before>/* Copyright (C) 2013 Slawomir Cygan <slawomir.cygan@gmail.com>
*
* 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 "api-loader.h"
#include "pointers.h"
#include <string>
#include <vector>
#include <stdexcept>
#include <cstdlib>
#include <cassert>
#ifdef USE_DETOURS
#include "detours/detours.h"
#endif
#ifdef USE_MHOOK
#include "mhook/mhook-lib/mhook.h"
#endif
#include "gl-wrappers.h"
#include <DGLCommon/os.h>
#ifndef _WIN32
#include "dl-intercept.h"
#endif
#ifdef _WIN32
#define LIBGL_NAME "opengl32.dll"
#define LIBGLES1_NAME "libGLESv1_CM.dll"
#define LIBGLES2_NAME "libGLESv2.dll"
#define LIBEGL_NAME "libEGL.dll"
#define STRIP_VERSION(X) X
#elif defined(__ANDROID__)
//on Android libraries are not opened by SONAME
#define LIBGL_NAME "libGL.so"
#define LIBGLES1_NAME "libGLESv1_CM.so"
#define LIBGLES2_NAME "libGLESv2.so"
#define LIBEGL_NAME "libEGL.so"
#define STRIP_VERSION(X) X
#else
#define LIBGL_NAME "libGL.so.1"
#define LIBGLES1_NAME "libGLESv1_CM.so.1"
#define LIBGLES2_NAME "libGLESv2.so.1"
#define LIBEGL_NAME "libEGL.so.1"
#define STRIP_VERSION(X) std::string(X).substr(0, std::string(X).length() - strlen(".1"))
#endif
//here direct pointers are kept (pointers to entrypoints exposed by underlying OpenGL32 implementation
//use DIRECT_CALL(name) to call one of these pointers
LoadedPointer g_DirectPointers[Entrypoints_NUM] = {
#define FUNC_LIST_ELEM_SUPPORTED(name, type, library) { NULL, library},
#define FUNC_LIST_ELEM_NOT_SUPPORTED(name, type, library) FUNC_LIST_ELEM_SUPPORTED(name, type, library)
#include "codegen/functionList.inl"
#undef FUNC_LIST_ELEM_SUPPORTED
#undef FUNC_LIST_ELEM_NOT_SUPPORTED
};
APILoader::APILoader():m_LoadedApiLibraries(LIBRARY_NONE),m_GlueLibrary(LIBRARY_NONE) {}
FUNC_PTR APILoader::loadGLPointer(LoadedLib library, Entrypoint entryp) {
#ifdef _WIN32
return reinterpret_cast<FUNC_PTR>(GetProcAddress((HINSTANCE)library, GetEntryPointName(entryp)));
#else
//(int) -> see http://www.trilithium.com/johan/2004/12/problem-with-dlsym/
return reinterpret_cast<FUNC_PTR>((ptrdiff_t)dlsym(library, GetEntryPointName(entryp)));
#endif
}
bool APILoader::loadExtPointer(Entrypoint entryp) {
if (!g_DirectPointers[entryp].ptr) {
if (!m_GlueLibrary) {
throw std::runtime_error("Trying to call *GetProcAdress, but no glue library loaded");
}
FUNC_PTR ptr = NULL;
switch (m_GlueLibrary) {
#ifdef HAVE_LIBRARY_WGL
case LIBRARY_WGL:
ptr = reinterpret_cast<FUNC_PTR>(DIRECT_CALL(wglGetProcAddress)(GetEntryPointName(entryp)));
break;
#endif
#ifdef HAVE_LIBRARY_GLX
case LIBRARY_GLX:
ptr = reinterpret_cast<FUNC_PTR>(DIRECT_CALL(glXGetProcAddress)(
reinterpret_cast<const GLubyte*>(GetEntryPointName(entryp))));
break;
#endif
case LIBRARY_EGL:
ptr = reinterpret_cast<FUNC_PTR>(DIRECT_CALL(eglGetProcAddress)(GetEntryPointName(entryp)));
break;
default:
assert(!"unknown glue library");
}
g_DirectPointers[entryp].ptr = ptr;
}
return g_DirectPointers[entryp].ptr != NULL;
}
std::string APILoader::getLibraryName(ApiLibrary apiLibrary) {
switch (apiLibrary) {
case LIBRARY_EGL:
return LIBEGL_NAME;
case LIBRARY_GL:
case LIBRARY_WGL:
case LIBRARY_GLX:
return LIBGL_NAME;
case LIBRARY_ES1:
return LIBGLES1_NAME;
case LIBRARY_ES2:
case LIBRARY_ES3:
return LIBGLES2_NAME;
default:
assert(!"unknown library");
throw std::runtime_error("Unknown GL library name");
}
}
bool APILoader::isLibGL(const char* name) {
std::string nameStr(name);
bool ret = nameStr.find(STRIP_VERSION(LIBGL_NAME)) != std::string::npos ||
nameStr.find(STRIP_VERSION(LIBGLES1_NAME)) != std::string::npos ||
nameStr.find(STRIP_VERSION(LIBGLES2_NAME)) != std::string::npos ||
nameStr.find(STRIP_VERSION(LIBEGL_NAME)) != std::string::npos;
return ret;
}
void APILoader::setPointer(Entrypoint entryp, FUNC_PTR direct) {
if (entryp < NO_ENTRYPOINT) {
g_DirectPointers[entryp].ptr = direct;
}
}
void APILoader::loadLibrary(ApiLibrary apiLibrary) {
std::string libraryName = getLibraryName(apiLibrary);
if (m_LoadedLibraries.find(libraryName) == m_LoadedLibraries.end()) {
std::vector<std::string> libSearchPath;
LoadedLib openGLLibraryHandle = NULL;
libSearchPath.push_back("");
#ifdef _WIN32
char buffer[1000];
#ifndef _WIN64
if (GetSystemWow64Directory(buffer, sizeof(buffer)) > 0) {
//we are running 32bit app on 64 bit windows
libSearchPath.push_back(buffer + std::string("\\"));
}
#endif
if (!openGLLibraryHandle) {
if (GetSystemDirectory(buffer, sizeof(buffer)) > 0) {
//we are running on native system (32 on 32 or 64 on 64)
libSearchPath.push_back(buffer + std::string("\\"));
}
}
#ifndef _WIN64
libSearchPath.push_back("C:\\Windows\\SysWOW64\\");
#endif
libSearchPath.push_back("C:\\Windows\\System32\\");
libSearchPath.push_back(".");
#endif
for (size_t i = 0; i < libSearchPath.size() && !openGLLibraryHandle; i++) {
#ifdef _WIN32
openGLLibraryHandle = (LoadedLib)LoadLibrary((libSearchPath[i] + libraryName).c_str());
#else
openGLLibraryHandle = dlopen((libSearchPath[i] + libraryName).c_str(), RTLD_NOW);
#endif
}
if (!openGLLibraryHandle) {
std::string msg = std::string("Cannot load ") + libraryName + " system library";
Os::fatal(msg.c_str());
} else {
m_LoadedLibraries[libraryName] = openGLLibraryHandle;
}
}
LoadedLib library = m_LoadedLibraries[libraryName];
//we use MS Detours only on win32, on x64 mHook is used
#ifdef USE_DETOURS
DetourRestoreAfterWith();
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
#endif
//g_DirectPointers is now filled with opengl32.dll pointers
// we will now detour (hook) them all, so g_DirectPointers will still lead to original opengl32.dll, but
//application will always call us.
for (int i = 0; i < Entrypoints_NUM; i++) {
if (!(g_DirectPointers[i].libraryMask & apiLibrary)) {
//Do not load - entrypoint does not belong to currently loaded API
continue;
}
if (m_LoadedApiLibraries & g_DirectPointers[i].libraryMask) {
//Do not load - entrypoint belongs to already loaded API
continue;
}
//this sets g_DirectPointers[i].ptr
setPointer(i, loadGLPointer(library, i));
if (g_DirectPointers[i].ptr) {
//this entrypoint was loaded from OpenGL32.dll, detour it!
#if defined(USE_DETOURS) || defined(USE_MHOOK)
FUNC_PTR hookPtr = getWrapperPointer(i);
#endif
#ifdef USE_DETOURS
DetourAttach(&(PVOID&)g_DirectPointers[i].ptr, hookPtr);
#endif
#ifdef USE_MHOOK
if (!Mhook_SetHook(&(PVOID&)g_DirectPointers[i].ptr, hookPtr)) {
Os::fatal("Cannot hook %s() function.", GetEntryPointName(i));
}
#endif
}
}
#ifdef USE_DETOURS
DetourTransactionCommit();
#endif
if (apiLibrary == LIBRARY_EGL || apiLibrary == LIBRARY_WGL || apiLibrary == LIBRARY_GLX)
m_GlueLibrary = apiLibrary;
m_LoadedApiLibraries |= apiLibrary;
}
FUNC_PTR APILoader::ensurePointer(Entrypoint entryp) {
if (g_DirectPointers[entryp].ptr || loadExtPointer(entryp)) {
return g_DirectPointers[entryp].ptr;
} else {
std::string error = "Operation aborted, because the ";
error += GetEntryPointName(entryp);
error += " function is not available on current context. Try updating GPU drivers.";
throw std::runtime_error(error);
}
}
APILoader g_ApiLoader;
<commit_msg>Correct libGLESv2.so SONAME: it is .2, not .1<commit_after>/* Copyright (C) 2013 Slawomir Cygan <slawomir.cygan@gmail.com>
*
* 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 "api-loader.h"
#include "pointers.h"
#include <string>
#include <vector>
#include <stdexcept>
#include <cstdlib>
#include <cassert>
#ifdef USE_DETOURS
#include "detours/detours.h"
#endif
#ifdef USE_MHOOK
#include "mhook/mhook-lib/mhook.h"
#endif
#include "gl-wrappers.h"
#include <DGLCommon/os.h>
#ifndef _WIN32
#include "dl-intercept.h"
#endif
#ifdef _WIN32
#define LIBGL_NAME "opengl32.dll"
#define LIBGLES1_NAME "libGLESv1_CM.dll"
#define LIBGLES2_NAME "libGLESv2.dll"
#define LIBEGL_NAME "libEGL.dll"
#define STRIP_VERSION(X) X
#elif defined(__ANDROID__)
//on Android libraries are not opened by SONAME
#define LIBGL_NAME "libGL.so"
#define LIBGLES1_NAME "libGLESv1_CM.so"
#define LIBGLES2_NAME "libGLESv2.so"
#define LIBEGL_NAME "libEGL.so"
#define STRIP_VERSION(X) X
#else
#define LIBGL_NAME "libGL.so.1"
#define LIBGLES1_NAME "libGLESv1_CM.so.1"
#define LIBGLES2_NAME "libGLESv2.so.2"
#define LIBEGL_NAME "libEGL.so.1"
#define STRIP_VERSION(X) std::string(X).substr(0, std::string(X).length() - strlen(".1"))
#endif
//here direct pointers are kept (pointers to entrypoints exposed by underlying OpenGL32 implementation
//use DIRECT_CALL(name) to call one of these pointers
LoadedPointer g_DirectPointers[Entrypoints_NUM] = {
#define FUNC_LIST_ELEM_SUPPORTED(name, type, library) { NULL, library},
#define FUNC_LIST_ELEM_NOT_SUPPORTED(name, type, library) FUNC_LIST_ELEM_SUPPORTED(name, type, library)
#include "codegen/functionList.inl"
#undef FUNC_LIST_ELEM_SUPPORTED
#undef FUNC_LIST_ELEM_NOT_SUPPORTED
};
APILoader::APILoader():m_LoadedApiLibraries(LIBRARY_NONE),m_GlueLibrary(LIBRARY_NONE) {}
FUNC_PTR APILoader::loadGLPointer(LoadedLib library, Entrypoint entryp) {
#ifdef _WIN32
return reinterpret_cast<FUNC_PTR>(GetProcAddress((HINSTANCE)library, GetEntryPointName(entryp)));
#else
//(int) -> see http://www.trilithium.com/johan/2004/12/problem-with-dlsym/
return reinterpret_cast<FUNC_PTR>((ptrdiff_t)dlsym(library, GetEntryPointName(entryp)));
#endif
}
bool APILoader::loadExtPointer(Entrypoint entryp) {
if (!g_DirectPointers[entryp].ptr) {
if (!m_GlueLibrary) {
throw std::runtime_error("Trying to call *GetProcAdress, but no glue library loaded");
}
FUNC_PTR ptr = NULL;
switch (m_GlueLibrary) {
#ifdef HAVE_LIBRARY_WGL
case LIBRARY_WGL:
ptr = reinterpret_cast<FUNC_PTR>(DIRECT_CALL(wglGetProcAddress)(GetEntryPointName(entryp)));
break;
#endif
#ifdef HAVE_LIBRARY_GLX
case LIBRARY_GLX:
ptr = reinterpret_cast<FUNC_PTR>(DIRECT_CALL(glXGetProcAddress)(
reinterpret_cast<const GLubyte*>(GetEntryPointName(entryp))));
break;
#endif
case LIBRARY_EGL:
ptr = reinterpret_cast<FUNC_PTR>(DIRECT_CALL(eglGetProcAddress)(GetEntryPointName(entryp)));
break;
default:
assert(!"unknown glue library");
}
g_DirectPointers[entryp].ptr = ptr;
}
return g_DirectPointers[entryp].ptr != NULL;
}
std::string APILoader::getLibraryName(ApiLibrary apiLibrary) {
switch (apiLibrary) {
case LIBRARY_EGL:
return LIBEGL_NAME;
case LIBRARY_GL:
case LIBRARY_WGL:
case LIBRARY_GLX:
return LIBGL_NAME;
case LIBRARY_ES1:
return LIBGLES1_NAME;
case LIBRARY_ES2:
case LIBRARY_ES3:
return LIBGLES2_NAME;
default:
assert(!"unknown library");
throw std::runtime_error("Unknown GL library name");
}
}
bool APILoader::isLibGL(const char* name) {
std::string nameStr(name);
bool ret = nameStr.find(STRIP_VERSION(LIBGL_NAME)) != std::string::npos ||
nameStr.find(STRIP_VERSION(LIBGLES1_NAME)) != std::string::npos ||
nameStr.find(STRIP_VERSION(LIBGLES2_NAME)) != std::string::npos ||
nameStr.find(STRIP_VERSION(LIBEGL_NAME)) != std::string::npos;
return ret;
}
void APILoader::setPointer(Entrypoint entryp, FUNC_PTR direct) {
if (entryp < NO_ENTRYPOINT) {
g_DirectPointers[entryp].ptr = direct;
}
}
void APILoader::loadLibrary(ApiLibrary apiLibrary) {
std::string libraryName = getLibraryName(apiLibrary);
if (m_LoadedLibraries.find(libraryName) == m_LoadedLibraries.end()) {
std::vector<std::string> libSearchPath;
LoadedLib openGLLibraryHandle = NULL;
libSearchPath.push_back("");
#ifdef _WIN32
char buffer[1000];
#ifndef _WIN64
if (GetSystemWow64Directory(buffer, sizeof(buffer)) > 0) {
//we are running 32bit app on 64 bit windows
libSearchPath.push_back(buffer + std::string("\\"));
}
#endif
if (!openGLLibraryHandle) {
if (GetSystemDirectory(buffer, sizeof(buffer)) > 0) {
//we are running on native system (32 on 32 or 64 on 64)
libSearchPath.push_back(buffer + std::string("\\"));
}
}
#ifndef _WIN64
libSearchPath.push_back("C:\\Windows\\SysWOW64\\");
#endif
libSearchPath.push_back("C:\\Windows\\System32\\");
libSearchPath.push_back(".");
#endif
for (size_t i = 0; i < libSearchPath.size() && !openGLLibraryHandle; i++) {
#ifdef _WIN32
openGLLibraryHandle = (LoadedLib)LoadLibrary((libSearchPath[i] + libraryName).c_str());
#else
openGLLibraryHandle = dlopen((libSearchPath[i] + libraryName).c_str(), RTLD_NOW);
#endif
}
if (!openGLLibraryHandle) {
std::string msg = std::string("Cannot load ") + libraryName + " system library";
Os::fatal(msg.c_str());
} else {
m_LoadedLibraries[libraryName] = openGLLibraryHandle;
}
}
LoadedLib library = m_LoadedLibraries[libraryName];
//we use MS Detours only on win32, on x64 mHook is used
#ifdef USE_DETOURS
DetourRestoreAfterWith();
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
#endif
//g_DirectPointers is now filled with opengl32.dll pointers
// we will now detour (hook) them all, so g_DirectPointers will still lead to original opengl32.dll, but
//application will always call us.
for (int i = 0; i < Entrypoints_NUM; i++) {
if (!(g_DirectPointers[i].libraryMask & apiLibrary)) {
//Do not load - entrypoint does not belong to currently loaded API
continue;
}
if (m_LoadedApiLibraries & g_DirectPointers[i].libraryMask) {
//Do not load - entrypoint belongs to already loaded API
continue;
}
//this sets g_DirectPointers[i].ptr
setPointer(i, loadGLPointer(library, i));
if (g_DirectPointers[i].ptr) {
//this entrypoint was loaded from OpenGL32.dll, detour it!
#if defined(USE_DETOURS) || defined(USE_MHOOK)
FUNC_PTR hookPtr = getWrapperPointer(i);
#endif
#ifdef USE_DETOURS
DetourAttach(&(PVOID&)g_DirectPointers[i].ptr, hookPtr);
#endif
#ifdef USE_MHOOK
if (!Mhook_SetHook(&(PVOID&)g_DirectPointers[i].ptr, hookPtr)) {
Os::fatal("Cannot hook %s() function.", GetEntryPointName(i));
}
#endif
}
}
#ifdef USE_DETOURS
DetourTransactionCommit();
#endif
if (apiLibrary == LIBRARY_EGL || apiLibrary == LIBRARY_WGL || apiLibrary == LIBRARY_GLX)
m_GlueLibrary = apiLibrary;
m_LoadedApiLibraries |= apiLibrary;
}
FUNC_PTR APILoader::ensurePointer(Entrypoint entryp) {
if (g_DirectPointers[entryp].ptr || loadExtPointer(entryp)) {
return g_DirectPointers[entryp].ptr;
} else {
std::string error = "Operation aborted, because the ";
error += GetEntryPointName(entryp);
error += " function is not available on current context. Try updating GPU drivers.";
throw std::runtime_error(error);
}
}
APILoader g_ApiLoader;
<|endoftext|>
|
<commit_before>#include "nlt_store.hpp"
namespace nark { namespace db { namespace dfadb {
NARK_DB_REGISTER_STORE("nlt", NestLoudsTrieStore);
NestLoudsTrieStore::NestLoudsTrieStore() {
}
NestLoudsTrieStore::~NestLoudsTrieStore() {
}
llong NestLoudsTrieStore::dataStorageSize() const {
return m_store->mem_size();
}
llong NestLoudsTrieStore::numDataRows() const {
return m_store->num_records();
}
void NestLoudsTrieStore::getValueAppend(llong id, valvec<byte>* val, DbContext* ctx) const {
m_store->get_record_append(size_t(id), val);
}
StoreIterator* NestLoudsTrieStore::createStoreIterForward(DbContext*) const {
return nullptr; // not needed
}
StoreIterator* NestLoudsTrieStore::createStoreIterBackward(DbContext*) const {
return nullptr; // not needed
}
void NestLoudsTrieStore::build(SortableStrVec& strVec) {
NestLoudsTrieConfig conf;
// conf.maxFragLen = 512;
conf.initFromEnv();
m_store.reset(new NestLoudsTrieDataStore_SE_512());
m_store->build_from(strVec, conf);
}
void NestLoudsTrieStore::load(PathRef path) {
std::string fpath = fstring(path.string()).endsWith(".nlt")
? path.string()
: path.string() + ".nlt";
std::unique_ptr<BaseDFA> dfa(BaseDFA::load_mmap(fpath.c_str()));
m_store.reset(dynamic_cast<NestLoudsTrieDataStore_SE_512*>(dfa.get()));
if (m_store) {
dfa.release();
}
}
void NestLoudsTrieStore::save(PathRef path) const {
std::string fpath = fstring(path.string()).endsWith(".nlt")
? path.string()
: path.string() + ".nlt";
m_store->save_mmap(fpath.c_str());
}
}}} // namespace nark::db::dfadb
<commit_msg>Minor fix src/nark/db/dfadb/nlt_store.cpp<commit_after>#include "nlt_store.hpp"
#include <typeinfo>
namespace nark { namespace db { namespace dfadb {
NARK_DB_REGISTER_STORE("nlt", NestLoudsTrieStore);
NestLoudsTrieStore::NestLoudsTrieStore() {
}
NestLoudsTrieStore::~NestLoudsTrieStore() {
}
llong NestLoudsTrieStore::dataStorageSize() const {
return m_store->mem_size();
}
llong NestLoudsTrieStore::numDataRows() const {
return m_store->num_records();
}
void NestLoudsTrieStore::getValueAppend(llong id, valvec<byte>* val, DbContext* ctx) const {
m_store->get_record_append(size_t(id), val);
}
StoreIterator* NestLoudsTrieStore::createStoreIterForward(DbContext*) const {
return nullptr; // not needed
}
StoreIterator* NestLoudsTrieStore::createStoreIterBackward(DbContext*) const {
return nullptr; // not needed
}
void NestLoudsTrieStore::build(SortableStrVec& strVec) {
NestLoudsTrieConfig conf;
// conf.maxFragLen = 512;
conf.initFromEnv();
m_store.reset(new NestLoudsTrieDataStore_SE_512());
m_store->build_from(strVec, conf);
}
void NestLoudsTrieStore::load(PathRef path) {
std::string fpath = fstring(path.string()).endsWith(".nlt")
? path.string()
: path.string() + ".nlt";
std::unique_ptr<BaseDFA> dfa(BaseDFA::load_mmap(fpath.c_str()));
m_store.reset(dynamic_cast<NestLoudsTrieDataStore_SE_512*>(dfa.get()));
if (m_store) {
dfa.release();
}
else {
THROW_STD(invalid_argument
, "FATAL: file: %s is %s, not a NestLoudsTrieDataStore_SE_512"
, typeid(*dfa).name(), fpath.c_str());
}
}
void NestLoudsTrieStore::save(PathRef path) const {
std::string fpath = fstring(path.string()).endsWith(".nlt")
? path.string()
: path.string() + ".nlt";
m_store->save_mmap(fpath.c_str());
}
}}} // namespace nark::db::dfadb
<|endoftext|>
|
<commit_before>#include "oddlib/compressiontype2.hpp"
#include "oddlib/stream.hpp"
#include "logger.hpp"
namespace Oddlib
{
static bool ExpandElement(Sint32& remainingCount, Uint8*& src, Uint32*& dst)
{
if (!remainingCount)
{
return false;
}
const Sint32 src_word = *src | (*(Uint16 *)(src + 1) << 8);
++dst;
src += 3;
remainingCount--;
*(dst - 1) = 4 * (Uint16)src_word & 0x3F00 | src_word & 0x3F | 16 * src_word & 0x3F0000 | 4 * (16 * src_word & 0xFC00000);
return true;
}
// Function 0x0040AA50 in AE
std::vector<Uint8> CompressionType2::Decompress(IStream& stream, Uint32 finalW, Uint32 /*w*/, Uint32 h, Uint32 dataSize)
{
std::vector<Uint8> ret(finalW*h);
std::vector<Uint8> s(dataSize);
stream.ReadBytes(s.data(), s.size());
Sint32 dwords_left = dataSize / 4;
Sint32 remainder = dataSize % 4;
Uint32 *dst = (Uint32*)ret.data();
Uint8 *src = s.data();
if (dwords_left > 0)
{
dst = (Uint32*)ret.data();
src = s.data();
do
{
for (int i = 0; i < 4; i++)
{
if (!ExpandElement(dwords_left, src, dst))
{
break;
}
}
} while (dwords_left);
}
while (remainder)
{
remainder--;
*(Uint8 *)dst = *src;
dst = (Uint32 *)((char *)dst + 1);
++src;
}
return ret;
}
}
<commit_msg>refactor for bounds saftey<commit_after>#include "oddlib/compressiontype2.hpp"
#include "oddlib/stream.hpp"
#include "logger.hpp"
namespace Oddlib
{
static bool Expand3To4Bytes(Sint32& remainingCount, IStream& stream, std::vector<Uint8>& ret, Uint32& dstPos)
{
if (!remainingCount)
{
return false;
}
const Sint32 src3Bytes = ReadUInt8(stream) | (ReadUint16(stream) << 8);
remainingCount--;
// TODO: Should write each byte by itself
const Uint32 value = 4 * (Uint16)src3Bytes & 0x3F00 | src3Bytes & 0x3F | 16 * src3Bytes & 0x3F0000 | 4 * (16 * src3Bytes & 0xFC00000);
*reinterpret_cast<Uint32*>(&ret[dstPos]) = value;
dstPos += 4;
return true;
}
// Function 0x0040AA50 in AE
std::vector<Uint8> CompressionType2::Decompress(IStream& stream, Uint32 finalW, Uint32 /*w*/, Uint32 h, Uint32 dataSize)
{
std::vector<Uint8> ret(finalW*h);
Sint32 dwords_left = dataSize / 4;
Sint32 remainder = dataSize % 4;
Uint32 dstPos = 0;
if (dwords_left > 0)
{
do
{
for (int i = 0; i < 4; i++)
{
if (!Expand3To4Bytes(dwords_left, stream, ret, dstPos))
{
break;
}
}
} while (dwords_left);
}
// TODO: Branch not tested
while (remainder)
{
remainder--;
ret[dstPos++] = ReadUInt8(stream);
}
return ret;
}
}
<|endoftext|>
|
<commit_before>
#include <vector>
#include <string>
using namespace std;
namespace L10ns {
enum class ActionKind {
None,
Init,
Update,
Log,
Set,
};
enum class FlagKind {
None,
Help,
Version,
Language,
Key,
Value,
};
struct Argument {
string * name;
string * description;
Argument(string * pname, string * pdescription) {
name = pname;
description = pdescription;
}
};
struct Flag : Argument {
string * alias;
bool hasValue;
FlagKind kind;
string value;
Flag(FlagKind pkind, const char pname[], const char palias[], const char pdescription[], bool phasValue)
: kind(pkind), Argument(new string(pname), new string(pdescription)), alias(new string(palias)) {
hasValue = phasValue;
value = "";
}
};
struct Action : Argument {
vector<Flag> * flags;
ActionKind kind;
Action(ActionKind pkind, const char pname[], const char pdescription[], vector<Flag> * pflags)
: kind(pkind), Argument(new string(pname), new string(pdescription)) {
if (pflags != NULL) {
flags = pflags;
}
}
};
static Flag helpFlag = Flag(FlagKind::Help, "--help", "-h", "Print help description.", /*hasValue*/ false);
static Flag languageFlag = Flag(FlagKind::Language, "--language", "-l", "Specify language.", false);
static vector<Flag> defaultFlags = {
helpFlag,
Flag(FlagKind::Version, "--version", "-v", "Print current version.", /*hasValue*/ false),
};
static vector<Flag> helpFlags = {
helpFlag,
};
static vector<Flag> setFlags = {
Flag(FlagKind::Key, "--key", "-k", "Specify localization key.", /*hasValue*/ true),
Flag(FlagKind::Value, "--value", "-v", "Specify localization value.", /*hasValue*/ true),
languageFlag,
helpFlag,
};
static vector<Flag> logFlags = {
languageFlag,
helpFlag,
};
static vector<Action> actions = {
Action(ActionKind::Init, "init", "Initialize project.", &helpFlags),
Action(ActionKind::Update, "update", "Update localization keys.", &helpFlags),
Action(ActionKind::Log, "log", "Show latest added localizations.", &logFlags),
Action(ActionKind::Set, "set", "Set localization.", &setFlags),
};
struct Command {
bool isRequestingHelp;
bool isRequestingVersion;
ActionKind action;
vector<Flag> * flags;
Command()
: isRequestingHelp(false)
, isRequestingVersion(false)
, action(ActionKind::None)
, flags(&defaultFlags) {
}
};
void setCommandFlag(Command *command, const Flag *flag, char *value = NULL) {
switch (flag->kind) {
case FlagKind::Help:
command->isRequestingHelp = true;
return;
case FlagKind::Version:
command->isRequestingVersion = true;
return;
default:
return;
}
}
Command* parseCommandArguments(int argc, char* argv[]) {
Command * command = new Command();
// Flag to optimize has action parsing.
bool hasAction = false;
// The option flag that is pending for a value.
const Flag * flagWhichAwaitsValue = NULL;
for (int argIndex = 1; argIndex < argc; argIndex++) {
auto arg = argv[argIndex];
if (!hasAction) {
for (auto const& a : actions) {
if (strcmp(a.name->c_str(), arg) == 0) {
command->action = a.kind;
hasAction = true;
command->flags = a.flags;
break;
}
}
}
if (flagWhichAwaitsValue == NULL) {
for (auto const& flag : *command->flags) {
if (strcmp(flag.name->c_str(), arg) == 0 || (flag.alias->length() != 0 && strcmp(flag.name->c_str(), arg) == 0)) {
if (flag.hasValue) {
flagWhichAwaitsValue = &flag;
}
setCommandFlag(command, &flag);
break;
}
}
}
else {
setCommandFlag(command, flagWhichAwaitsValue, arg);
flagWhichAwaitsValue = NULL;
continue;
}
}
return command;
}
} // L10ns
<commit_msg>Removes short alias of version<commit_after>
#include <vector>
#include <string>
using namespace std;
namespace L10ns {
enum class ActionKind {
None,
Init,
Update,
Log,
Set,
};
enum class FlagKind {
None,
Help,
Version,
Language,
Key,
Value,
};
struct Argument {
string * name;
string * description;
Argument(string * pname, string * pdescription) {
name = pname;
description = pdescription;
}
};
struct Flag : Argument {
string * alias;
bool hasValue;
FlagKind kind;
string value;
Flag(FlagKind pkind, const char pname[], const char palias[], const char pdescription[], bool phasValue)
: kind(pkind), Argument(new string(pname), new string(pdescription)), alias(new string(palias)) {
hasValue = phasValue;
value = "";
}
};
struct Action : Argument {
vector<Flag> * flags;
ActionKind kind;
Action(ActionKind pkind, const char pname[], const char pdescription[], vector<Flag> * pflags)
: kind(pkind), Argument(new string(pname), new string(pdescription)) {
if (pflags != NULL) {
flags = pflags;
}
}
};
static Flag helpFlag = Flag(FlagKind::Help, "--help", "-h", "Print help description.", /*hasValue*/ false);
static Flag languageFlag = Flag(FlagKind::Language, "--language", "-l", "Specify language.", false);
static vector<Flag> defaultFlags = {
helpFlag,
Flag(FlagKind::Version, "--version", "", "Print current version.", /*hasValue*/ false),
};
static vector<Flag> helpFlags = {
helpFlag,
};
static vector<Flag> setFlags = {
Flag(FlagKind::Key, "--key", "-k", "Specify localization key.", /*hasValue*/ true),
Flag(FlagKind::Value, "--value", "-v", "Specify localization value.", /*hasValue*/ true),
languageFlag,
helpFlag,
};
static vector<Flag> logFlags = {
languageFlag,
helpFlag,
};
static vector<Action> actions = {
Action(ActionKind::Init, "init", "Initialize project.", &helpFlags),
Action(ActionKind::Update, "update", "Update localization keys.", &helpFlags),
Action(ActionKind::Log, "log", "Show latest added localizations.", &logFlags),
Action(ActionKind::Set, "set", "Set localization.", &setFlags),
};
struct Command {
bool isRequestingHelp;
bool isRequestingVersion;
ActionKind action;
vector<Flag> * flags;
Command()
: isRequestingHelp(false)
, isRequestingVersion(false)
, action(ActionKind::None)
, flags(&defaultFlags) {
}
};
void setCommandFlag(Command *command, const Flag *flag, char *value = NULL) {
switch (flag->kind) {
case FlagKind::Help:
command->isRequestingHelp = true;
return;
case FlagKind::Version:
command->isRequestingVersion = true;
return;
default:
return;
}
}
Command* parseCommandArguments(int argc, char* argv[]) {
Command * command = new Command();
// Flag to optimize has action parsing.
bool hasAction = false;
// The option flag that is pending for a value.
const Flag * flagWhichAwaitsValue = NULL;
for (int argIndex = 1; argIndex < argc; argIndex++) {
auto arg = argv[argIndex];
if (!hasAction) {
for (auto const& a : actions) {
if (strcmp(a.name->c_str(), arg) == 0) {
command->action = a.kind;
hasAction = true;
command->flags = a.flags;
break;
}
}
}
if (flagWhichAwaitsValue == NULL) {
for (auto const& flag : *command->flags) {
if (strcmp(flag.name->c_str(), arg) == 0 || (flag.alias->length() != 0 && strcmp(flag.name->c_str(), arg) == 0)) {
if (flag.hasValue) {
flagWhichAwaitsValue = &flag;
}
setCommandFlag(command, &flag);
break;
}
}
}
else {
setCommandFlag(command, flagWhichAwaitsValue, arg);
flagWhichAwaitsValue = NULL;
continue;
}
}
return command;
}
} // L10ns
<|endoftext|>
|
<commit_before>
#include <vector>
#include <string>
using namespace std;
namespace L10ns {
enum class ActionKind {
None,
Init,
Update,
Log,
Set,
};
enum class FlagKind {
None,
Help,
Version,
Language,
Key,
Value,
};
struct Argument {
string * name;
string * description;
Argument(string * pname, string * pdescription) {
name = pname;
description = pdescription;
}
};
struct Flag : Argument {
string * alias;
bool hasValue;
FlagKind kind;
string value;
Flag(FlagKind pkind, const char pname[], const char palias[], const char pdescription[], bool phasValue)
: kind(pkind), Argument(new string(pname), new string(pdescription)), alias(new string(palias)) {
hasValue = phasValue;
value = "";
}
};
struct Action : Argument {
vector<Flag> * flags;
ActionKind kind;
string * info;
Action(ActionKind pkind, const char pname[], const char pdescription[], const char pinfo[],vector<Flag> * pflags)
: kind(pkind), Argument(new string(pname), new string(pdescription)), info(new string(pinfo)) {
if (pflags != NULL) {
flags = pflags;
}
}
};
static Flag helpFlag = Flag(FlagKind::Help, "--help", "-h", "Print help description.", /*hasValue*/ false);
static Flag languageFlag = Flag(FlagKind::Language, "--language", "-l", "Specify language.", false);
static vector<Flag> defaultFlags = {
helpFlag,
Flag(FlagKind::Version, "--version", "", "Print current version.", /*hasValue*/ false),
};
static vector<Flag> helpFlags = {
helpFlag,
};
static vector<Flag> setFlags = {
Flag(FlagKind::Key, "--key", "-k", "Specify localization key.", /*hasValue*/ true),
Flag(FlagKind::Value, "--value", "-v", "Specify localization value.", /*hasValue*/ true),
languageFlag,
helpFlag,
};
static vector<Flag> logFlags = {
languageFlag,
helpFlag,
};
static const char * initInfo =
"Initialize a L10ns project. This command creates on 'l10ns.json' "
"file, with sane default options applied.";
static const char * updateInfo =
"Initialize a L10ns project. This command creates on 'l10ns.json' "
"file, with sane default options applied.";
static const char * logInfo =
"Initialize a L10ns project. This command creates on 'l10ns.json' "
"file, with sane default options applied.";
static const char * setInfo =
"Initialize a L10ns project. This command creates on 'l10ns.json' "
"file, with sane default options applied.";
static vector<Action> actions = {
Action(ActionKind::Init, "init", "Initialize project.", initInfo, &helpFlags),
Action(ActionKind::Update, "update", "Update localization keys.", updateInfo, &helpFlags),
Action(ActionKind::Log, "log", "Show latest added localizations.", logInfo, &logFlags),
Action(ActionKind::Set, "set", "Set localization.", setInfo, &setFlags),
};
struct Command {
bool isRequestingHelp;
bool isRequestingVersion;
ActionKind action;
vector<Flag> * flags;
Command()
: isRequestingHelp(false)
, isRequestingVersion(false)
, action(ActionKind::None)
, flags(&defaultFlags) {
}
};
void setCommandFlag(Command *command, const Flag *flag, char *value = NULL) {
switch (flag->kind) {
case FlagKind::Help:
command->isRequestingHelp = true;
return;
case FlagKind::Version:
command->isRequestingVersion = true;
return;
default:
return;
}
}
Command* parseCommandArguments(int argc, char* argv[]) {
Command * command = new Command();
// Flag to optimize has action parsing.
bool hasAction = false;
// The option flag that is pending for a value.
const Flag * flagWhichAwaitsValue = NULL;
for (int argIndex = 1; argIndex < argc; argIndex++) {
auto arg = argv[argIndex];
if (!hasAction) {
for (auto const& a : actions) {
if (strcmp(a.name->c_str(), arg) == 0) {
command->action = a.kind;
hasAction = true;
command->flags = a.flags;
break;
}
}
}
if (flagWhichAwaitsValue == NULL) {
for (auto const& flag : *command->flags) {
if (strcmp(flag.name->c_str(), arg) == 0 || (flag.alias->length() != 0 && strcmp(flag.name->c_str(), arg) == 0)) {
if (flag.hasValue) {
flagWhichAwaitsValue = &flag;
}
setCommandFlag(command, &flag);
break;
}
}
}
else {
setCommandFlag(command, flagWhichAwaitsValue, arg);
flagWhichAwaitsValue = NULL;
continue;
}
}
return command;
}
} // L10ns
<commit_msg>Fixes info<commit_after>
#include <vector>
#include <string>
using namespace std;
namespace L10ns {
enum class ActionKind {
None,
Init,
Update,
Log,
Set,
};
enum class FlagKind {
None,
Help,
Version,
Language,
Key,
Value,
};
struct Argument {
string * name;
string * description;
Argument(string * pname, string * pdescription) {
name = pname;
description = pdescription;
}
};
struct Flag : Argument {
string * alias;
bool hasValue;
FlagKind kind;
string value;
Flag(FlagKind pkind, const char pname[], const char palias[], const char pdescription[], bool phasValue)
: kind(pkind), Argument(new string(pname), new string(pdescription)), alias(new string(palias)) {
hasValue = phasValue;
value = "";
}
};
struct Action : Argument {
vector<Flag> * flags;
ActionKind kind;
string * info;
Action(ActionKind pkind, const char pname[], const char pdescription[], const char pinfo[],vector<Flag> * pflags)
: kind(pkind), Argument(new string(pname), new string(pdescription)), info(new string(pinfo)) {
if (pflags != NULL) {
flags = pflags;
}
}
};
static Flag helpFlag = Flag(FlagKind::Help, "--help", "-h", "Print help description.", /*hasValue*/ false);
static Flag languageFlag = Flag(FlagKind::Language, "--language", "-l", "Specify language.", false);
static vector<Flag> defaultFlags = {
helpFlag,
Flag(FlagKind::Version, "--version", "", "Print current version.", /*hasValue*/ false),
};
static vector<Flag> helpFlags = {
helpFlag,
};
static vector<Flag> setFlags = {
Flag(FlagKind::Key, "--key", "-k", "Specify localization key.", /*hasValue*/ true),
Flag(FlagKind::Value, "--value", "-v", "Specify localization value.", /*hasValue*/ true),
languageFlag,
helpFlag,
};
static vector<Flag> logFlags = {
languageFlag,
helpFlag,
};
static const char * initInfo =
"Initialize a L10ns project. This command creates on 'l10ns.json' "
"file, with sane default options applied.";
static const char * updateInfo =
"Synchronize your keys between source code and storage.";
static const char * logInfo =
"Show latest localizations.";
static const char * setInfo =
"Set new localizations.";
static vector<Action> actions = {
Action(ActionKind::Init, "init", "Initialize project.", initInfo, &helpFlags),
Action(ActionKind::Update, "update", "Update localization keys.", updateInfo, &helpFlags),
Action(ActionKind::Log, "log", "Show latest added localizations.", logInfo, &logFlags),
Action(ActionKind::Set, "set", "Set localization.", setInfo, &setFlags),
};
struct Command {
bool isRequestingHelp;
bool isRequestingVersion;
ActionKind action;
vector<Flag> * flags;
Command()
: isRequestingHelp(false)
, isRequestingVersion(false)
, action(ActionKind::None)
, flags(&defaultFlags) {
}
};
void setCommandFlag(Command *command, const Flag *flag, char *value = NULL) {
switch (flag->kind) {
case FlagKind::Help:
command->isRequestingHelp = true;
return;
case FlagKind::Version:
command->isRequestingVersion = true;
return;
default:
return;
}
}
Command* parseCommandArguments(int argc, char* argv[]) {
Command * command = new Command();
// Flag to optimize has action parsing.
bool hasAction = false;
// The option flag that is pending for a value.
const Flag * flagWhichAwaitsValue = NULL;
for (int argIndex = 1; argIndex < argc; argIndex++) {
auto arg = argv[argIndex];
if (!hasAction) {
for (auto const& a : actions) {
if (strcmp(a.name->c_str(), arg) == 0) {
command->action = a.kind;
hasAction = true;
command->flags = a.flags;
break;
}
}
}
if (flagWhichAwaitsValue == NULL) {
for (auto const& flag : *command->flags) {
if (strcmp(flag.name->c_str(), arg) == 0 || (flag.alias->length() != 0 && strcmp(flag.name->c_str(), arg) == 0)) {
if (flag.hasValue) {
flagWhichAwaitsValue = &flag;
}
setCommandFlag(command, &flag);
break;
}
}
}
else {
setCommandFlag(command, flagWhichAwaitsValue, arg);
flagWhichAwaitsValue = NULL;
continue;
}
}
return command;
}
} // L10ns
<|endoftext|>
|
<commit_before>/**
** \file scheduler/scheduler.cc
** \brief Implementation of scheduler::Scheduler.
*/
//#define ENABLE_DEBUG_TRACES
#include <cassert>
#include <cstdlib>
#include <libport/compiler.hh>
#include <libport/containers.hh>
#include <libport/foreach.hh>
#include "kernel/userver.hh"
#include "object/urbi-exception.hh"
#include "scheduler/scheduler.hh"
#include "scheduler/job.hh"
namespace scheduler
{
// This function is required to start a new job using the libcoroutine.
// Its only purpose is to create the context and start the execution
// of the new job.
static void
run_job (void* job)
{
static_cast<Job*>(job)->run();
}
void
Scheduler::add_job (Job* job)
{
assert (job);
assert (!libport::has (jobs_, job));
assert (!libport::has (jobs_to_start_, job));
jobs_to_start_.push_back (job);
}
libport::utime_t
Scheduler::work ()
{
#ifdef ENABLE_DEBUG_TRACES
static int cycle = 0;
#endif
ECHO ("======================================================== cycle "
<< ++cycle);
// Start new jobs. You may note that to_kill_ is reset at the beginning
// of each loop and one final time at the end. This is to ensure that
// we are not trying to clear the job on which we are iterating (it
// may only be set to a reference onto the latest scheduled job).
to_start_.clear ();
std::swap (to_start_, jobs_to_start_);
foreach (Job* job, to_start_)
{
to_kill_ = 0;
assert (job);
ECHO ("will start job " << *job);
// Job will start for a very short time and do a yield_front() to
// be restarted below in the course of the regular cycle.
assert (!current_job_);
current_job_ = job;
Coro_startCoro_ (self_, job->coro_get(), job, run_job);
// We have to assume that a new job may have had side-effects.
possible_side_effect_ = true;
}
// Start deferred jobs
for (libport::utime_t current_time = ::urbiserver->getTime ();
!deferred_jobs_.empty();
deferred_jobs_.pop ())
{
deferred_job j = deferred_jobs_.top ();
if (current_time < j.get<0>())
break;
jobs_.push_back (j.get<1> ());
}
// If something is going to happen, or if we have just started a
// new job, add the list of jobs waiting for something to happen
// on the pending jobs queue.
if (!if_change_jobs_.empty() && (possible_side_effect_ || !jobs_.empty()))
{
foreach (Job* job, if_change_jobs_)
jobs_.push_back (job);
if_change_jobs_.clear ();
}
// Run all the jobs in the run queue once. If any job declares upon entry or
// return that it is not side-effect free, we remember that for the next
// cycle.
possible_side_effect_ = false;
pending_.clear ();
std::swap (pending_, jobs_);
ECHO (pending_.size() << " jobs in the queue for this cycle");
foreach (Job* job, pending_)
{
// Kill a job if needed. See explanation in job.hh.
to_kill_ = 0;
assert (job);
assert (!job->terminated ());
ECHO ("will resume job " << *job << (job->side_effect_free_get() ? " (side-effect free)" : ""));
possible_side_effect_ |= !job->side_effect_free_get ();
assert (!current_job_);
Coro_switchTo_ (self_, job->coro_get ());
assert (!current_job_);
possible_side_effect_ |= !job->side_effect_free_get ();
ECHO ("back from job " << *job << (job->side_effect_free_get() ? " (side-effect free)" : ""));
}
// Kill a job if needed. See explanation in job.hh.
to_kill_ = 0;
// Do we have some work to do now?
if (!jobs_.empty () || !jobs_to_start_.empty())
{
ECHO ("scheduler: asking to be recalled ASAP, " << jobs_.size() << " jobs ready and " << jobs_to_start_.size()
<< " to start");
return 0;
}
// Do we have deferred jobs?
if (!deferred_jobs_.empty ())
{
ECHO ("scheduler: asking to be recalled later");
return deferred_jobs_.top ().get<0> ();
}
// Ok, let's say, we'll be called again in one hour.
ECHO ("scheduler: asking to be recalled in a long time");
return ::urbiserver->getTime() + 3600000000LL;
}
void
Scheduler::switch_back (Job* job)
{
// Switch back to the scheduler.
assert (current_job_ == job);
current_job_ = 0;
Coro_switchTo_ (job->coro_get (), self_);
// We regained control, we are again in the context of the job.
assert (!current_job_);
current_job_ = job;
ECHO ("job " << *job << " resumed");
// Check that we are not near exhausting the stack space.
job->check_stack_space ();
// Execute a deferred exception if any
job->check_for_pending_exception ();
}
void
Scheduler::resume_scheduler (Job* job)
{
// If the job has not terminated, put it at the back of the run queue
// so that the run queue order is preserved between work cycles.
if (!job->terminated ())
jobs_.push_back (job);
ECHO (*job << " has " << (job->terminated () ? "" : "not ") << "terminated");
switch_back (job);
}
void
Scheduler::resume_scheduler_front (Job* job)
{
// Put the job in front of the queue. If the job asks to be requeued,
// it is not terminated.
assert (!job->terminated ());
jobs_.push_front (job);
switch_back (job);
}
void
Scheduler::resume_scheduler_until (Job* job, libport::utime_t deadline)
{
// Put the job in the deferred queue. If the job asks to be requeued,
// it is not terminated.
assert (!job->terminated ());
deferred_jobs_.push (boost::make_tuple (deadline, job));
switch_back (job);
}
void
Scheduler::resume_scheduler_suspend (Job* job)
{
suspended_jobs_.push_back (job);
switch_back (job);
}
void
Scheduler::resume_scheduler_things_changed (Job* job)
{
if_change_jobs_.push_back (job);
switch_back (job);
}
void
Scheduler::resume_job (Job* job)
{
// Suspended job may have been killed externally, in which case it
// will not appear in the list of suspended jobs.
if (libport::has (suspended_jobs_, job))
{
jobs_.push_back (job);
suspended_jobs_.remove (job);
}
}
void
Scheduler::killall_jobs ()
{
ECHO ("killing all jobs!");
// This implementation is quite inefficient because it will call
// kill_job() for each job. But who cares? We are killing everyone
// anyway.
while (!jobs_to_start_.empty ())
jobs_to_start_.pop_front ();
while (!suspended_jobs_.empty ())
kill_job (suspended_jobs_.front ());
while (!if_change_jobs_.empty ())
kill_job (if_change_jobs_.front ());
while (!jobs_.empty ())
kill_job (jobs_.front ());
while (!deferred_jobs_.empty ())
kill_job (deferred_jobs_.top ().get<1>());
}
void
Scheduler::unschedule_job (Job* job)
{
assert (job);
assert (job != current_job_);
ECHO ("unscheduling job " << *job);
// Remove the job from the queues where it could be stored.
jobs_to_start_.remove (job);
jobs_.remove (job);
suspended_jobs_.remove (job);
if_change_jobs_.remove (job);
// Remove it from live queues as well if the job is destroyed.
to_start_.remove (job);
pending_.remove (job);
// We have no remove() on a priority queue, regenerate a queue without
// this job.
{
deferred_jobs old_deferred;
std::swap (old_deferred, deferred_jobs_);
while (!old_deferred.empty ())
{
deferred_job j = old_deferred.top ();
old_deferred.pop ();
if (j.get<1>() != job)
deferred_jobs_.push (j);
}
}
}
void
Scheduler::kill_job (Job* job)
{
assert (job != current_job_);
ECHO ("deleting job " << *job);
delete job;
}
bool operator> (const deferred_job& left, const deferred_job& right)
{
return left.get<0>() > right.get<0>();
}
} // namespace scheduler
<commit_msg>Do not yield() on side-effect-free jobs<commit_after>/**
** \file scheduler/scheduler.cc
** \brief Implementation of scheduler::Scheduler.
*/
//#define ENABLE_DEBUG_TRACES
#include <cassert>
#include <cstdlib>
#include <libport/compiler.hh>
#include <libport/containers.hh>
#include <libport/foreach.hh>
#include "kernel/userver.hh"
#include "object/urbi-exception.hh"
#include "scheduler/scheduler.hh"
#include "scheduler/job.hh"
namespace scheduler
{
// This function is required to start a new job using the libcoroutine.
// Its only purpose is to create the context and start the execution
// of the new job.
static void
run_job (void* job)
{
static_cast<Job*>(job)->run();
}
void
Scheduler::add_job (Job* job)
{
assert (job);
assert (!libport::has (jobs_, job));
assert (!libport::has (jobs_to_start_, job));
jobs_to_start_.push_back (job);
}
libport::utime_t
Scheduler::work ()
{
#ifdef ENABLE_DEBUG_TRACES
static int cycle = 0;
#endif
ECHO ("======================================================== cycle "
<< ++cycle);
// Start new jobs. You may note that to_kill_ is reset at the beginning
// of each loop and one final time at the end. This is to ensure that
// we are not trying to clear the job on which we are iterating (it
// may only be set to a reference onto the latest scheduled job).
to_start_.clear ();
std::swap (to_start_, jobs_to_start_);
foreach (Job* job, to_start_)
{
to_kill_ = 0;
assert (job);
ECHO ("will start job " << *job);
// Job will start for a very short time and do a yield_front() to
// be restarted below in the course of the regular cycle.
assert (!current_job_);
current_job_ = job;
Coro_startCoro_ (self_, job->coro_get(), job, run_job);
// We have to assume that a new job may have had side-effects.
possible_side_effect_ = true;
}
// Start deferred jobs
for (libport::utime_t current_time = ::urbiserver->getTime ();
!deferred_jobs_.empty();
deferred_jobs_.pop ())
{
deferred_job j = deferred_jobs_.top ();
if (current_time < j.get<0>())
break;
jobs_.push_back (j.get<1> ());
}
// If something is going to happen, or if we have just started a
// new job, add the list of jobs waiting for something to happen
// on the pending jobs queue.
if (!if_change_jobs_.empty() && (possible_side_effect_ || !jobs_.empty()))
{
foreach (Job* job, if_change_jobs_)
jobs_.push_back (job);
if_change_jobs_.clear ();
}
// Run all the jobs in the run queue once. If any job declares upon entry or
// return that it is not side-effect free, we remember that for the next
// cycle.
possible_side_effect_ = false;
pending_.clear ();
std::swap (pending_, jobs_);
ECHO (pending_.size() << " jobs in the queue for this cycle");
foreach (Job* job, pending_)
{
// Kill a job if needed. See explanation in job.hh.
to_kill_ = 0;
assert (job);
assert (!job->terminated ());
ECHO ("will resume job " << *job << (job->side_effect_free_get() ? " (side-effect free)" : ""));
possible_side_effect_ |= !job->side_effect_free_get ();
assert (!current_job_);
Coro_switchTo_ (self_, job->coro_get ());
assert (!current_job_);
possible_side_effect_ |= !job->side_effect_free_get ();
ECHO ("back from job " << *job << (job->side_effect_free_get() ? " (side-effect free)" : ""));
}
// Kill a job if needed. See explanation in job.hh.
to_kill_ = 0;
// Do we have some work to do now?
if (!jobs_.empty () || !jobs_to_start_.empty())
{
ECHO ("scheduler: asking to be recalled ASAP, " << jobs_.size() << " jobs ready and " << jobs_to_start_.size()
<< " to start");
return 0;
}
// Do we have deferred jobs?
if (!deferred_jobs_.empty ())
{
ECHO ("scheduler: asking to be recalled later");
return deferred_jobs_.top ().get<0> ();
}
// Ok, let's say, we'll be called again in one hour.
ECHO ("scheduler: asking to be recalled in a long time");
return ::urbiserver->getTime() + 3600000000LL;
}
void
Scheduler::switch_back (Job* job)
{
// Switch back to the scheduler.
assert (current_job_ == job);
current_job_ = 0;
Coro_switchTo_ (job->coro_get (), self_);
// We regained control, we are again in the context of the job.
assert (!current_job_);
current_job_ = job;
ECHO ("job " << *job << " resumed");
// Check that we are not near exhausting the stack space.
job->check_stack_space ();
// Execute a deferred exception if any
job->check_for_pending_exception ();
}
void
Scheduler::resume_scheduler (Job* job)
{
// If the job has not terminated and is side-effect free, then we
// assume it will not take a long time as we are probably evaluating
// a condition. In order to reduce the number of cycles spent to evaluate
// the condition, continue until it asks to be suspended in another
// way or until it is no longer side-effect free.
if (!job->terminated () && job->side_effect_free_get ())
return;
// If the job has not terminated, put it at the back of the run queue
// so that the run queue order is preserved between work cycles.
if (!job->terminated ())
jobs_.push_back (job);
ECHO (*job << " has " << (job->terminated () ? "" : "not ") << "terminated");
switch_back (job);
}
void
Scheduler::resume_scheduler_front (Job* job)
{
// Put the job in front of the queue. If the job asks to be requeued,
// it is not terminated.
assert (!job->terminated ());
jobs_.push_front (job);
switch_back (job);
}
void
Scheduler::resume_scheduler_until (Job* job, libport::utime_t deadline)
{
// Put the job in the deferred queue. If the job asks to be requeued,
// it is not terminated.
assert (!job->terminated ());
deferred_jobs_.push (boost::make_tuple (deadline, job));
switch_back (job);
}
void
Scheduler::resume_scheduler_suspend (Job* job)
{
suspended_jobs_.push_back (job);
switch_back (job);
}
void
Scheduler::resume_scheduler_things_changed (Job* job)
{
if_change_jobs_.push_back (job);
switch_back (job);
}
void
Scheduler::resume_job (Job* job)
{
// Suspended job may have been killed externally, in which case it
// will not appear in the list of suspended jobs.
if (libport::has (suspended_jobs_, job))
{
jobs_.push_back (job);
suspended_jobs_.remove (job);
}
}
void
Scheduler::killall_jobs ()
{
ECHO ("killing all jobs!");
// This implementation is quite inefficient because it will call
// kill_job() for each job. But who cares? We are killing everyone
// anyway.
while (!jobs_to_start_.empty ())
jobs_to_start_.pop_front ();
while (!suspended_jobs_.empty ())
kill_job (suspended_jobs_.front ());
while (!if_change_jobs_.empty ())
kill_job (if_change_jobs_.front ());
while (!jobs_.empty ())
kill_job (jobs_.front ());
while (!deferred_jobs_.empty ())
kill_job (deferred_jobs_.top ().get<1>());
}
void
Scheduler::unschedule_job (Job* job)
{
assert (job);
assert (job != current_job_);
ECHO ("unscheduling job " << *job);
// Remove the job from the queues where it could be stored.
jobs_to_start_.remove (job);
jobs_.remove (job);
suspended_jobs_.remove (job);
if_change_jobs_.remove (job);
// Remove it from live queues as well if the job is destroyed.
to_start_.remove (job);
pending_.remove (job);
// We have no remove() on a priority queue, regenerate a queue without
// this job.
{
deferred_jobs old_deferred;
std::swap (old_deferred, deferred_jobs_);
while (!old_deferred.empty ())
{
deferred_job j = old_deferred.top ();
old_deferred.pop ();
if (j.get<1>() != job)
deferred_jobs_.push (j);
}
}
}
void
Scheduler::kill_job (Job* job)
{
assert (job != current_job_);
ECHO ("deleting job " << *job);
delete job;
}
bool operator> (const deferred_job& left, const deferred_job& right)
{
return left.get<0>() > right.get<0>();
}
} // namespace scheduler
<|endoftext|>
|
<commit_before>/*
===========================================================================
Daemon GPL Source Code
Copyright (C) 2012 Unvanquished Developers
This file is part of the Daemon GPL Source Code (Daemon Source Code).
Daemon Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Daemon Source Code 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 Daemon Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Daemon Source Code is also subject to certain additional terms.
You should have received a copy of these additional terms immediately following the
terms and conditions of the GNU General Public License which accompanied the Daemon
Source Code. If not, please request a copy in writing from id Software at the address
below.
If you have questions concerning this license or the applicable additional terms, you
may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville,
Maryland 20850 USA.
===========================================================================
*/
extern "C"
{
#include "q_shared.h"
#include "qcommon.h"
#include "../../libs/findlocale/findlocale.h"
}
#include "../../libs/tinygettext/tinygettext.hpp"
#include <sstream>
using namespace tinygettext;
DictionaryManager trans_manager;
DictionaryManager trans_managergame;
Dictionary trans_dict;
Dictionary trans_dictgame;
cvar_t *language;
bool enabled = false;
#define _(x) Trans_Gettext(x)
extern "C" void Trans_Init( void )
{
char **poFiles;
int numPoFiles, i;
FL_Locale *locale;
language = Cvar_Get( "language", "", CVAR_ARCHIVE );
FL_FindLocale( &locale, FL_MESSAGES );
// Invalid or not found. Just use builtin language.
if( !locale->lang || !locale->lang[0] || !locale->country || !locale->country[0] )
{
Cvar_Set( "language", "en_US" );
}
poFiles = FS_ListFiles( "translation/client", ".po", &numPoFiles );
// This assumes that the names in both folders are the same
for( i = 0; i < numPoFiles; i++ )
{
int ret;
Dictionary *dict1;
Dictionary *dict2;
char *buffer, language[ 6 ];
if( FS_ReadFile( va( "translation/client/%s", poFiles[ i ] ), ( void ** ) &buffer ) > 0 )
{
dict1 = new Dictionary();
COM_StripExtension2( poFiles[ i ], language, sizeof( language ) );
std::stringstream ss( buffer );
trans_manager.add_po( poFiles[ i ], ss, Language::from_env( std::string( language ) ) );
FS_FreeFile( buffer );
}
else
{
Com_Printf( "^1ERROR: Could not open client translation: %s\n", poFiles[ i ] );
}
if( FS_ReadFile( va( "translation/game/%s", poFiles[ i ] ), ( void ** ) &buffer ) > 0 )
{
dict2 = new Dictionary();
COM_StripExtension2( poFiles[ i ], language, sizeof( language ) );
std::stringstream ss( buffer );
trans_managergame.add_po( poFiles[ i ], ss, Language::from_env( std::string( language ) ) );
FS_FreeFile( buffer );
}
else
{
Com_Printf( "^1ERROR: Could not open game translation: %s\n", poFiles[ i ] );
}
}
FS_FreeFileList( poFiles );
trans_dict = trans_manager.get_dictionary( Language::from_env( std::string( language->string ) ) );
trans_dictgame = trans_managergame.get_dictionary( Language::from_env( std::string( language->string ) ) );
enabled = true;
Com_Printf( "Loaded %lu language(s)\n", trans_manager.get_languages().size() );
}
extern "C" const char* Trans_Gettext( const char *msgid )
{
if( !enabled ) { return msgid; }
return trans_dict.translate( std::string( msgid ) ).c_str();
}
extern "C" const char* Trans_GettextGame( const char *msgid )
{
if( !enabled ) { return msgid; }
return trans_dictgame.translate( std::string( msgid ) ).c_str();
}
extern "C" const char* Trans_GettextPlural( const char *msgid, const char *msgid_plural, int num )
{
if( !enabled ) { return num == 1 ? msgid : msgid_plural; }
return trans_dict.translate_plural( std::string( msgid ), std::string( msgid_plural ), num ).c_str();
}
extern "C" const char* Trans_GettextGamePlural( const char *msgid, const char *msgid_plural, int num )
{
if( !enabled ) { return num == 1 ? msgid : msgid_plural; }
return trans_dictgame.translate_plural( std::string( msgid ), std::string( msgid_plural ), num ).c_str();
}
<commit_msg>Force language changing through a menu<commit_after>/*
===========================================================================
Daemon GPL Source Code
Copyright (C) 2012 Unvanquished Developers
This file is part of the Daemon GPL Source Code (Daemon Source Code).
Daemon Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Daemon Source Code 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 Daemon Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Daemon Source Code is also subject to certain additional terms.
You should have received a copy of these additional terms immediately following the
terms and conditions of the GNU General Public License which accompanied the Daemon
Source Code. If not, please request a copy in writing from id Software at the address
below.
If you have questions concerning this license or the applicable additional terms, you
may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville,
Maryland 20850 USA.
===========================================================================
*/
extern "C"
{
#include "q_shared.h"
#include "qcommon.h"
#include "../../libs/findlocale/findlocale.h"
}
#include "../../libs/tinygettext/tinygettext.hpp"
#include <sstream>
using namespace tinygettext;
DictionaryManager trans_manager;
DictionaryManager trans_managergame;
Dictionary trans_dict;
Dictionary trans_dictgame;
cvar_t *language;
bool enabled = false;
int modificationCount=0;
#define _(x) Trans_Gettext(x)
extern "C" void Trans_UpdateLanguage_f( void )
{
trans_dict = trans_manager.get_dictionary( Language::from_env( std::string( language->string ) ) );
trans_dictgame = trans_managergame.get_dictionary( Language::from_env( std::string( language->string ) ) );
Com_Printf( "Switched language to %s\n", Language::from_env( std::string( language->string ) ).get_name().c_str() );
}
extern "C" void Trans_Init( void )
{
char **poFiles, langList[ MAX_TOKEN_CHARS ], encList[ MAX_TOKEN_CHARS ];
int numPoFiles, i;
FL_Locale *locale;
std::set<Language> lang;
language = Cvar_Get( "language", "", CVAR_ROM );
FL_FindLocale( &locale, FL_MESSAGES );
// Invalid or not found. Just use builtin language.
if( !locale->lang || !locale->lang[0] || !locale->country || !locale->country[0] )
{
Cvar_Set( "language", "en_US" );
}
else
{
Cvar_Set( "language", va( "%s_%s", locale->lang, locale->country ) );
}
poFiles = FS_ListFiles( "translation/client", ".po", &numPoFiles );
// This assumes that the names in both folders are the same
for( i = 0; i < numPoFiles; i++ )
{
int ret;
Dictionary *dict1;
Dictionary *dict2;
char *buffer, language[ 6 ];
if( FS_ReadFile( va( "translation/client/%s", poFiles[ i ] ), ( void ** ) &buffer ) > 0 )
{
dict1 = new Dictionary();
COM_StripExtension2( poFiles[ i ], language, sizeof( language ) );
std::stringstream ss( buffer );
trans_manager.add_po( poFiles[ i ], ss, Language::from_env( std::string( language ) ) );
FS_FreeFile( buffer );
}
else
{
Com_Printf( "^1ERROR: Could not open client translation: %s\n", poFiles[ i ] );
}
if( FS_ReadFile( va( "translation/game/%s", poFiles[ i ] ), ( void ** ) &buffer ) > 0 )
{
dict2 = new Dictionary();
COM_StripExtension2( poFiles[ i ], language, sizeof( language ) );
std::stringstream ss( buffer );
trans_managergame.add_po( poFiles[ i ], ss, Language::from_env( std::string( language ) ) );
FS_FreeFile( buffer );
}
else
{
Com_Printf( "^1ERROR: Could not open game translation: %s\n", poFiles[ i ] );
}
}
FS_FreeFileList( poFiles );
trans_dict = trans_manager.get_dictionary( Language::from_env( std::string( language->string ) ) );
trans_dictgame = trans_managergame.get_dictionary( Language::from_env( std::string( language->string ) ) );
lang = trans_manager.get_languages();
for( std::set<Language>::iterator p = lang.begin(); p != lang.end(); p++ )
{
Q_strcat( langList, sizeof( langList ), va( "\"%s\" ", p->get_name().c_str() ) );
Q_strcat( encList, sizeof( encList ), va( "\"%s_%s\" ", p->get_language().c_str(), p->get_country().c_str() ) );
}
Cvar_Set( "trans_languages", langList );
Cvar_Set( "trans_encodings", encList );
Com_Printf( "Loaded %lu language(s)\n", lang.size() );
Cmd_AddCommand( "updatelanguage", Trans_UpdateLanguage_f );
enabled = true;
}
extern "C" const char* Trans_Gettext( const char *msgid )
{
if( !enabled ) { return msgid; }
return trans_dict.translate( std::string( msgid ) ).c_str();
}
extern "C" const char* Trans_GettextGame( const char *msgid )
{
if( !enabled ) { return msgid; }
return trans_dictgame.translate( std::string( msgid ) ).c_str();
}
extern "C" const char* Trans_GettextPlural( const char *msgid, const char *msgid_plural, int num )
{
if( !enabled ) { return num == 1 ? msgid : msgid_plural; }
return trans_dict.translate_plural( std::string( msgid ), std::string( msgid_plural ), num ).c_str();
}
extern "C" const char* Trans_GettextGamePlural( const char *msgid, const char *msgid_plural, int num )
{
if( !enabled ) { return num == 1 ? msgid : msgid_plural; }
return trans_dictgame.translate_plural( std::string( msgid ), std::string( msgid_plural ), num ).c_str();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012, Noriyuki OHKAWA a.k.a. notogawa.
// 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 Noriyuki OHKAWA and notogawa nor the names of other
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "scoped_global_lock.hpp"
namespace ift {
scoped_global_lock::scoped_global_lock()
{
while (!__sync_bool_compare_and_swap (&mutex, recurse, recurse+1));
++recurse;
}
scoped_global_lock::~scoped_global_lock() throw ()
{
--recurse;
__sync_bool_compare_and_swap (&mutex, recurse+1, recurse);
}
bool scoped_global_lock::locked()
{
return 0 < mutex && recurse == mutex;
}
int scoped_global_lock::mutex = 0;
__thread int scoped_global_lock::recurse = 0;
}
<commit_msg>suggested to add explicit braces around empty body in 'while' statement.<commit_after>// Copyright (c) 2012, Noriyuki OHKAWA a.k.a. notogawa.
// 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 Noriyuki OHKAWA and notogawa nor the names of other
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "scoped_global_lock.hpp"
namespace ift {
scoped_global_lock::scoped_global_lock()
{
while (!__sync_bool_compare_and_swap (&mutex, recurse, recurse+1)) {}
++recurse;
}
scoped_global_lock::~scoped_global_lock() throw ()
{
--recurse;
__sync_bool_compare_and_swap (&mutex, recurse+1, recurse);
}
bool scoped_global_lock::locked()
{
return 0 < mutex && recurse == mutex;
}
int scoped_global_lock::mutex = 0;
__thread int scoped_global_lock::recurse = 0;
}
<|endoftext|>
|
<commit_before>#include "Genes/Look_Ahead_Gene.h"
#include <cmath>
#include <algorithm>
#include "Utility.h"
#include "Game/Board.h"
#include "Game/Clock.h"
Look_Ahead_Gene::Look_Ahead_Gene() :
Gene(0.0),
mean_game_length(100),
positions_per_second(0)
{
}
void Look_Ahead_Gene::reset_properties() const
{
properties["Mean Game Length"] = mean_game_length;
properties["Positions Per Second"] = positions_per_second;
}
void Look_Ahead_Gene::load_properties()
{
mean_game_length = properties["Mean Game Length"];
positions_per_second = properties["Positions Per Second"];
}
Look_Ahead_Gene::~Look_Ahead_Gene()
{
}
double Look_Ahead_Gene::positions_to_examine(const Board& board, const Clock& clock) const
{
auto time_left = clock.time_left(board.whose_turn());
auto moves_so_far = board.get_game_record().size()/2; // only count moves by this player
auto moves_left = Math::average_moves_left(mean_game_length, moves_so_far);
auto time_per_move = time_left/moves_left;
return positions_per_second*time_per_move; // positions to examine for one move
}
void Look_Ahead_Gene::mutate()
{
mean_game_length = std::max(1.0, mean_game_length + Random::random_normal(1.0));
positions_per_second = std::max(0.0, positions_per_second + Random::random_normal(10.0));
}
Look_Ahead_Gene* Look_Ahead_Gene::duplicate() const
{
return new Look_Ahead_Gene(*this);
}
std::string Look_Ahead_Gene::name() const
{
return "Look Ahead Gene";
}
double Look_Ahead_Gene::score_board(const Board&, Color) const
{
return 0.0;
}
<commit_msg>Lower initial estimate of mean game length<commit_after>#include "Genes/Look_Ahead_Gene.h"
#include <cmath>
#include <algorithm>
#include "Utility.h"
#include "Game/Board.h"
#include "Game/Clock.h"
Look_Ahead_Gene::Look_Ahead_Gene() :
Gene(0.0),
mean_game_length(50),
positions_per_second(0)
{
}
void Look_Ahead_Gene::reset_properties() const
{
properties["Mean Game Length"] = mean_game_length;
properties["Positions Per Second"] = positions_per_second;
}
void Look_Ahead_Gene::load_properties()
{
mean_game_length = properties["Mean Game Length"];
positions_per_second = properties["Positions Per Second"];
}
Look_Ahead_Gene::~Look_Ahead_Gene()
{
}
double Look_Ahead_Gene::positions_to_examine(const Board& board, const Clock& clock) const
{
auto time_left = clock.time_left(board.whose_turn());
auto moves_so_far = board.get_game_record().size()/2; // only count moves by this player
auto moves_left = Math::average_moves_left(mean_game_length, moves_so_far);
auto time_per_move = time_left/moves_left;
return positions_per_second*time_per_move; // positions to examine for one move
}
void Look_Ahead_Gene::mutate()
{
mean_game_length = std::max(1.0, mean_game_length + Random::random_normal(1.0));
positions_per_second = std::max(0.0, positions_per_second + Random::random_normal(10.0));
}
Look_Ahead_Gene* Look_Ahead_Gene::duplicate() const
{
return new Look_Ahead_Gene(*this);
}
std::string Look_Ahead_Gene::name() const
{
return "Look Ahead Gene";
}
double Look_Ahead_Gene::score_board(const Board&, Color) const
{
return 0.0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012, Cornell University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of HyperDex 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.
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
// Google Log
#include <glog/logging.h>
// HyperDex
#include "daemon/communication.h"
#include "daemon/daemon.h"
using hyperdex::communication;
using hyperdex::reconfigure_returncode;
//////////////////////////////// Early Messages ////////////////////////////////
class communication::early_message
{
public:
early_message();
early_message(uint64_t version, uint64_t id,
std::auto_ptr<e::buffer> m);
~early_message() throw ();
public:
uint64_t config_version;
uint64_t id;
std::auto_ptr<e::buffer> msg;
};
communication :: early_message :: early_message()
: config_version(0)
, id()
, msg()
{
}
communication :: early_message :: early_message(uint64_t v,
uint64_t i,
std::auto_ptr<e::buffer> m)
: config_version(v)
, id(i)
, msg(m)
{
}
communication :: early_message :: ~early_message() throw ()
{
}
///////////////////////////////// Public Class /////////////////////////////////
communication :: communication(daemon* d)
: m_daemon(d)
, m_busybee_mapper(&m_daemon->m_config)
, m_busybee()
, m_early_messages()
{
}
communication :: ~communication() throw ()
{
}
bool
communication :: setup(const po6::net::location& bind_to,
unsigned threads)
{
m_busybee.reset(new busybee_mta(&m_busybee_mapper, bind_to, m_daemon->m_us.get(), threads));
return true;
}
void
communication :: teardown()
{
}
reconfigure_returncode
communication :: prepare(const configuration&,
const configuration&,
const server_id&)
{
// XXX
return RECONFIGURE_SUCCESS;
}
reconfigure_returncode
communication :: reconfigure(const configuration&,
const configuration&,
const server_id&)
{
// XXX
return RECONFIGURE_SUCCESS;
}
reconfigure_returncode
communication :: cleanup(const configuration&,
const configuration&,
const server_id&)
{
// XXX
return RECONFIGURE_SUCCESS;
}
bool
communication :: send(const virtual_server_id& from,
const server_id& to,
network_msgtype msg_type,
std::auto_ptr<e::buffer> msg)
{
assert(msg->size() >= HYPERDEX_HEADER_SIZE_VS);
#ifdef HD_LOG_ALL_MESSAGES
LOG(INFO) << "SEND " << from << "->" << to << " " << msg_type << " " << msg->hex();
#endif
if (m_daemon->m_us != m_daemon->m_config.get_server_id(from))
{
return false;
}
uint8_t mt = static_cast<uint8_t>(msg_type);
msg->pack_at(BUSYBEE_HEADER_SIZE) << mt << from.get();
if (to == m_daemon->m_us)
{
m_busybee->deliver(to.get(), msg);
}
else
{
busybee_returncode rc = m_busybee->send(to.get(), msg);
switch (rc)
{
case BUSYBEE_SUCCESS:
break;
case BUSYBEE_DISRUPTED:
handle_disruption(to.get());
return false;
case BUSYBEE_SHUTDOWN:
case BUSYBEE_POLLFAILED:
case BUSYBEE_ADDFDFAIL:
case BUSYBEE_TIMEOUT:
case BUSYBEE_EXTERNAL:
default:
LOG(ERROR) << "BusyBee unexpectedly returned " << rc;
return false;
}
}
return true;
}
bool
communication :: send(const virtual_server_id& from,
const virtual_server_id& vto,
network_msgtype msg_type,
std::auto_ptr<e::buffer> msg)
{
assert(msg->size() >= HYPERDEX_HEADER_SIZE_VV);
#ifdef HD_LOG_ALL_MESSAGES
LOG(INFO) << "SEND " << from << "->" << vto << " " << msg_type << " " << msg->hex();
#endif
if (m_daemon->m_us != m_daemon->m_config.get_server_id(from))
{
return false;
}
uint8_t mt = static_cast<uint8_t>(msg_type);
uint8_t flags = 1;
msg->pack_at(BUSYBEE_HEADER_SIZE) << mt << flags << m_daemon->m_config.version() << vto.get() << from.get();
server_id to = m_daemon->m_config.get_server_id(vto);
if (to == server_id())
{
return false;
}
if (to == m_daemon->m_us)
{
m_busybee->deliver(to.get(), msg);
}
else
{
busybee_returncode rc = m_busybee->send(to.get(), msg);
switch (rc)
{
case BUSYBEE_SUCCESS:
break;
case BUSYBEE_DISRUPTED:
handle_disruption(to.get());
return false;
case BUSYBEE_SHUTDOWN:
case BUSYBEE_POLLFAILED:
case BUSYBEE_ADDFDFAIL:
case BUSYBEE_TIMEOUT:
case BUSYBEE_EXTERNAL:
default:
LOG(ERROR) << "BusyBee unexpectedly returned " << rc;
return false;
}
}
return true;
}
bool
communication :: send(const virtual_server_id& vto,
network_msgtype msg_type,
std::auto_ptr<e::buffer> msg)
{
assert(msg->size() >= HYPERDEX_HEADER_SIZE_SV);
#ifdef HD_LOG_ALL_MESSAGES
LOG(INFO) << "SEND ->" << vto << " " << msg_type << " " << msg->hex();
#endif
uint8_t mt = static_cast<uint8_t>(msg_type);
uint8_t flags = 0;
msg->pack_at(BUSYBEE_HEADER_SIZE) << mt << flags << m_daemon->m_config.version() << vto.get();
server_id to = m_daemon->m_config.get_server_id(vto);
if (to == server_id())
{
return false;
}
if (to == m_daemon->m_us)
{
m_busybee->deliver(to.get(), msg);
}
else
{
busybee_returncode rc = m_busybee->send(to.get(), msg);
switch (rc)
{
case BUSYBEE_SUCCESS:
break;
case BUSYBEE_DISRUPTED:
handle_disruption(to.get());
return false;
case BUSYBEE_SHUTDOWN:
case BUSYBEE_POLLFAILED:
case BUSYBEE_ADDFDFAIL:
case BUSYBEE_TIMEOUT:
case BUSYBEE_EXTERNAL:
default:
LOG(ERROR) << "BusyBee unexpectedly returned " << rc;
return false;
}
}
return true;
}
bool
communication :: recv(server_id* from,
virtual_server_id* vfrom,
virtual_server_id* vto,
network_msgtype* msg_type,
std::auto_ptr<e::buffer>* msg,
e::unpacker* up)
{
// Read messages from the network until we get one that meets the following
// constraints:
// - It is addressed to a virtual_server_id
// - The virtual_server_id destination maps to us
// - If it comes from a virtual_server_id, that id maps to the sender
// - The message version is less than or equal to our current config
while (true)
{
uint64_t id;
busybee_returncode rc = m_busybee->recv(&id, msg);
switch (rc)
{
case BUSYBEE_SUCCESS:
break;
case BUSYBEE_SHUTDOWN:
return false;
case BUSYBEE_DISRUPTED:
handle_disruption(id);
continue;
case BUSYBEE_POLLFAILED:
case BUSYBEE_ADDFDFAIL:
case BUSYBEE_TIMEOUT:
case BUSYBEE_EXTERNAL:
default:
LOG(ERROR) << "busybee unexpectedly returned " << rc;
continue;
}
uint8_t mt;
uint8_t flags;
uint64_t version;
uint64_t vidf;
uint64_t vidt;
*up = (*msg)->unpack_from(BUSYBEE_HEADER_SIZE);
*up = *up >> mt >> flags >> version >> vidt;
*msg_type = static_cast<network_msgtype>(mt);
*from = server_id(id);
*vto = virtual_server_id(vidt);
if ((flags & 0x1))
{
*up = *up >> vidf;
*vfrom = virtual_server_id(vidf);
}
else
{
*vfrom = virtual_server_id();
}
if (up->error())
{
LOG(WARNING) << "dropping message that has a malformed header; here's some hex: " << (*msg)->hex();
continue;
}
bool from_valid = true;
bool to_valid = m_daemon->m_us == m_daemon->m_config.get_server_id(virtual_server_id(vidt));
// If this is a virtual-virtual message
if ((flags & 0x1))
{
from_valid = *from == m_daemon->m_config.get_server_id(virtual_server_id(vidf));
}
if (from_valid && to_valid)
{
#ifdef HD_LOG_ALL_MESSAGES
LOG(INFO) << "RECV " << *from << "->" << *vto << " " << *msg_type << " " << (*msg)->hex();
#endif
return true;
}
// Shove the message back at the client so it fails with a reconfigure.
if (!(flags & 0x1))
{
mt = static_cast<uint8_t>(CONFIGMISMATCH);
(*msg)->pack_at(BUSYBEE_HEADER_SIZE) << mt;
m_busybee->send(id, *msg);
}
else if (version > m_daemon->m_config.version())
{
early_message em(version, id, *msg);
m_early_messages.push(em);
continue;
}
}
}
void
communication :: handle_disruption(uint64_t)
{
// XXX
}
<commit_msg>Log messages after filling in the header<commit_after>// Copyright (c) 2012, Cornell University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of HyperDex 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.
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
// Google Log
#include <glog/logging.h>
// HyperDex
#include "daemon/communication.h"
#include "daemon/daemon.h"
using hyperdex::communication;
using hyperdex::reconfigure_returncode;
//////////////////////////////// Early Messages ////////////////////////////////
class communication::early_message
{
public:
early_message();
early_message(uint64_t version, uint64_t id,
std::auto_ptr<e::buffer> m);
~early_message() throw ();
public:
uint64_t config_version;
uint64_t id;
std::auto_ptr<e::buffer> msg;
};
communication :: early_message :: early_message()
: config_version(0)
, id()
, msg()
{
}
communication :: early_message :: early_message(uint64_t v,
uint64_t i,
std::auto_ptr<e::buffer> m)
: config_version(v)
, id(i)
, msg(m)
{
}
communication :: early_message :: ~early_message() throw ()
{
}
///////////////////////////////// Public Class /////////////////////////////////
communication :: communication(daemon* d)
: m_daemon(d)
, m_busybee_mapper(&m_daemon->m_config)
, m_busybee()
, m_early_messages()
{
}
communication :: ~communication() throw ()
{
}
bool
communication :: setup(const po6::net::location& bind_to,
unsigned threads)
{
m_busybee.reset(new busybee_mta(&m_busybee_mapper, bind_to, m_daemon->m_us.get(), threads));
return true;
}
void
communication :: teardown()
{
}
reconfigure_returncode
communication :: prepare(const configuration&,
const configuration&,
const server_id&)
{
// XXX
return RECONFIGURE_SUCCESS;
}
reconfigure_returncode
communication :: reconfigure(const configuration&,
const configuration&,
const server_id&)
{
// XXX
return RECONFIGURE_SUCCESS;
}
reconfigure_returncode
communication :: cleanup(const configuration&,
const configuration&,
const server_id&)
{
// XXX
return RECONFIGURE_SUCCESS;
}
bool
communication :: send(const virtual_server_id& from,
const server_id& to,
network_msgtype msg_type,
std::auto_ptr<e::buffer> msg)
{
assert(msg->size() >= HYPERDEX_HEADER_SIZE_VS);
if (m_daemon->m_us != m_daemon->m_config.get_server_id(from))
{
return false;
}
uint8_t mt = static_cast<uint8_t>(msg_type);
msg->pack_at(BUSYBEE_HEADER_SIZE) << mt << from.get();
#ifdef HD_LOG_ALL_MESSAGES
LOG(INFO) << "SEND " << from << "->" << to << " " << msg_type << " " << msg->hex();
#endif
if (to == m_daemon->m_us)
{
m_busybee->deliver(to.get(), msg);
}
else
{
busybee_returncode rc = m_busybee->send(to.get(), msg);
switch (rc)
{
case BUSYBEE_SUCCESS:
break;
case BUSYBEE_DISRUPTED:
handle_disruption(to.get());
return false;
case BUSYBEE_SHUTDOWN:
case BUSYBEE_POLLFAILED:
case BUSYBEE_ADDFDFAIL:
case BUSYBEE_TIMEOUT:
case BUSYBEE_EXTERNAL:
default:
LOG(ERROR) << "BusyBee unexpectedly returned " << rc;
return false;
}
}
return true;
}
bool
communication :: send(const virtual_server_id& from,
const virtual_server_id& vto,
network_msgtype msg_type,
std::auto_ptr<e::buffer> msg)
{
assert(msg->size() >= HYPERDEX_HEADER_SIZE_VV);
if (m_daemon->m_us != m_daemon->m_config.get_server_id(from))
{
return false;
}
uint8_t mt = static_cast<uint8_t>(msg_type);
uint8_t flags = 1;
msg->pack_at(BUSYBEE_HEADER_SIZE) << mt << flags << m_daemon->m_config.version() << vto.get() << from.get();
server_id to = m_daemon->m_config.get_server_id(vto);
if (to == server_id())
{
return false;
}
#ifdef HD_LOG_ALL_MESSAGES
LOG(INFO) << "SEND " << from << "->" << vto << " " << msg_type << " " << msg->hex();
#endif
if (to == m_daemon->m_us)
{
m_busybee->deliver(to.get(), msg);
}
else
{
busybee_returncode rc = m_busybee->send(to.get(), msg);
switch (rc)
{
case BUSYBEE_SUCCESS:
break;
case BUSYBEE_DISRUPTED:
handle_disruption(to.get());
return false;
case BUSYBEE_SHUTDOWN:
case BUSYBEE_POLLFAILED:
case BUSYBEE_ADDFDFAIL:
case BUSYBEE_TIMEOUT:
case BUSYBEE_EXTERNAL:
default:
LOG(ERROR) << "BusyBee unexpectedly returned " << rc;
return false;
}
}
return true;
}
bool
communication :: send(const virtual_server_id& vto,
network_msgtype msg_type,
std::auto_ptr<e::buffer> msg)
{
assert(msg->size() >= HYPERDEX_HEADER_SIZE_SV);
uint8_t mt = static_cast<uint8_t>(msg_type);
uint8_t flags = 0;
msg->pack_at(BUSYBEE_HEADER_SIZE) << mt << flags << m_daemon->m_config.version() << vto.get();
server_id to = m_daemon->m_config.get_server_id(vto);
if (to == server_id())
{
return false;
}
#ifdef HD_LOG_ALL_MESSAGES
LOG(INFO) << "SEND ->" << vto << " " << msg_type << " " << msg->hex();
#endif
if (to == m_daemon->m_us)
{
m_busybee->deliver(to.get(), msg);
}
else
{
busybee_returncode rc = m_busybee->send(to.get(), msg);
switch (rc)
{
case BUSYBEE_SUCCESS:
break;
case BUSYBEE_DISRUPTED:
handle_disruption(to.get());
return false;
case BUSYBEE_SHUTDOWN:
case BUSYBEE_POLLFAILED:
case BUSYBEE_ADDFDFAIL:
case BUSYBEE_TIMEOUT:
case BUSYBEE_EXTERNAL:
default:
LOG(ERROR) << "BusyBee unexpectedly returned " << rc;
return false;
}
}
return true;
}
bool
communication :: recv(server_id* from,
virtual_server_id* vfrom,
virtual_server_id* vto,
network_msgtype* msg_type,
std::auto_ptr<e::buffer>* msg,
e::unpacker* up)
{
// Read messages from the network until we get one that meets the following
// constraints:
// - It is addressed to a virtual_server_id
// - The virtual_server_id destination maps to us
// - If it comes from a virtual_server_id, that id maps to the sender
// - The message version is less than or equal to our current config
while (true)
{
uint64_t id;
busybee_returncode rc = m_busybee->recv(&id, msg);
switch (rc)
{
case BUSYBEE_SUCCESS:
break;
case BUSYBEE_SHUTDOWN:
return false;
case BUSYBEE_DISRUPTED:
handle_disruption(id);
continue;
case BUSYBEE_POLLFAILED:
case BUSYBEE_ADDFDFAIL:
case BUSYBEE_TIMEOUT:
case BUSYBEE_EXTERNAL:
default:
LOG(ERROR) << "busybee unexpectedly returned " << rc;
continue;
}
uint8_t mt;
uint8_t flags;
uint64_t version;
uint64_t vidf;
uint64_t vidt;
*up = (*msg)->unpack_from(BUSYBEE_HEADER_SIZE);
*up = *up >> mt >> flags >> version >> vidt;
*msg_type = static_cast<network_msgtype>(mt);
*from = server_id(id);
*vto = virtual_server_id(vidt);
if ((flags & 0x1))
{
*up = *up >> vidf;
*vfrom = virtual_server_id(vidf);
}
else
{
*vfrom = virtual_server_id();
}
if (up->error())
{
LOG(WARNING) << "dropping message that has a malformed header; here's some hex: " << (*msg)->hex();
continue;
}
bool from_valid = true;
bool to_valid = m_daemon->m_us == m_daemon->m_config.get_server_id(virtual_server_id(vidt));
// If this is a virtual-virtual message
if ((flags & 0x1))
{
from_valid = *from == m_daemon->m_config.get_server_id(virtual_server_id(vidf));
}
if (from_valid && to_valid)
{
#ifdef HD_LOG_ALL_MESSAGES
LOG(INFO) << "RECV " << *from << "->" << *vto << " " << *msg_type << " " << (*msg)->hex();
#endif
return true;
}
// Shove the message back at the client so it fails with a reconfigure.
if (!(flags & 0x1))
{
mt = static_cast<uint8_t>(CONFIGMISMATCH);
(*msg)->pack_at(BUSYBEE_HEADER_SIZE) << mt;
m_busybee->send(id, *msg);
}
else if (version > m_daemon->m_config.version())
{
early_message em(version, id, *msg);
m_early_messages.push(em);
continue;
}
}
}
void
communication :: handle_disruption(uint64_t)
{
// XXX
}
<|endoftext|>
|
<commit_before>#include "extractor/graph_compressor.hpp"
#include "extractor/compressed_edge_container.hpp"
#include "extractor/restriction_map.hpp"
#include "util/dynamic_graph.hpp"
#include "util/node_based_graph.hpp"
#include "util/percent.hpp"
#include "util/simple_logger.hpp"
namespace osrm
{
namespace extractor
{
GraphCompressor::GraphCompressor(SpeedProfileProperties speed_profile)
: speed_profile(std::move(speed_profile))
{
}
void GraphCompressor::Compress(const std::unordered_set<NodeID> &barrier_nodes,
const std::unordered_set<NodeID> &traffic_lights,
RestrictionMap &restriction_map,
util::NodeBasedDynamicGraph &graph,
CompressedEdgeContainer &geometry_compressor)
{
const unsigned original_number_of_nodes = graph.GetNumberOfNodes();
const unsigned original_number_of_edges = graph.GetNumberOfEdges();
util::Percent progress(original_number_of_nodes);
for (const NodeID node_v : util::irange(0u, original_number_of_nodes))
{
progress.printStatus(node_v);
// only contract degree 2 vertices
if (2 != graph.GetOutDegree(node_v))
{
continue;
}
// don't contract barrier node
if (barrier_nodes.end() != barrier_nodes.find(node_v))
{
continue;
}
// check if v is a via node for a turn restriction, i.e. a 'directed' barrier node
if (restriction_map.IsViaNode(node_v))
{
continue;
}
// reverse_e2 forward_e2
// u <---------- v -----------> w
// ----------> <-----------
// forward_e1 reverse_e1
//
// Will be compressed to:
//
// reverse_e1
// u <---------- w
// ---------->
// forward_e1
//
// If the edges are compatible.
const bool reverse_edge_order = graph.GetEdgeData(graph.BeginEdges(node_v)).reversed;
const EdgeID forward_e2 = graph.BeginEdges(node_v) + reverse_edge_order;
BOOST_ASSERT(SPECIAL_EDGEID != forward_e2);
BOOST_ASSERT(forward_e2 >= graph.BeginEdges(node_v) && forward_e2 < graph.EndEdges(node_v));
const EdgeID reverse_e2 = graph.BeginEdges(node_v) + 1 - reverse_edge_order;
BOOST_ASSERT(SPECIAL_EDGEID != reverse_e2);
BOOST_ASSERT(reverse_e2 >= graph.BeginEdges(node_v) && reverse_e2 < graph.EndEdges(node_v));
const EdgeData &fwd_edge_data2 = graph.GetEdgeData(forward_e2);
const EdgeData &rev_edge_data2 = graph.GetEdgeData(reverse_e2);
const NodeID node_w = graph.GetTarget(forward_e2);
BOOST_ASSERT(SPECIAL_NODEID != node_w);
BOOST_ASSERT(node_v != node_w);
const NodeID node_u = graph.GetTarget(reverse_e2);
BOOST_ASSERT(SPECIAL_NODEID != node_u);
BOOST_ASSERT(node_u != node_v);
const EdgeID forward_e1 = graph.FindEdge(node_u, node_v);
BOOST_ASSERT(SPECIAL_EDGEID != forward_e1);
BOOST_ASSERT(node_v == graph.GetTarget(forward_e1));
const EdgeID reverse_e1 = graph.FindEdge(node_w, node_v);
BOOST_ASSERT(SPECIAL_EDGEID != reverse_e1);
BOOST_ASSERT(node_v == graph.GetTarget(reverse_e1));
const EdgeData &fwd_edge_data1 = graph.GetEdgeData(forward_e1);
const EdgeData &rev_edge_data1 = graph.GetEdgeData(reverse_e1);
if (graph.FindEdgeInEitherDirection(node_u, node_w) != SPECIAL_EDGEID)
{
continue;
}
// this case can happen if two ways with different names overlap
if (fwd_edge_data1.name_id != rev_edge_data1.name_id ||
fwd_edge_data2.name_id != rev_edge_data2.name_id)
{
continue;
}
if (fwd_edge_data1.IsCompatibleTo(fwd_edge_data2) &&
rev_edge_data1.IsCompatibleTo(rev_edge_data2))
{
BOOST_ASSERT(graph.GetEdgeData(forward_e1).name_id ==
graph.GetEdgeData(reverse_e1).name_id);
BOOST_ASSERT(graph.GetEdgeData(forward_e2).name_id ==
graph.GetEdgeData(reverse_e2).name_id);
// Get distances before graph is modified
const int forward_weight1 = graph.GetEdgeData(forward_e1).distance;
const int forward_weight2 = graph.GetEdgeData(forward_e2).distance;
BOOST_ASSERT(0 != forward_weight1);
BOOST_ASSERT(0 != forward_weight2);
const int reverse_weight1 = graph.GetEdgeData(reverse_e1).distance;
const int reverse_weight2 = graph.GetEdgeData(reverse_e2).distance;
BOOST_ASSERT(0 != reverse_weight1);
BOOST_ASSERT(0 != reverse_weight2);
const bool has_node_penalty = traffic_lights.find(node_v) != traffic_lights.end();
// add weight of e2's to e1
graph.GetEdgeData(forward_e1).distance += fwd_edge_data2.distance;
graph.GetEdgeData(reverse_e1).distance += rev_edge_data2.distance;
if (has_node_penalty)
{
graph.GetEdgeData(forward_e1).distance += speed_profile.traffic_signal_penalty;
graph.GetEdgeData(reverse_e1).distance += speed_profile.traffic_signal_penalty;
}
// extend e1's to targets of e2's
graph.SetTarget(forward_e1, node_w);
graph.SetTarget(reverse_e1, node_u);
// remove e2's (if bidir, otherwise only one)
graph.DeleteEdge(node_v, forward_e2);
graph.DeleteEdge(node_v, reverse_e2);
// update any involved turn restrictions
restriction_map.FixupStartingTurnRestriction(node_u, node_v, node_w);
restriction_map.FixupArrivingTurnRestriction(node_u, node_v, node_w, graph);
restriction_map.FixupStartingTurnRestriction(node_w, node_v, node_u);
restriction_map.FixupArrivingTurnRestriction(node_w, node_v, node_u, graph);
// store compressed geometry in container
geometry_compressor.CompressEdge(
forward_e1, forward_e2, node_v, node_w,
forward_weight1 + (has_node_penalty ? speed_profile.traffic_signal_penalty : 0),
forward_weight2);
geometry_compressor.CompressEdge(
reverse_e1, reverse_e2, node_v, node_u, reverse_weight1,
reverse_weight2 + (has_node_penalty ? speed_profile.traffic_signal_penalty : 0));
}
}
PrintStatistics(original_number_of_nodes, original_number_of_edges, graph);
}
void GraphCompressor::PrintStatistics(unsigned original_number_of_nodes,
unsigned original_number_of_edges,
const util::NodeBasedDynamicGraph &graph) const
{
unsigned new_node_count = 0;
unsigned new_edge_count = 0;
for (const auto i : util::irange(0u, graph.GetNumberOfNodes()))
{
if (graph.GetOutDegree(i) > 0)
{
++new_node_count;
new_edge_count += (graph.EndEdges(i) - graph.BeginEdges(i));
}
}
util::SimpleLogger().Write() << "Node compression ratio: "
<< new_node_count / (double)original_number_of_nodes;
util::SimpleLogger().Write() << "Edge compression ratio: "
<< new_edge_count / (double)original_number_of_edges;
}
}
}
<commit_msg>Disable compression across traffic lights. Previously, we merged the traffic light penalty into the edge weight. When later considering traffic data, we need to be able to update just the edge weight, and it was impossible to extricate the traffic penalty. This increases the number of edge-based-nodes a little bit, but some quick tests show it should only be about 0.1% overall (only affects traffic signals on edges with no intersections (i.e. degree=2))<commit_after>#include "extractor/graph_compressor.hpp"
#include "extractor/compressed_edge_container.hpp"
#include "extractor/restriction_map.hpp"
#include "util/dynamic_graph.hpp"
#include "util/node_based_graph.hpp"
#include "util/percent.hpp"
#include "util/simple_logger.hpp"
namespace osrm
{
namespace extractor
{
GraphCompressor::GraphCompressor(SpeedProfileProperties speed_profile)
: speed_profile(std::move(speed_profile))
{
}
void GraphCompressor::Compress(const std::unordered_set<NodeID> &barrier_nodes,
const std::unordered_set<NodeID> &traffic_lights,
RestrictionMap &restriction_map,
util::NodeBasedDynamicGraph &graph,
CompressedEdgeContainer &geometry_compressor)
{
const unsigned original_number_of_nodes = graph.GetNumberOfNodes();
const unsigned original_number_of_edges = graph.GetNumberOfEdges();
util::Percent progress(original_number_of_nodes);
for (const NodeID node_v : util::irange(0u, original_number_of_nodes))
{
progress.printStatus(node_v);
// only contract degree 2 vertices
if (2 != graph.GetOutDegree(node_v))
{
continue;
}
// don't contract barrier node
if (barrier_nodes.end() != barrier_nodes.find(node_v))
{
continue;
}
// check if v is a via node for a turn restriction, i.e. a 'directed' barrier node
if (restriction_map.IsViaNode(node_v))
{
continue;
}
// reverse_e2 forward_e2
// u <---------- v -----------> w
// ----------> <-----------
// forward_e1 reverse_e1
//
// Will be compressed to:
//
// reverse_e1
// u <---------- w
// ---------->
// forward_e1
//
// If the edges are compatible.
const bool reverse_edge_order = graph.GetEdgeData(graph.BeginEdges(node_v)).reversed;
const EdgeID forward_e2 = graph.BeginEdges(node_v) + reverse_edge_order;
BOOST_ASSERT(SPECIAL_EDGEID != forward_e2);
BOOST_ASSERT(forward_e2 >= graph.BeginEdges(node_v) && forward_e2 < graph.EndEdges(node_v));
const EdgeID reverse_e2 = graph.BeginEdges(node_v) + 1 - reverse_edge_order;
BOOST_ASSERT(SPECIAL_EDGEID != reverse_e2);
BOOST_ASSERT(reverse_e2 >= graph.BeginEdges(node_v) && reverse_e2 < graph.EndEdges(node_v));
const EdgeData &fwd_edge_data2 = graph.GetEdgeData(forward_e2);
const EdgeData &rev_edge_data2 = graph.GetEdgeData(reverse_e2);
const NodeID node_w = graph.GetTarget(forward_e2);
BOOST_ASSERT(SPECIAL_NODEID != node_w);
BOOST_ASSERT(node_v != node_w);
const NodeID node_u = graph.GetTarget(reverse_e2);
BOOST_ASSERT(SPECIAL_NODEID != node_u);
BOOST_ASSERT(node_u != node_v);
const EdgeID forward_e1 = graph.FindEdge(node_u, node_v);
BOOST_ASSERT(SPECIAL_EDGEID != forward_e1);
BOOST_ASSERT(node_v == graph.GetTarget(forward_e1));
const EdgeID reverse_e1 = graph.FindEdge(node_w, node_v);
BOOST_ASSERT(SPECIAL_EDGEID != reverse_e1);
BOOST_ASSERT(node_v == graph.GetTarget(reverse_e1));
const EdgeData &fwd_edge_data1 = graph.GetEdgeData(forward_e1);
const EdgeData &rev_edge_data1 = graph.GetEdgeData(reverse_e1);
if (graph.FindEdgeInEitherDirection(node_u, node_w) != SPECIAL_EDGEID)
{
continue;
}
// this case can happen if two ways with different names overlap
if (fwd_edge_data1.name_id != rev_edge_data1.name_id ||
fwd_edge_data2.name_id != rev_edge_data2.name_id)
{
continue;
}
if (fwd_edge_data1.IsCompatibleTo(fwd_edge_data2) &&
rev_edge_data1.IsCompatibleTo(rev_edge_data2))
{
BOOST_ASSERT(graph.GetEdgeData(forward_e1).name_id ==
graph.GetEdgeData(reverse_e1).name_id);
BOOST_ASSERT(graph.GetEdgeData(forward_e2).name_id ==
graph.GetEdgeData(reverse_e2).name_id);
// Do not compress edge if it crosses a traffic signal.
// This can't be done in IsCompatibleTo, becase we only store the
// traffic signals in the `traffic_lights` list, which EdgeData
// doesn't have access to.
const bool has_node_penalty = traffic_lights.find(node_v) != traffic_lights.end();
if (has_node_penalty)
{
continue;
}
// Get distances before graph is modified
const int forward_weight1 = graph.GetEdgeData(forward_e1).distance;
const int forward_weight2 = graph.GetEdgeData(forward_e2).distance;
BOOST_ASSERT(0 != forward_weight1);
BOOST_ASSERT(0 != forward_weight2);
const int reverse_weight1 = graph.GetEdgeData(reverse_e1).distance;
const int reverse_weight2 = graph.GetEdgeData(reverse_e2).distance;
BOOST_ASSERT(0 != reverse_weight1);
BOOST_ASSERT(0 != reverse_weight2);
// add weight of e2's to e1
graph.GetEdgeData(forward_e1).distance += fwd_edge_data2.distance;
graph.GetEdgeData(reverse_e1).distance += rev_edge_data2.distance;
// extend e1's to targets of e2's
graph.SetTarget(forward_e1, node_w);
graph.SetTarget(reverse_e1, node_u);
// remove e2's (if bidir, otherwise only one)
graph.DeleteEdge(node_v, forward_e2);
graph.DeleteEdge(node_v, reverse_e2);
// update any involved turn restrictions
restriction_map.FixupStartingTurnRestriction(node_u, node_v, node_w);
restriction_map.FixupArrivingTurnRestriction(node_u, node_v, node_w, graph);
restriction_map.FixupStartingTurnRestriction(node_w, node_v, node_u);
restriction_map.FixupArrivingTurnRestriction(node_w, node_v, node_u, graph);
// store compressed geometry in container
geometry_compressor.CompressEdge(
forward_e1, forward_e2, node_v, node_w,
forward_weight1, forward_weight2);
geometry_compressor.CompressEdge(
reverse_e1, reverse_e2, node_v, node_u,
reverse_weight1, reverse_weight2);
}
}
PrintStatistics(original_number_of_nodes, original_number_of_edges, graph);
}
void GraphCompressor::PrintStatistics(unsigned original_number_of_nodes,
unsigned original_number_of_edges,
const util::NodeBasedDynamicGraph &graph) const
{
unsigned new_node_count = 0;
unsigned new_edge_count = 0;
for (const auto i : util::irange(0u, graph.GetNumberOfNodes()))
{
if (graph.GetOutDegree(i) > 0)
{
++new_node_count;
new_edge_count += (graph.EndEdges(i) - graph.BeginEdges(i));
}
}
util::SimpleLogger().Write() << "Node compression ratio: "
<< new_node_count / (double)original_number_of_nodes;
util::SimpleLogger().Write() << "Edge compression ratio: "
<< new_edge_count / (double)original_number_of_edges;
}
}
}
<|endoftext|>
|
<commit_before>#include <stdint.h>
#include "types.h"
#include "GetProofOfStakeReward.h"
money_t GetProofOfStakeReward(timestamp_t coinAge, blockheight_t height)
{
// The actual formula is shaped as (A + exp(B * nHeight) + C)
// Since we can't use float, and that using fixed-point numbers would be both complex and error-prone, we chose to use a step-by-step solution
// Each array cell is the reward given starting from a specific bloc height. Each cells will be applied for the next 43,836 blocks (about a month)
// Note that these values have to be divided by 10,000 later (ie 9278 is actually 0.9278).
static uint16_t const rewardSteps[] = { 10000, 9754, 9593, 9435, 9278, 9124, 8972, 8823, 8675, 8530, 8386, 8245, 8106, 7969, 7834, 7701, 7569, 7440, 7312, 7187, 7063, 6941, 6821, 6702, 6585, 6470, 6356, 6245, 6134, 6026, 5919, 5813, 5709, 5607, 5505, 5406, 5308, 5211, 5116, 5022, 4929, 4838, 4748, 4659, 4572, 4486, 4401, 4318, 4235, 4154, 4074, 3995, 3917, 3841, 3765, 3691, 3617, 3545, 3474, 3404, 3334, 3266, 3199, 3133, 3067, 3003, 2940, 2877, 2816, 2755, 2695, 2636, 2578, 2521, 2464, 2409, 2354, 2300, 2247, 2194, 2142, 2091, 2041, 1992, 1943, 1895, 1847, 1801, 1755, 1709, 1664, 1620, 1577, 1534, 1492, 1450, 1409, 1369, 1329, 1290, 1251, 1213, 1176, 1139, 1102, 1066, 1031, 996, 961, 928, 894, 861, 829, 797, 765, 734, 703, 673, 643, 600 };
uint32_t stepIndex = height / 43836;
uint32_t stepCount = sizeof( rewardSteps ) / sizeof( rewardSteps[ 0 ] );
if ( stepIndex >= stepCount )
stepIndex = stepCount;
money_t rewardCoinYear = COIN * rewardSteps[ stepIndex ] / 10000;
// So basically, we're getting the number of coin per year (above), divided by the number of days in a year, multiplied by the coin age (in days) of the stake (prorata).
// If the end of the formula looks weird to you, it's because there isn't exactly 365 days in a year - that would be forgetting the leap years ... So there's actually 365.2421 days.
// "( 365 * 33 + 8 ) / 33" is approximatively 0.2424. "* 33 / ( 365 * 33 + 8 )" is a way to take this in account without risking losing precision (ie. without using floats).
return coinAge * rewardCoinYear * 33 / ( 365 * 33 + 8 );
}
<commit_msg>Fixes buffer overflow<commit_after>#include <stdint.h>
#include "types.h"
#include "GetProofOfStakeReward.h"
money_t GetProofOfStakeReward(timestamp_t coinAge, blockheight_t height)
{
// The actual formula is shaped as (A + exp(B * nHeight) + C)
// Since we can't use float, and that using fixed-point numbers would be both complex and error-prone, we chose to use a step-by-step solution
// Each array cell is the reward given starting from a specific bloc height. Each cells will be applied for the next 43,836 blocks (about a month)
// Note that these values have to be divided by 10,000 later (ie 9278 is actually 0.9278).
static uint16_t const rewardSteps[] = { 10000, 9754, 9593, 9435, 9278, 9124, 8972, 8823, 8675, 8530, 8386, 8245, 8106, 7969, 7834, 7701, 7569, 7440, 7312, 7187, 7063, 6941, 6821, 6702, 6585, 6470, 6356, 6245, 6134, 6026, 5919, 5813, 5709, 5607, 5505, 5406, 5308, 5211, 5116, 5022, 4929, 4838, 4748, 4659, 4572, 4486, 4401, 4318, 4235, 4154, 4074, 3995, 3917, 3841, 3765, 3691, 3617, 3545, 3474, 3404, 3334, 3266, 3199, 3133, 3067, 3003, 2940, 2877, 2816, 2755, 2695, 2636, 2578, 2521, 2464, 2409, 2354, 2300, 2247, 2194, 2142, 2091, 2041, 1992, 1943, 1895, 1847, 1801, 1755, 1709, 1664, 1620, 1577, 1534, 1492, 1450, 1409, 1369, 1329, 1290, 1251, 1213, 1176, 1139, 1102, 1066, 1031, 996, 961, 928, 894, 861, 829, 797, 765, 734, 703, 673, 643, 600 };
uint32_t stepIndex = height / 43836;
uint32_t stepCount = sizeof( rewardSteps ) / sizeof( rewardSteps[ 0 ] );
if ( stepIndex >= stepCount )
stepIndex = stepCount - 1;
money_t rewardCoinYear = COIN * rewardSteps[ stepIndex ] / 10000;
// So basically, we're getting the number of coin per year (above), divided by the number of days in a year, multiplied by the coin age (in days) of the stake (prorata).
// If the end of the formula looks weird to you, it's because there isn't exactly 365 days in a year - that would be forgetting the leap years ... So there's actually 365.2421 days.
// "( 365 * 33 + 8 ) / 33" is approximatively 0.2424. "* 33 / ( 365 * 33 + 8 )" is a way to take this in account without risking losing precision (ie. without using floats).
return coinAge * rewardCoinYear * 33 / ( 365 * 33 + 8 );
}
<|endoftext|>
|
<commit_before><commit_msg>No cloud collisions<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
> File Name: TaskSerializer.cpp
> Project Name: Hearthstonepp
> Author: Young-Joong Kim
> Purpose: Serializer for TaskMeta and MetaData
> Created Time: 2018/05/20
> Copyright (c) 2018, Young-Joong Kim
*************************************************************************/
#include <Cards/Character.h>
#include <Cards/Weapon.h>
#include <Tasks/MetaData.h>
#include <Tasks/TaskSerializer.h>
#include <algorithm>
namespace Hearthstonepp::Serializer
{
flatbuffers::Offset<FlatData::Entity> CreateEntity(
flatbuffers::FlatBufferBuilder& builder, const Entity* entity)
{
if (entity == nullptr)
{
return FlatData::CreateEntity(builder);
}
return FlatData::CreateEntity(builder, CreateCard(builder, entity->card),
0);
}
flatbuffers::Offset<FlatData::Card> CreateCard(
flatbuffers::FlatBufferBuilder& builder, const Card* card)
{
std::vector<int> mechanics;
mechanics.reserve(card->mechanics.size());
for (const auto& mechanic : card->mechanics)
{
mechanics.emplace_back(static_cast<int>(mechanic));
}
size_t attack = card->attack ? *card->attack : 0;
size_t health = card->health ? *card->health : 0;
size_t durability = card->durability ? *card->durability : 0;
return FlatData::CreateCard(
builder, builder.CreateString(card->id), static_cast<int>(card->rarity),
static_cast<int>(card->faction), static_cast<int>(card->cardSet),
static_cast<int>(card->cardClass), static_cast<int>(card->cardType),
static_cast<int>(card->race), builder.CreateString(card->name),
builder.CreateString(card->text), card->isCollectible,
static_cast<int>(card->cost), static_cast<uint32_t>(attack),
static_cast<uint32_t>(health), static_cast<uint32_t>(durability),
builder.CreateVector(mechanics), 0, 0, card->GetMaxAllowedInDeck());
}
TaskMeta CreateEntityVector(const TaskMetaTrait& trait,
const std::vector<Entity*>& vector)
{
flatbuffers::FlatBufferBuilder builder(1024);
std::vector<flatbuffers::Offset<FlatData::Entity>> flatten;
for (const auto entity : vector)
{
flatten.emplace_back(CreateEntity(builder, entity));
}
auto entities =
FlatData::CreateEntityVector(builder, builder.CreateVector(flatten));
builder.Finish(entities);
return TaskMeta(trait, builder.GetSize(), builder.GetBufferPointer());
}
TaskMeta CreateTaskMetaVector(const std::vector<TaskMeta>& vector,
MetaData status, BYTE userID)
{
flatbuffers::FlatBufferBuilder builder(1024);
std::vector<flatbuffers::Offset<FlatData::TaskMeta>> flatten;
// Convert TaskMeta to FlatData::TaskMeta
for (const auto& task : vector)
{
auto trait = FlatData::TaskMetaTrait(static_cast<int>(task.id),
static_cast<status_t>(task.status),
task.userID);
const auto& unique = task.GetConstBuffer();
auto buffer = builder.CreateVector(unique.get(), task.GetBufferSize());
auto temporal = FlatData::CreateTaskMeta(builder, &trait, buffer);
flatten.emplace_back(std::move(temporal));
}
// Convert std::vector to FlatData::TaskMetaVector
auto integrated =
FlatData::CreateTaskMetaVector(builder, builder.CreateVector(flatten));
builder.Finish(integrated);
return TaskMeta(TaskMetaTrait(TaskID::TASK_VECTOR, status, userID),
builder.GetSize(), builder.GetBufferPointer());
}
TaskMeta CreateRequire(TaskID request, BYTE userID)
{
flatbuffers::FlatBufferBuilder builder(32);
auto flat =
FlatData::CreateRequireTaskMeta(builder, static_cast<int>(request));
builder.Finish(flat);
return TaskMeta(TaskMetaTrait(TaskID::REQUIRE, MetaData::INVALID, userID),
builder.GetSize(), builder.GetBufferPointer());
}
TaskMeta CreateResponseMulligan(const BYTE* index, size_t size)
{
flatbuffers::FlatBufferBuilder builder(32);
auto vector = builder.CreateVector(index, size);
auto flat = FlatData::CreateResponseMulligan(builder, vector);
builder.Finish(flat);
return TaskMeta(TaskMetaTrait(TaskID::MULLIGAN), builder.GetSize(),
builder.GetBufferPointer());
}
TaskMeta CreateResponsePlayCard(size_t cardIndex)
{
flatbuffers::FlatBufferBuilder builder(32);
auto flat =
FlatData::CreateResponsePlayCard(builder, static_cast<BYTE>(cardIndex));
builder.Finish(flat);
return TaskMeta(TaskMetaTrait(TaskID::SELECT_CARD, MetaData::SELECT_CARD),
builder.GetSize(), builder.GetBufferPointer());
}
TaskMeta CreateResponsePlayMinion(size_t position)
{
flatbuffers::FlatBufferBuilder builder(32);
auto flat = FlatData::CreateResponsePlayMinion(builder,
static_cast<BYTE>(position));
builder.Finish(flat);
return TaskMeta(
TaskMetaTrait(TaskID::SELECT_POSITION, MetaData::SELECT_POSITION),
builder.GetSize(), builder.GetBufferPointer());
}
TaskMeta CreateResponseTarget(size_t src, size_t dst)
{
flatbuffers::FlatBufferBuilder builder(32);
auto flat = FlatData::CreateResponseTarget(builder, static_cast<BYTE>(src),
static_cast<BYTE>(dst));
builder.Finish(flat);
return TaskMeta(
TaskMetaTrait(TaskID::SELECT_TARGET, MetaData::SELECT_TARGET),
builder.GetSize(), builder.GetBufferPointer());
}
TaskMeta CreatePlayerSetting(const std::string& player1,
const std::string& player2)
{
flatbuffers::FlatBufferBuilder builder(256);
auto setting = FlatData::CreatePlayerSetting(
builder, builder.CreateString(player1), builder.CreateString(player2));
builder.Finish(setting);
return TaskMeta(TaskMetaTrait(TaskID::PLAYER_SETTING), builder.GetSize(),
builder.GetBufferPointer());
}
TaskMeta CreateGameStatus(TaskID taskID, MetaData status, const Player& player1,
const Player& player2)
{
using EntityOffset = flatbuffers::Offset<FlatData::Entity>;
using VectorOffset = flatbuffers::Offset<flatbuffers::Vector<EntityOffset>>;
flatbuffers::FlatBufferBuilder builder(256);
// Tie multi card vector
auto target = {player1.field, player2.field, player1.attacked,
player2.attacked};
std::vector<VectorOffset> result(target.size());
// Convert Card vector to FlatData::Card vector
std::transform(target.begin(), target.end(), result.begin(),
[&builder](auto&& vec) -> VectorOffset {
std::vector<EntityOffset> dest(vec.size());
std::transform(vec.begin(), vec.end(), dest.begin(),
[&builder](Entity* entity) {
return CreateEntity(builder, entity);
});
return builder.CreateVector(dest);
});
auto gameStatus = FlatData::CreateGameStatus(
builder, player1.id, player2.id, player1.existMana, player2.existMana,
CreateEntity(builder, player1.hero),
CreateEntity(builder, player2.hero), result[0], result[1], result[2],
static_cast<BYTE>(player2.hand.size()),
static_cast<BYTE>(player1.cards.size()),
static_cast<BYTE>(player2.cards.size()), result[3], result[4]);
builder.Finish(gameStatus);
return TaskMeta(TaskMetaTrait(taskID, status, player1.id),
builder.GetSize(), builder.GetBufferPointer());
}
} // namespace Hearthstonepp::Serializer
<commit_msg>[ci skip] Update TaskSerializer - Fix invalid Argument of player1.hand<commit_after>/*************************************************************************
> File Name: TaskSerializer.cpp
> Project Name: Hearthstonepp
> Author: Young-Joong Kim
> Purpose: Serializer for TaskMeta and MetaData
> Created Time: 2018/05/20
> Copyright (c) 2018, Young-Joong Kim
*************************************************************************/
#include <Cards/Character.h>
#include <Cards/Weapon.h>
#include <Tasks/MetaData.h>
#include <Tasks/TaskSerializer.h>
#include <algorithm>
namespace Hearthstonepp::Serializer
{
flatbuffers::Offset<FlatData::Entity> CreateEntity(
flatbuffers::FlatBufferBuilder& builder, const Entity* entity)
{
if (entity == nullptr)
{
return FlatData::CreateEntity(builder);
}
return FlatData::CreateEntity(builder, CreateCard(builder, entity->card),
0);
}
flatbuffers::Offset<FlatData::Card> CreateCard(
flatbuffers::FlatBufferBuilder& builder, const Card* card)
{
std::vector<int> mechanics;
mechanics.reserve(card->mechanics.size());
for (const auto& mechanic : card->mechanics)
{
mechanics.emplace_back(static_cast<int>(mechanic));
}
size_t attack = card->attack ? *card->attack : 0;
size_t health = card->health ? *card->health : 0;
size_t durability = card->durability ? *card->durability : 0;
return FlatData::CreateCard(
builder, builder.CreateString(card->id), static_cast<int>(card->rarity),
static_cast<int>(card->faction), static_cast<int>(card->cardSet),
static_cast<int>(card->cardClass), static_cast<int>(card->cardType),
static_cast<int>(card->race), builder.CreateString(card->name),
builder.CreateString(card->text), card->isCollectible,
static_cast<int>(card->cost), static_cast<uint32_t>(attack),
static_cast<uint32_t>(health), static_cast<uint32_t>(durability),
builder.CreateVector(mechanics), 0, 0, card->GetMaxAllowedInDeck());
}
TaskMeta CreateEntityVector(const TaskMetaTrait& trait,
const std::vector<Entity*>& vector)
{
flatbuffers::FlatBufferBuilder builder(1024);
std::vector<flatbuffers::Offset<FlatData::Entity>> flatten;
for (const auto entity : vector)
{
flatten.emplace_back(CreateEntity(builder, entity));
}
auto entities =
FlatData::CreateEntityVector(builder, builder.CreateVector(flatten));
builder.Finish(entities);
return TaskMeta(trait, builder.GetSize(), builder.GetBufferPointer());
}
TaskMeta CreateTaskMetaVector(const std::vector<TaskMeta>& vector,
MetaData status, BYTE userID)
{
flatbuffers::FlatBufferBuilder builder(1024);
std::vector<flatbuffers::Offset<FlatData::TaskMeta>> flatten;
// Convert TaskMeta to FlatData::TaskMeta
for (const auto& task : vector)
{
auto trait = FlatData::TaskMetaTrait(static_cast<int>(task.id),
static_cast<status_t>(task.status),
task.userID);
const auto& unique = task.GetConstBuffer();
auto buffer = builder.CreateVector(unique.get(), task.GetBufferSize());
auto temporal = FlatData::CreateTaskMeta(builder, &trait, buffer);
flatten.emplace_back(std::move(temporal));
}
// Convert std::vector to FlatData::TaskMetaVector
auto integrated =
FlatData::CreateTaskMetaVector(builder, builder.CreateVector(flatten));
builder.Finish(integrated);
return TaskMeta(TaskMetaTrait(TaskID::TASK_VECTOR, status, userID),
builder.GetSize(), builder.GetBufferPointer());
}
TaskMeta CreateRequire(TaskID request, BYTE userID)
{
flatbuffers::FlatBufferBuilder builder(32);
auto flat =
FlatData::CreateRequireTaskMeta(builder, static_cast<int>(request));
builder.Finish(flat);
return TaskMeta(TaskMetaTrait(TaskID::REQUIRE, MetaData::INVALID, userID),
builder.GetSize(), builder.GetBufferPointer());
}
TaskMeta CreateResponseMulligan(const BYTE* index, size_t size)
{
flatbuffers::FlatBufferBuilder builder(32);
auto vector = builder.CreateVector(index, size);
auto flat = FlatData::CreateResponseMulligan(builder, vector);
builder.Finish(flat);
return TaskMeta(TaskMetaTrait(TaskID::MULLIGAN), builder.GetSize(),
builder.GetBufferPointer());
}
TaskMeta CreateResponsePlayCard(size_t cardIndex)
{
flatbuffers::FlatBufferBuilder builder(32);
auto flat =
FlatData::CreateResponsePlayCard(builder, static_cast<BYTE>(cardIndex));
builder.Finish(flat);
return TaskMeta(TaskMetaTrait(TaskID::SELECT_CARD, MetaData::SELECT_CARD),
builder.GetSize(), builder.GetBufferPointer());
}
TaskMeta CreateResponsePlayMinion(size_t position)
{
flatbuffers::FlatBufferBuilder builder(32);
auto flat = FlatData::CreateResponsePlayMinion(builder,
static_cast<BYTE>(position));
builder.Finish(flat);
return TaskMeta(
TaskMetaTrait(TaskID::SELECT_POSITION, MetaData::SELECT_POSITION),
builder.GetSize(), builder.GetBufferPointer());
}
TaskMeta CreateResponseTarget(size_t src, size_t dst)
{
flatbuffers::FlatBufferBuilder builder(32);
auto flat = FlatData::CreateResponseTarget(builder, static_cast<BYTE>(src),
static_cast<BYTE>(dst));
builder.Finish(flat);
return TaskMeta(
TaskMetaTrait(TaskID::SELECT_TARGET, MetaData::SELECT_TARGET),
builder.GetSize(), builder.GetBufferPointer());
}
TaskMeta CreatePlayerSetting(const std::string& player1,
const std::string& player2)
{
flatbuffers::FlatBufferBuilder builder(256);
auto setting = FlatData::CreatePlayerSetting(
builder, builder.CreateString(player1), builder.CreateString(player2));
builder.Finish(setting);
return TaskMeta(TaskMetaTrait(TaskID::PLAYER_SETTING), builder.GetSize(),
builder.GetBufferPointer());
}
TaskMeta CreateGameStatus(TaskID taskID, MetaData status, const Player& player1,
const Player& player2)
{
using EntityOffset = flatbuffers::Offset<FlatData::Entity>;
using VectorOffset = flatbuffers::Offset<flatbuffers::Vector<EntityOffset>>;
flatbuffers::FlatBufferBuilder builder(256);
auto makeOffset = [&builder](auto&& vec) -> VectorOffset {
std::vector<EntityOffset> dest(vec.size());
std::transform(vec.begin(), vec.end(), dest.begin(),
[&builder](Entity* entity) {
return CreateEntity(builder, entity);
});
return builder.CreateVector(dest);
};
// Tie multi card vector
auto target = {player1.field, player2.field, player1.attacked,
player2.attacked};
std::vector<VectorOffset> result(target.size());
// Convert Card vector to FlatData::Card vector
std::transform(target.begin(), target.end(), result.begin(), makeOffset);
auto gameStatus = FlatData::CreateGameStatus(
builder, player1.id, player2.id, player1.existMana, player2.existMana,
CreateEntity(builder, player1.hero),
CreateEntity(builder, player2.hero), result[0],
makeOffset(player1.hand), result[1],
static_cast<BYTE>(player2.hand.size()),
static_cast<BYTE>(player1.cards.size()),
static_cast<BYTE>(player2.cards.size()), result[2], result[3]);
builder.Finish(gameStatus);
return TaskMeta(TaskMetaTrait(taskID, status, player1.id),
builder.GetSize(), builder.GetBufferPointer());
}
} // namespace Hearthstonepp::Serializer
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2012, J3P LLC. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "DDImage/Knobs.h"
#include "DDImage/Row.h"
#include "boost/signal.hpp"
#include "boost/bind.hpp"
#include "boost/lexical_cast.hpp"
#include "IECore/LRUCache.h"
#include "IECore/ImageDisplayDriver.h"
#include "IECoreNuke/DisplayIop.h"
#include "IECoreNuke/TypeIds.h"
using namespace IECore;
using namespace IECoreNuke;
using namespace DD::Image;
using namespace Imath;
//////////////////////////////////////////////////////////////////////////
// DisplayDriverServer cache. Many nodes may all want to use a server on
// the same port. We therefore use an LRUCache to manage the lifetime of
// the servers and provide them to the nodes.
//////////////////////////////////////////////////////////////////////////
typedef LRUCache<int, DisplayDriverServerPtr> ServerCache;
// key is the port number for the server.
static DisplayDriverServerPtr serverCacheGetter( int key, size_t cost )
{
cost = 1;
return new DisplayDriverServer( key );
}
// max cost of 4 means we will never have more than 4 unused servers at any one time.
static ServerCache g_servers( serverCacheGetter, 4 );
//////////////////////////////////////////////////////////////////////////
// NukeDisplayDriver implementation
//////////////////////////////////////////////////////////////////////////
namespace IECoreNuke
{
class NukeDisplayDriver : public IECore::ImageDisplayDriver
{
public :
IE_CORE_DECLARERUNTIMETYPEDEXTENSION( NukeDisplayDriver, NukeDisplayDriverTypeId, ImageDisplayDriver );
NukeDisplayDriver( const Imath::Box2i &displayWindow, const Imath::Box2i &dataWindow, const std::vector<std::string> &channelNames, ConstCompoundDataPtr parameters )
: ImageDisplayDriver( displayWindow, dataWindow, channelNames, parameters )
{
if( parameters )
{
m_parameters = parameters->copy();
}
else
{
m_parameters = new CompoundData;
}
instanceCreatedSignal( this );
}
virtual ~NukeDisplayDriver()
{
}
/// Returns a copy of the parameters used in creating this instance. This
/// is useful in recognising relevant instances in the instanceCreatedSignal.
ConstCompoundDataPtr parameters() const
{
return m_parameters;
}
/// Updates the current image, and then emits the dataReceivedSignal.
virtual void imageData( const Imath::Box2i &box, const float *data, size_t dataSize )
{
ImageDisplayDriver::imageData( box, data, dataSize );
dataReceivedSignal( this, box );
}
/// This signal is emitted when a new NukeDisplayDriver has been created.
/// This allows nuke nodes to pick up the new DisplayDrivers even when they're
/// created in some other code, such as a DisplayDriverServer.
typedef boost::signal<void( NukeDisplayDriver * )> InstanceCreatedSignal;
static InstanceCreatedSignal instanceCreatedSignal;
/// This signal is emitted when this NukeDisplayDriver instance receives new data.
typedef boost::signal<void( NukeDisplayDriver *, const Imath::Box2i &box )> DataReceivedSignal;
DataReceivedSignal dataReceivedSignal;
private :
static const DisplayDriverDescription<NukeDisplayDriver> g_description;
ConstCompoundDataPtr m_parameters;
};
NukeDisplayDriver::InstanceCreatedSignal NukeDisplayDriver::instanceCreatedSignal;
const DisplayDriver::DisplayDriverDescription<NukeDisplayDriver> NukeDisplayDriver::g_description;
} // namespace IECoreNuke
//////////////////////////////////////////////////////////////////////////
// DisplayIop implementation
//////////////////////////////////////////////////////////////////////////
const DD::Image::Iop::Description DisplayIop::g_description( "ieDisplay", DisplayIop::build );
DisplayIop::DisplayIop( Node *node )
: Iop( node ), m_portNumber( 1559 ), m_updateCount( 0 ), m_server( g_servers.get( m_portNumber ) ), m_driver( 0 )
{
inputs( 0 );
slowness( 0 ); // disable caching as we're buffering everything internally ourselves
NukeDisplayDriver::instanceCreatedSignal.connect( boost::bind( &DisplayIop::driverCreated, this, _1 ) );
}
DisplayIop::~DisplayIop()
{
NukeDisplayDriver::instanceCreatedSignal.disconnect( boost::bind( &DisplayIop::driverCreated, this, _1 ) );
connectToDriver( 0 );
}
const char *DisplayIop::Class() const
{
return "ieDisplay";
}
const char *DisplayIop::node_help() const
{
return "Acts as a framebuffer for external renderers.";
}
void DisplayIop::knobs( DD::Image::Knob_Callback f )
{
Iop::knobs( f );
Int_knob( f, &m_portNumber, "portNumber", "Port Number" );
SetFlags( f, Knob::KNOB_CHANGED_ALWAYS | Knob::NO_ANIMATION );
Tooltip(
f,
"The port on which to receive images. This must match "
"the port being used by the renderer to send images."
);
}
int DisplayIop::knob_changed( DD::Image::Knob *knob )
{
if( knob->is( "portNumber" ) )
{
int portNumber = this->knob( "portNumber" )->get_value();
m_server = g_servers.get( portNumber );
return 1;
}
return Iop::knob_changed( knob );
}
void DisplayIop::append( DD::Image::Hash &hash )
{
Iop::append( hash );
hash.append( __DATE__ );
hash.append( __TIME__ );
hash.append( firstDisplayIop()->m_updateCount );
}
void DisplayIop::_validate( bool forReal )
{
Box2i displayWindow( V2i( 0, 0 ), V2i( 255, 255 ) );
if( firstDisplayIop()->m_driver )
{
displayWindow = firstDisplayIop()->m_driver->image()->getDisplayWindow();
}
m_format = m_fullSizeFormat = Format( displayWindow.size().x + 1, displayWindow.size().y + 1 );
// these set function don't copy the format, but instead reference its address.
// we therefore have to store the format as member data.
info_.format( m_format );
info_.full_size_format( m_fullSizeFormat );
info_.set( m_format );
info_.channels( Mask_RGBA );
}
void DisplayIop::engine( int y, int x, int r, const DD::Image::ChannelSet &channels, DD::Image::Row &row )
{
Channel outputChannels[4] = { Chan_Red, Chan_Green, Chan_Blue, Chan_Alpha };
const char *inputChannels[] = { "R", "G", "B", "A", 0 };
const ImagePrimitive *image = 0;
Box2i inputDataWindow;
Box2i inputDisplayWindow;
if( firstDisplayIop()->m_driver )
{
image = firstDisplayIop()->m_driver->image().get();
inputDataWindow = image->getDataWindow();
inputDisplayWindow = image->getDisplayWindow();
}
int i = 0;
while( inputChannels[i] )
{
const FloatVectorData *inputData = image ? image->variableData<FloatVectorData>( inputChannels[i] ) : 0;
if( inputData )
{
float *output = row.writable( outputChannels[i] ) + x;
// remap coordinate relative to our data window. nuke images have pixel origin at bottom,
// cortex images have pixel origin at top.
V2i pDataWindow = V2i( x, inputDisplayWindow.max.y - y ) - inputDataWindow.min;
const float *input = &((inputData->readable())[pDataWindow.y*(inputDataWindow.size().x+1) + pDataWindow.x]);
memcpy( output, input, (r-x) * sizeof( float ) );
}
else
{
row.erase( outputChannels[i] );
}
i++;
}
}
DD::Image::Op *DisplayIop::build( Node *node )
{
return new DisplayIop( node );
}
DisplayIop *DisplayIop::firstDisplayIop()
{
return static_cast<DisplayIop *>( firstOp() );
}
void DisplayIop::driverCreated( NukeDisplayDriver *driver )
{
ConstStringDataPtr portNumber = driver->parameters()->member<StringData>( "displayPort" );
if( portNumber && boost::lexical_cast<int>( portNumber->readable() ) == m_portNumber )
{
firstDisplayIop()->connectToDriver( driver );
}
}
void DisplayIop::connectToDriver( NukeDisplayDriver *driver )
{
assert( this == firstDisplayIop() );
if( m_driver )
{
m_driver->dataReceivedSignal.disconnect( boost::bind( &DisplayIop::driverDataReceived, this, _1, _2 ) );
}
m_driver = driver;
if( m_driver )
{
m_driver->dataReceivedSignal.connect( boost::bind( &DisplayIop::driverDataReceived, this, _1, _2 ) );
}
m_updateCount++;
asapUpdate();
}
void DisplayIop::driverDataReceived( NukeDisplayDriver *driver, const Imath::Box2i &box )
{
assert( this == firstDisplayIop() );
m_updateCount++;
asapUpdate();
}
<commit_msg>Setting KNOB_CHANGED_RECURSIVE on port number knob to work around nuke not calling DisplayIop::knob_changed() when the knob is changed from a PythonPanel.knobChanged() method.<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2012, J3P LLC. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "DDImage/Knobs.h"
#include "DDImage/Row.h"
#include "boost/signal.hpp"
#include "boost/bind.hpp"
#include "boost/lexical_cast.hpp"
#include "IECore/LRUCache.h"
#include "IECore/ImageDisplayDriver.h"
#include "IECoreNuke/DisplayIop.h"
#include "IECoreNuke/TypeIds.h"
using namespace IECore;
using namespace IECoreNuke;
using namespace DD::Image;
using namespace Imath;
//////////////////////////////////////////////////////////////////////////
// DisplayDriverServer cache. Many nodes may all want to use a server on
// the same port. We therefore use an LRUCache to manage the lifetime of
// the servers and provide them to the nodes.
//////////////////////////////////////////////////////////////////////////
typedef LRUCache<int, DisplayDriverServerPtr> ServerCache;
// key is the port number for the server.
static DisplayDriverServerPtr serverCacheGetter( int key, size_t cost )
{
cost = 1;
return new DisplayDriverServer( key );
}
// max cost of 4 means we will never have more than 4 unused servers at any one time.
static ServerCache g_servers( serverCacheGetter, 4 );
//////////////////////////////////////////////////////////////////////////
// NukeDisplayDriver implementation
//////////////////////////////////////////////////////////////////////////
namespace IECoreNuke
{
class NukeDisplayDriver : public IECore::ImageDisplayDriver
{
public :
IE_CORE_DECLARERUNTIMETYPEDEXTENSION( NukeDisplayDriver, NukeDisplayDriverTypeId, ImageDisplayDriver );
NukeDisplayDriver( const Imath::Box2i &displayWindow, const Imath::Box2i &dataWindow, const std::vector<std::string> &channelNames, ConstCompoundDataPtr parameters )
: ImageDisplayDriver( displayWindow, dataWindow, channelNames, parameters )
{
if( parameters )
{
m_parameters = parameters->copy();
}
else
{
m_parameters = new CompoundData;
}
instanceCreatedSignal( this );
}
virtual ~NukeDisplayDriver()
{
}
/// Returns a copy of the parameters used in creating this instance. This
/// is useful in recognising relevant instances in the instanceCreatedSignal.
ConstCompoundDataPtr parameters() const
{
return m_parameters;
}
/// Updates the current image, and then emits the dataReceivedSignal.
virtual void imageData( const Imath::Box2i &box, const float *data, size_t dataSize )
{
ImageDisplayDriver::imageData( box, data, dataSize );
dataReceivedSignal( this, box );
}
/// This signal is emitted when a new NukeDisplayDriver has been created.
/// This allows nuke nodes to pick up the new DisplayDrivers even when they're
/// created in some other code, such as a DisplayDriverServer.
typedef boost::signal<void( NukeDisplayDriver * )> InstanceCreatedSignal;
static InstanceCreatedSignal instanceCreatedSignal;
/// This signal is emitted when this NukeDisplayDriver instance receives new data.
typedef boost::signal<void( NukeDisplayDriver *, const Imath::Box2i &box )> DataReceivedSignal;
DataReceivedSignal dataReceivedSignal;
private :
static const DisplayDriverDescription<NukeDisplayDriver> g_description;
ConstCompoundDataPtr m_parameters;
};
NukeDisplayDriver::InstanceCreatedSignal NukeDisplayDriver::instanceCreatedSignal;
const DisplayDriver::DisplayDriverDescription<NukeDisplayDriver> NukeDisplayDriver::g_description;
} // namespace IECoreNuke
//////////////////////////////////////////////////////////////////////////
// DisplayIop implementation
//////////////////////////////////////////////////////////////////////////
const DD::Image::Iop::Description DisplayIop::g_description( "ieDisplay", DisplayIop::build );
DisplayIop::DisplayIop( Node *node )
: Iop( node ), m_portNumber( 1559 ), m_server( g_servers.get( m_portNumber ) ), m_updateCount( 0 ), m_driver( 0 )
{
inputs( 0 );
slowness( 0 ); // disable caching as we're buffering everything internally ourselves
NukeDisplayDriver::instanceCreatedSignal.connect( boost::bind( &DisplayIop::driverCreated, this, _1 ) );
}
DisplayIop::~DisplayIop()
{
NukeDisplayDriver::instanceCreatedSignal.disconnect( boost::bind( &DisplayIop::driverCreated, this, _1 ) );
connectToDriver( 0 );
}
const char *DisplayIop::Class() const
{
return "ieDisplay";
}
const char *DisplayIop::node_help() const
{
return "Acts as a framebuffer for external renderers.";
}
void DisplayIop::knobs( DD::Image::Knob_Callback f )
{
Iop::knobs( f );
Int_knob( f, &m_portNumber, "portNumber", "Port Number" );
// we must have KNOB_CHANGED_RECURSIVE set otherwise nuke doesn't give us knob_changed()
// calls when the knob value is changed from a knobChanged method of a PythonPanel.
SetFlags( f, Knob::KNOB_CHANGED_ALWAYS | Knob::KNOB_CHANGED_RECURSIVE | Knob::NO_ANIMATION );
Tooltip(
f,
"The port on which to receive images. This must match "
"the port being used by the renderer to send images."
);
}
int DisplayIop::knob_changed( DD::Image::Knob *knob )
{
if( knob->is( "portNumber" ) )
{
int portNumber = this->knob( "portNumber" )->get_value();
m_server = g_servers.get( portNumber );
return 1;
}
return Iop::knob_changed( knob );
}
void DisplayIop::append( DD::Image::Hash &hash )
{
Iop::append( hash );
hash.append( __DATE__ );
hash.append( __TIME__ );
hash.append( firstDisplayIop()->m_updateCount );
}
void DisplayIop::_validate( bool forReal )
{
Box2i displayWindow( V2i( 0, 0 ), V2i( 255, 255 ) );
if( firstDisplayIop()->m_driver )
{
displayWindow = firstDisplayIop()->m_driver->image()->getDisplayWindow();
}
m_format = m_fullSizeFormat = Format( displayWindow.size().x + 1, displayWindow.size().y + 1 );
// these set function don't copy the format, but instead reference its address.
// we therefore have to store the format as member data.
info_.format( m_format );
info_.full_size_format( m_fullSizeFormat );
info_.set( m_format );
info_.channels( Mask_RGBA );
}
void DisplayIop::engine( int y, int x, int r, const DD::Image::ChannelSet &channels, DD::Image::Row &row )
{
Channel outputChannels[4] = { Chan_Red, Chan_Green, Chan_Blue, Chan_Alpha };
const char *inputChannels[] = { "R", "G", "B", "A", 0 };
const ImagePrimitive *image = 0;
Box2i inputDataWindow;
Box2i inputDisplayWindow;
if( firstDisplayIop()->m_driver )
{
image = firstDisplayIop()->m_driver->image().get();
inputDataWindow = image->getDataWindow();
inputDisplayWindow = image->getDisplayWindow();
}
int i = 0;
while( inputChannels[i] )
{
const FloatVectorData *inputData = image ? image->variableData<FloatVectorData>( inputChannels[i] ) : 0;
if( inputData )
{
float *output = row.writable( outputChannels[i] ) + x;
// remap coordinate relative to our data window. nuke images have pixel origin at bottom,
// cortex images have pixel origin at top.
V2i pDataWindow = V2i( x, inputDisplayWindow.max.y - y ) - inputDataWindow.min;
const float *input = &((inputData->readable())[pDataWindow.y*(inputDataWindow.size().x+1) + pDataWindow.x]);
memcpy( output, input, (r-x) * sizeof( float ) );
}
else
{
row.erase( outputChannels[i] );
}
i++;
}
}
DD::Image::Op *DisplayIop::build( Node *node )
{
return new DisplayIop( node );
}
DisplayIop *DisplayIop::firstDisplayIop()
{
return static_cast<DisplayIop *>( firstOp() );
}
void DisplayIop::driverCreated( NukeDisplayDriver *driver )
{
ConstStringDataPtr portNumber = driver->parameters()->member<StringData>( "displayPort" );
if( portNumber && boost::lexical_cast<int>( portNumber->readable() ) == m_portNumber )
{
firstDisplayIop()->connectToDriver( driver );
}
}
void DisplayIop::connectToDriver( NukeDisplayDriver *driver )
{
assert( this == firstDisplayIop() );
if( m_driver )
{
m_driver->dataReceivedSignal.disconnect( boost::bind( &DisplayIop::driverDataReceived, this, _1, _2 ) );
}
m_driver = driver;
if( m_driver )
{
m_driver->dataReceivedSignal.connect( boost::bind( &DisplayIop::driverDataReceived, this, _1, _2 ) );
}
m_updateCount++;
asapUpdate();
}
void DisplayIop::driverDataReceived( NukeDisplayDriver *driver, const Imath::Box2i &box )
{
assert( this == firstDisplayIop() );
m_updateCount++;
asapUpdate();
}
<|endoftext|>
|
<commit_before>/* dlvhex -- Answer-Set Programming with external interfaces.
* Copyright (C) 2005-2007 Roman Schindlauer
* Copyright (C) 2006-2015 Thomas Krennwallner
* Copyright (C) 2009-2016 Peter Schüller
* Copyright (C) 2011-2016 Christoph Redl
* Copyright (C) 2015-2016 Tobias Kaminski
* Copyright (C) 2015-2016 Antonius Weinzierl
*
* This file is part of dlvhex.
*
* dlvhex 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.
*
* dlvhex 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 dlvhex; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA.
*/
/**
* @file InconsistencyAnalyzer.cpp
* @author Christoph Redl
* @date Wed April 20 2016
*
* @brief Computes a reason for the inconsistency in a program unit.
*
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "dlvhex2/BaseModelGenerator.h"
#include "dlvhex2/InconsistencyAnalyzer.h"
#include "dlvhex2/Printer.h"
#include "dlvhex2/ProgramCtx.h"
#include "dlvhex2/Benchmarking.h"
#include "dlvhex2/Benchmarking.h"
#include "dlvhex2/InternalGrounder.h"
#include "dlvhex2/SATSolver.h"
#include <boost/graph/breadth_first_search.hpp>
#include <boost/graph/visitors.hpp>
#include <boost/graph/strong_components.hpp>
#include <boost/graph/filtered_graph.hpp>
#include <boost/foreach.hpp>
DLVHEX_NAMESPACE_BEGIN
InconsistencyAnalyzer::InconsistencyAnalyzer(ProgramCtx& ctx) : ctx(ctx){
}
Nogood InconsistencyAnalyzer::getInconsistencyReason(BaseModelGenerator* mg, InterpretationConstPtr explAtoms, InterpretationConstPtr unitInput, std::vector<ID>& innerEatoms, OrdinaryASPProgram& program, AnnotatedGroundProgram& annotatedOptimizedProgram, bool* haveInconsistencyReason){
#ifndef NDEBUG
DBGLOG(DBG, "Performing inconsistency analyzis for program:" << std::endl << *program.edb << std::endl << printManyToString<RawPrinter>(program.idb, "\n", ctx.registry()));
#endif
// ground the program without optimization
InternalGrounder grounder(ctx, program, InternalGrounder::builtin);
OrdinaryASPProgram gp = grounder.getGroundProgram();
#ifndef NDEBUG
DBGLOG(DBG, "Unoptimized grounded program:" << std::endl << *gp.edb << std::endl << printManyToString<RawPrinter>(gp.idb, "\n", ctx.registry()));
#endif
// Construct domain of the SAT instance.
// It consists of all external atom input atoms and all ordinary atoms in the program (to be added below).
// It can be constructed by using the program mask of the previous (optimized) grounding and adding newly introduced atoms in the non-optimized grounding.
// All input atoms from predecessor components are already contained in the program mask of the optimized grounding.
InterpretationPtr domain(new Interpretation(*annotatedOptimizedProgram.getProgramMask()));
for (int eaIndex = 0; eaIndex < innerEatoms.size(); ++eaIndex) {
const ExternalAtom& eatom = ctx.registry()->eatoms.getByID(innerEatoms[eaIndex]);
eatom.updatePredicateInputMask();
domain->add(*(eatom.getPredicateInputMask()));
}
bm::bvector<>::enumerator en, en_end;
// remove input from predecessor units
InterpretationPtr newEdb(new Interpretation(*gp.edb));
newEdb->getStorage() -= unitInput->getStorage();
gp.edb = newEdb;
#ifndef NDEBUG
DBGLOG(DBG, "Program to be analyzed:" << std::endl << *gp.edb << std::endl << printManyToString<RawPrinter>(gp.idb, "\n", ctx.registry()));
#endif
NogoodSet instance;
// add input is pseudo-nogoods to make sure they are part of the problem
en = unitInput->getStorage().first();
en_end = unitInput->getStorage().end();
while (en < en_end) {
Nogood ng;
ng.insert(NogoodContainer::createLiteral(*en, true));
ng.insert(NogoodContainer::createLiteral(*en, false));
instance.addNogood(ng);
en++;
}
// interprete the ground program as a set of classical implications
if (!!gp.edb) {
en = gp.edb->getStorage().first();
en_end = gp.edb->getStorage().end();
while (en < en_end) {
Nogood ng;
ng.insert(NogoodContainer::createLiteral(*en, false));
instance.addNogood(ng);
// domain->setFact(*en);
en++;
}
}
BOOST_FOREACH (ID ruleID, gp.idb) {
const Rule& rule = ctx.registry()->rules.getByID(ruleID);
Nogood ng;
BOOST_FOREACH (ID h, rule.head) { ng.insert(NogoodContainer::createLiteral(h.address, false)); domain->setFact(h.address); }
BOOST_FOREACH (ID b, rule.body) { ng.insert(NogoodContainer::createLiteral(b.address, !b.isNaf())); domain->setFact(b.address); }
instance.addNogood(ng);
}
SATSolverPtr classicalSolver = SATSolver::getInstance(ctx, instance /*, domain*/);
// explanation atoms are all atoms from the domain which are not defined in the given program, i.e., which do not unify with a head atom in program
/*
InterpretationPtr explanationAtoms(new Interpretation(ctx.registry()));
en = domain->getStorage().first();
en_end = domain->getStorage().end();
while (en < en_end) {
const OrdinaryAtom& datom = ctx.registry()->ogatoms.getByAddress(*en);
bool definedInProgram = false;
BOOST_FOREACH (ID ruleID, program.idb) {
const Rule& rule = ctx.registry()->rules.getByID(ruleID);
BOOST_FOREACH (ID hatomID, rule.head) {
const OrdinaryAtom& hatom = ctx.registry()->lookupOrdinaryAtom(hatomID);
if (datom.unifiesWith(hatom)) {
definedInProgram = true;
break;
}
en++;
}
}
if (!definedInProgram) explanationAtoms->setFact(*en);
}
*/
DBGLOG(DBG, "Explanation atoms: " << *explAtoms);
// compute the classical models and an inconsistency reason
Nogood inconsistencyReason;
InterpretationPtr alreadyPos(new Interpretation(ctx.registry()));
InterpretationPtr alreadyNeg(new Interpretation(ctx.registry()));
InterpretationConstPtr model;
while ( (model = classicalSolver->getNextModel()) != InterpretationConstPtr() ) {
// compatibility check
bool verified = true;
for (int eaIndex = 0; eaIndex < innerEatoms.size() && verified; ++eaIndex){
BaseModelGenerator::VerifyExternalAtomCB vcb(model, ctx.registry()->eatoms.getByID(innerEatoms[eaIndex]), *(annotatedOptimizedProgram.getEAMask(eaIndex)));
mg->evaluateExternalAtom(ctx, innerEatoms[eaIndex], model, vcb, ctx.config.getOption("ExternalLearning") ? classicalSolver : NogoodContainerPtr());
verified &= vcb.verify();
}
if (verified) {
DBGLOG(DBG, "Got classical model: " << *model);
// add a literal "l" over some explanation atom "a", where the sign of "l" is the opposite of "a"'s sign in the model
en = explAtoms->getStorage().first();
en_end = explAtoms->getStorage().end();
while (en < en_end) {
// Use its negation in the inconsistency explanation; this will either:
// (i) prevent super sets of this model from becoming models of the program (namely if l="F a"; then adding "a" as fact will eliminate the model because "a" must be true); or
// (ii) ensure that there is a non-empty unfounded set (namely if l=T a); then *not* adding "a" as fact will leave "a" unfounded)
if (model->getFact(*en)) {
if (alreadyPos->getFact(*en)) { en++; continue; } // cannot use this literal because it needs to be added negatively but is already positive
if (alreadyNeg->getFact(*en)) break; // needs to be added negatively and is already negative --> done
DBGLOG(DBG, "Adding -" << printToString<RawPrinter>(ctx.registry()->ogatoms.getIDByAddress(*en), ctx.registry()) << " to reason nogood");
inconsistencyReason.insert(NogoodContainer::createLiteral(*en, false));
alreadyNeg->setFact(*en);
// eliminate all models with this literal
Nogood ng;
ng.insert(NogoodContainer::createLiteral(*en, true));
classicalSolver->addNogood(ng);
break;
}else{
if (alreadyNeg->getFact(*en)) { en++; continue; } // cannot use this literal because it needs to be added positively but is already negative
if (alreadyPos->getFact(*en)) break; // needs to be added positively and is already positive --> done
DBGLOG(DBG, "Adding " << printToString<RawPrinter>(ctx.registry()->ogatoms.getIDByAddress(*en), ctx.registry()) << " to reason nogood");
inconsistencyReason.insert(NogoodContainer::createLiteral(*en, true));
alreadyPos->setFact(*en);
// eliminate all models with this literal
Nogood ng;
ng.insert(NogoodContainer::createLiteral(*en, false));
classicalSolver->addNogood(ng);
break;
}
en++;
}
if (en == en_end) {
// could not find a reason
DBGLOG(DBG, "No inconsistency reason found");
*haveInconsistencyReason = false;
return Nogood();
}
}
}
DBGLOG(DBG, "Found inconsistency reason: " << inconsistencyReason.getStringRepresentation(ctx.registry()) << std::endl << "for program " << *gp.edb << std::endl << printManyToString<RawPrinter>(gp.idb, "\n", ctx.registry()) << std::endl << "wrt. explanation atoms " << *explAtoms);
*haveInconsistencyReason = true;
return inconsistencyReason;
}
DLVHEX_NAMESPACE_END
// vim:expandtab:ts=4:sw=4:
// mode: C++
// End:
<commit_msg>some fixes<commit_after>/* dlvhex -- Answer-Set Programming with external interfaces.
* Copyright (C) 2005-2007 Roman Schindlauer
* Copyright (C) 2006-2015 Thomas Krennwallner
* Copyright (C) 2009-2016 Peter Schüller
* Copyright (C) 2011-2016 Christoph Redl
* Copyright (C) 2015-2016 Tobias Kaminski
* Copyright (C) 2015-2016 Antonius Weinzierl
*
* This file is part of dlvhex.
*
* dlvhex 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.
*
* dlvhex 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 dlvhex; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA.
*/
/**
* @file InconsistencyAnalyzer.cpp
* @author Christoph Redl
* @date Wed April 20 2016
*
* @brief Computes a reason for the inconsistency in a program unit.
*
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "dlvhex2/BaseModelGenerator.h"
#include "dlvhex2/InconsistencyAnalyzer.h"
#include "dlvhex2/Printer.h"
#include "dlvhex2/ProgramCtx.h"
#include "dlvhex2/Benchmarking.h"
#include "dlvhex2/Benchmarking.h"
#include "dlvhex2/InternalGrounder.h"
#include "dlvhex2/SATSolver.h"
#include <boost/graph/breadth_first_search.hpp>
#include <boost/graph/visitors.hpp>
#include <boost/graph/strong_components.hpp>
#include <boost/graph/filtered_graph.hpp>
#include <boost/foreach.hpp>
DLVHEX_NAMESPACE_BEGIN
InconsistencyAnalyzer::InconsistencyAnalyzer(ProgramCtx& ctx) : ctx(ctx){
}
Nogood InconsistencyAnalyzer::getInconsistencyReason(BaseModelGenerator* mg, InterpretationConstPtr explAtoms, InterpretationConstPtr unitInput, std::vector<ID>& innerEatoms, OrdinaryASPProgram& program, AnnotatedGroundProgram& annotatedOptimizedProgram, bool* haveInconsistencyReason){
#ifndef NDEBUG
DBGLOG(DBG, "Performing inconsistency analyzis for program:" << std::endl << *program.edb << std::endl << printManyToString<RawPrinter>(program.idb, "\n", ctx.registry()));
#endif
// ground the program without optimization
InternalGrounder grounder(ctx, program, InternalGrounder::builtin);
OrdinaryASPProgram gp = grounder.getGroundProgram();
#ifndef NDEBUG
DBGLOG(DBG, "Unoptimized grounded program:" << std::endl << *gp.edb << std::endl << printManyToString<RawPrinter>(gp.idb, "\n", ctx.registry()));
#endif
// Construct domain of the SAT instance.
// It consists of all external atom input atoms and all ordinary atoms in the program (to be added below).
// It can be constructed by using the program mask of the previous (optimized) grounding and adding newly introduced atoms in the non-optimized grounding.
// All input atoms from predecessor components are already contained in the program mask of the optimized grounding.
InterpretationPtr domain(new Interpretation(*annotatedOptimizedProgram.getProgramMask()));
for (int eaIndex = 0; eaIndex < innerEatoms.size(); ++eaIndex) {
const ExternalAtom& eatom = ctx.registry()->eatoms.getByID(innerEatoms[eaIndex]);
eatom.updatePredicateInputMask();
domain->add(*(eatom.getPredicateInputMask()));
}
bm::bvector<>::enumerator en, en_end;
// remove input from predecessor units
InterpretationPtr newEdb(new Interpretation(*gp.edb));
newEdb->getStorage() -= unitInput->getStorage();
gp.edb = newEdb;
#ifndef NDEBUG
DBGLOG(DBG, "Program to be analyzed:" << std::endl << *gp.edb << std::endl << printManyToString<RawPrinter>(gp.idb, "\n", ctx.registry()));
#endif
NogoodSet instance;
// add input is pseudo-nogoods to make sure they are part of the problem
en = unitInput->getStorage().first();
en_end = unitInput->getStorage().end();
while (en < en_end) {
Nogood ng;
ng.insert(NogoodContainer::createLiteral(*en, true));
ng.insert(NogoodContainer::createLiteral(*en, false));
instance.addNogood(ng);
en++;
}
// interprete the ground program as a set of classical implications
if (!!gp.edb) {
en = gp.edb->getStorage().first();
en_end = gp.edb->getStorage().end();
while (en < en_end) {
Nogood ng;
ng.insert(NogoodContainer::createLiteral(*en, false));
instance.addNogood(ng);
// domain->setFact(*en);
en++;
}
}
BOOST_FOREACH (ID ruleID, gp.idb) {
const Rule& rule = ctx.registry()->rules.getByID(ruleID);
Nogood ng;
BOOST_FOREACH (ID h, rule.head) { ng.insert(NogoodContainer::createLiteral(h.address, false)); domain->setFact(h.address); }
BOOST_FOREACH (ID b, rule.body) { ng.insert(NogoodContainer::createLiteral(b.address, !b.isNaf())); domain->setFact(b.address); }
instance.addNogood(ng);
}
SATSolverPtr classicalSolver = SATSolver::getInstance(ctx, instance /*, domain*/);
// explanation atoms are all atoms from the domain which are not defined in the given program, i.e., which do not unify with a head atom in program
/*
InterpretationPtr explanationAtoms(new Interpretation(ctx.registry()));
en = domain->getStorage().first();
en_end = domain->getStorage().end();
while (en < en_end) {
const OrdinaryAtom& datom = ctx.registry()->ogatoms.getByAddress(*en);
bool definedInProgram = false;
BOOST_FOREACH (ID ruleID, program.idb) {
const Rule& rule = ctx.registry()->rules.getByID(ruleID);
BOOST_FOREACH (ID hatomID, rule.head) {
const OrdinaryAtom& hatom = ctx.registry()->lookupOrdinaryAtom(hatomID);
if (datom.unifiesWith(hatom)) {
definedInProgram = true;
break;
}
en++;
}
}
if (!definedInProgram) explanationAtoms->setFact(*en);
}
*/
DBGLOG(DBG, "Explanation atoms: " << *explAtoms);
// compute the classical models and an inconsistency reason
Nogood inconsistencyReason;
InterpretationPtr alreadyPos(new Interpretation(ctx.registry()));
InterpretationPtr alreadyNeg(new Interpretation(ctx.registry()));
InterpretationConstPtr model;
while ( (model = classicalSolver->getNextModel()) != InterpretationConstPtr() ) {
// compatibility check
bool verified = true;
for (int eaIndex = 0; eaIndex < innerEatoms.size() && verified; ++eaIndex){
BaseModelGenerator::VerifyExternalAtomCB vcb(model, ctx.registry()->eatoms.getByID(innerEatoms[eaIndex]), *(annotatedOptimizedProgram.getEAMask(eaIndex)));
mg->evaluateExternalAtom(ctx, innerEatoms[eaIndex], model, vcb, ctx.config.getOption("ExternalLearning") ? classicalSolver : NogoodContainerPtr());
verified &= vcb.verify();
}
if (verified) {
DBGLOG(DBG, "Got classical model: " << *model);
// add a literal "l" over some explanation atom "a", where the sign of "l" is the opposite of "a"'s sign in the model
en = explAtoms->getStorage().first();
en_end = explAtoms->getStorage().end();
while (en < en_end) {
// we want an inconsistency reason which is currently violated
if (unitInput->getFact(*en) != model->getFact(*en)) { en++; continue; }
// Use its negation in the inconsistency explanation; this will either:
// (i) prevent super sets of this model from becoming models of the program (namely if l="F a"; then adding "a" as fact will eliminate the model because "a" must be true); or
// (ii) ensure that there is a non-empty unfounded set (namely if l=T a); then *not* adding "a" as fact will leave "a" unfounded)
if (model->getFact(*en)) {
if (alreadyPos->getFact(*en)) { en++; continue; } // cannot use this literal because it needs to be added negatively but is already positive
if (alreadyNeg->getFact(*en)) break; // needs to be added negatively and is already negative --> done
DBGLOG(DBG, "Adding -" << printToString<RawPrinter>(ctx.registry()->ogatoms.getIDByAddress(*en), ctx.registry()) << " to reason nogood");
inconsistencyReason.insert(NogoodContainer::createLiteral(*en, false));
alreadyNeg->setFact(*en);
// eliminate all models with this literal
if (annotatedOptimizedProgram.getProgramMask()->getFact(*en)){
Nogood ng;
ng.insert(NogoodContainer::createLiteral(*en, true));
DBGLOG(DBG, "Adding nogood " << ng.getStringRepresentation(ctx.registry()) << " to solver");
classicalSolver->addNogood(ng);
}
break;
}else{
if (alreadyNeg->getFact(*en)) { en++; continue; } // cannot use this literal because it needs to be added positively but is already negative
if (alreadyPos->getFact(*en)) break; // needs to be added positively and is already positive --> done
DBGLOG(DBG, "Adding " << printToString<RawPrinter>(ctx.registry()->ogatoms.getIDByAddress(*en), ctx.registry()) << " to reason nogood");
inconsistencyReason.insert(NogoodContainer::createLiteral(*en, true));
alreadyPos->setFact(*en);
// eliminate all models with this literal
if (annotatedOptimizedProgram.getProgramMask()->getFact(*en)){
Nogood ng;
ng.insert(NogoodContainer::createLiteral(*en, false));
DBGLOG(DBG, "Adding nogood " << ng.getStringRepresentation(ctx.registry()) << " to solver");
classicalSolver->addNogood(ng);
}
break;
}
en++;
}
if (en == en_end) {
// could not find a reason
DBGLOG(DBG, "No inconsistency reason found");
*haveInconsistencyReason = false;
return Nogood();
}
}
}
DBGLOG(DBG, "Found inconsistency reason: " << inconsistencyReason.getStringRepresentation(ctx.registry()) << std::endl << "for program " << *gp.edb << std::endl << printManyToString<RawPrinter>(gp.idb, "\n", ctx.registry()) << std::endl << "wrt. explanation atoms " << *explAtoms);
*haveInconsistencyReason = true;
return inconsistencyReason;
}
DLVHEX_NAMESPACE_END
// vim:expandtab:ts=4:sw=4:
// mode: C++
// End:
<|endoftext|>
|
<commit_before>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
// STL includes
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <istream>
#include <iterator>
// MOOSE includes
#include "MooseError.h"
#include "MaterialProperty.h"
// External includes
#include "pcrecpp.h"
namespace MooseUtils
{
void
tokenize(const std::string &str, std::vector<std::string> &elements, unsigned int min_len, const std::string &delims)
{
elements.clear();
std::string::size_type last_pos = str.find_first_not_of(delims, 0);
std::string::size_type pos = str.find_first_of(delims, std::min(last_pos + min_len, str.size()));
while (last_pos != std::string::npos)
{
elements.push_back(str.substr(last_pos, pos - last_pos));
// skip delims between tokens
last_pos = str.find_first_not_of(delims, pos);
if (last_pos == std::string::npos) break;
pos = str.find_first_of(delims, std::min(last_pos + min_len, str.size()));
}
}
void
escape(std::string &str)
{
std::map<char, std::string> escapes;
escapes['\a'] = "\\a";
escapes['\b'] = "\\b";
escapes['\f'] = "\\f";
escapes['\n'] = "\\n";
escapes['\t'] = "\\t";
escapes['\v'] = "\\v";
escapes['\r'] = "\\r";
for (std::map<char, std::string>::iterator it = escapes.begin(); it != escapes.end(); ++it)
for (size_t pos=0; (pos=str.find(it->first, pos)) != std::string::npos; pos+=it->second.size())
str.replace(pos, 1, it->second);
}
std::string
trim(std::string str, const std::string &white_space)
{
std::string r = str.erase(str.find_last_not_of(white_space)+1);
return r.erase(0,r.find_first_not_of(white_space));
}
bool pathContains(const std::string &expression,
const std::string &string_to_find,
const std::string &delims)
{
std::vector<std::string> elements;
tokenize(expression, elements, 0, delims);
std::vector<std::string>::iterator found_it = std::find(elements.begin(), elements.end(), string_to_find);
if (found_it != elements.end())
return true;
else
return false;
}
bool
checkFileReadable(const std::string & filename, bool check_line_endings, bool throw_on_unreadable)
{
std::ifstream in(filename.c_str(), std::ifstream::in);
if (in.fail())
{
if (throw_on_unreadable)
mooseError((std::string("Unable to open file \"") + filename
+ std::string("\". Check to make sure that it exists and that you have read permission.")).c_str());
else
return false;
}
if (check_line_endings)
{
std::istream_iterator<char> iter(in);
std::istream_iterator<char> eos;
in >> std::noskipws;
while (iter != eos)
if (*iter++ == '\r')
mooseError(filename + " contains Windows(DOS) line endings which are not supported.");
}
in.close();
return true;
}
bool
checkFileWriteable(const std::string & filename, bool throw_on_unwritable)
{
std::ofstream out(filename.c_str(), std::ofstream::out);
if (out.fail())
{
if (throw_on_unwritable)
mooseError((std::string("Unable to open file \"") + filename
+ std::string("\". Check to make sure that it exists and that you have write permission.")).c_str());
else
return false;
}
out.close();
return true;
}
void
parallelBarrierNotify(const Parallel::Communicator & comm)
{
processor_id_type slave_processor_id;
if (comm.rank() == 0)
{
// The master process is already through, so report it
Moose::out << "Jobs complete: 1/" << comm.size() << (1 == comm.size() ? "\n" : "\r") << std::flush;
for (unsigned int i=2; i<=comm.size(); ++i)
{
comm.receive(MPI_ANY_SOURCE, slave_processor_id);
Moose::out << "Jobs complete: " << i << "/" << comm.size() << (i == comm.size() ? "\n" : "\r") << std::flush;
}
}
else
{
slave_processor_id = comm.rank();
comm.send(0, slave_processor_id);
}
comm.barrier();
}
bool
hasExtension(const std::string & filename, std::string ext, bool strip_exodus_ext)
{
// Extract the extension, w/o the '.'
std::string file_ext;
if (strip_exodus_ext)
{
pcrecpp::RE re(".*\\.([^\\.]*?)(?:-s\\d+)?\\s*$"); // capture the complete extension, ignoring -s*
re.FullMatch(filename, &file_ext);
}
else
{
pcrecpp::RE re(".*\\.([^\\.]*?)\\s*$"); // capture the complete extension
re.FullMatch(filename, &file_ext);
}
// Perform the comparision
if (file_ext == ext)
return true;
else
return false;
}
std::pair<std::string, std::string>
splitFileName(std::string full_file)
{
// Error if path ends with /
if (full_file[full_file.size()-1] == '/')
mooseError("Invalid full file name: " << full_file);
// Define the variables to output
std::string path;
std::string file;
// Locate the / sepearting the file from path
std::size_t found = full_file.find_last_of("/");
// If no / is found used "." for the path, otherwise seperate the two
if (found == std::string::npos)
{
path = ".";
file = full_file;
}
else
{
path = full_file.substr(0, found);
file = full_file.substr(found+1);
}
// Return the path and file as a pair
return std::pair<std::string, std::string>(path, file);
}
std::string
camelCaseToUnderscore(const std::string & camel_case_name)
{
string replaced = camel_case_name;
// Put underscores in front of each contiguous set of capital letters
pcrecpp::RE("(?!^)([A-Z]+)").GlobalReplace("_\\1", &replaced);
// Convert all capital letters to lower case
std::transform(replaced.begin(), replaced.end(), replaced.begin(), ::tolower);
return replaced;
}
std::string
underscoreToCamelCase(const std::string & underscore_name, bool leading_upper_case)
{
pcrecpp::StringPiece input(underscore_name);
pcrecpp::RE re("([^_]*)(_|$)");
std::string result;
std::string us, not_us;
bool make_upper = leading_upper_case;
while (re.Consume(&input, ¬_us, &us))
{
if (not_us.length() > 0)
{
if (make_upper)
{
result += std::toupper(not_us[0]);
if (not_us.length() > 1)
result += not_us.substr(1);
}
else
result += not_us;
}
if (us == "")
break;
// Toggle flag so next match is upper cased
make_upper = true;
}
return result;
}
std::string
shortName(const std::string & name)
{
return name.substr(name.find_last_of('/') != std::string::npos ? name.find_last_of('/') + 1 : 0);
}
bool
absoluteFuzzyEqual(const Real & var1, const Real & var2, const Real & tol)
{
return (std::abs(var1 - var2) < tol);
}
bool
absoluteFuzzyGreaterEqual(const Real & var1, const Real & var2, const Real & tol)
{
return (var1 > (var2 - tol));
}
bool
absoluteFuzzyGreaterThan(const Real & var1, const Real & var2, const Real & tol)
{
return (var1 > (var2 + tol));
}
bool
absoluteFuzzyLessEqual(const Real & var1, const Real & var2, const Real & tol)
{
return (var1 < (var2 + tol));
}
bool
absoluteFuzzyLessThan(const Real & var1, const Real & var2, const Real & tol)
{
return (var1 < (var2 - tol));
}
bool
relativeFuzzyEqual(const Real & var1, const Real & var2, const Real & tol)
{
return (absoluteFuzzyEqual(var1, var2, tol*(std::abs(var1)+std::abs(var2))));
}
bool
relativeFuzzyGreaterEqual(const Real & var1, const Real & var2, const Real & tol)
{
return (absoluteFuzzyGreaterEqual(var1, var2, tol*(std::abs(var1)+std::abs(var2))));
}
bool
relativeFuzzyGreaterThan(const Real & var1, const Real & var2, const Real & tol)
{
return (absoluteFuzzyGreaterThan(var1, var2, tol*(std::abs(var1)+std::abs(var2))));
}
bool
relativeFuzzyLessEqual(const Real & var1, const Real & var2, const Real & tol)
{
return (absoluteFuzzyLessEqual(var1, var2, tol*(std::abs(var1)+std::abs(var2))));
}
bool
relativeFuzzyLessThan(const Real & var1, const Real & var2, const Real & tol)
{
return (absoluteFuzzyLessThan(var1, var2, tol*(std::abs(var1)+std::abs(var2))));
}
void
MaterialPropertyStorageDump(const HashMap<const libMesh::Elem *, HashMap<unsigned int, MaterialProperties> > & props)
{
// Define the iterators
HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> >::const_iterator elem_it;
HashMap<unsigned int, MaterialProperties>::const_iterator side_it;
MaterialProperties::const_iterator prop_it;
// Loop through the elements
for (elem_it = props.begin(); elem_it != props.end(); ++elem_it)
{
Moose::out << "Element " << elem_it->first->id() << '\n';
// Loop through the sides
for (side_it = elem_it->second.begin(); side_it != elem_it->second.end(); ++side_it)
{
Moose::out << " Side " << side_it->first << '\n';
// Loop over properties
unsigned int cnt = 0;
for (prop_it = side_it->second.begin(); prop_it != side_it->second.end(); ++prop_it)
{
MaterialProperty<Real> * mp = dynamic_cast<MaterialProperty<Real> *>(*prop_it);
if (mp)
{
Moose::out << " Property " << cnt << '\n';
cnt++;
// Loop over quadrature points
for (unsigned int qp = 0; qp < mp->size(); ++qp)
Moose::out << " prop[" << qp << "] = " << (*mp)[qp] << '\n';
}
}
}
}
}
} // MooseUtils namespace
<commit_msg>Fix fuzzy functions closes #5408<commit_after>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
// STL includes
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <istream>
#include <iterator>
// MOOSE includes
#include "MooseError.h"
#include "MaterialProperty.h"
// External includes
#include "pcrecpp.h"
namespace MooseUtils
{
void
tokenize(const std::string &str, std::vector<std::string> &elements, unsigned int min_len, const std::string &delims)
{
elements.clear();
std::string::size_type last_pos = str.find_first_not_of(delims, 0);
std::string::size_type pos = str.find_first_of(delims, std::min(last_pos + min_len, str.size()));
while (last_pos != std::string::npos)
{
elements.push_back(str.substr(last_pos, pos - last_pos));
// skip delims between tokens
last_pos = str.find_first_not_of(delims, pos);
if (last_pos == std::string::npos) break;
pos = str.find_first_of(delims, std::min(last_pos + min_len, str.size()));
}
}
void
escape(std::string &str)
{
std::map<char, std::string> escapes;
escapes['\a'] = "\\a";
escapes['\b'] = "\\b";
escapes['\f'] = "\\f";
escapes['\n'] = "\\n";
escapes['\t'] = "\\t";
escapes['\v'] = "\\v";
escapes['\r'] = "\\r";
for (std::map<char, std::string>::iterator it = escapes.begin(); it != escapes.end(); ++it)
for (size_t pos=0; (pos=str.find(it->first, pos)) != std::string::npos; pos+=it->second.size())
str.replace(pos, 1, it->second);
}
std::string
trim(std::string str, const std::string &white_space)
{
std::string r = str.erase(str.find_last_not_of(white_space)+1);
return r.erase(0,r.find_first_not_of(white_space));
}
bool pathContains(const std::string &expression,
const std::string &string_to_find,
const std::string &delims)
{
std::vector<std::string> elements;
tokenize(expression, elements, 0, delims);
std::vector<std::string>::iterator found_it = std::find(elements.begin(), elements.end(), string_to_find);
if (found_it != elements.end())
return true;
else
return false;
}
bool
checkFileReadable(const std::string & filename, bool check_line_endings, bool throw_on_unreadable)
{
std::ifstream in(filename.c_str(), std::ifstream::in);
if (in.fail())
{
if (throw_on_unreadable)
mooseError((std::string("Unable to open file \"") + filename
+ std::string("\". Check to make sure that it exists and that you have read permission.")).c_str());
else
return false;
}
if (check_line_endings)
{
std::istream_iterator<char> iter(in);
std::istream_iterator<char> eos;
in >> std::noskipws;
while (iter != eos)
if (*iter++ == '\r')
mooseError(filename + " contains Windows(DOS) line endings which are not supported.");
}
in.close();
return true;
}
bool
checkFileWriteable(const std::string & filename, bool throw_on_unwritable)
{
std::ofstream out(filename.c_str(), std::ofstream::out);
if (out.fail())
{
if (throw_on_unwritable)
mooseError((std::string("Unable to open file \"") + filename
+ std::string("\". Check to make sure that it exists and that you have write permission.")).c_str());
else
return false;
}
out.close();
return true;
}
void
parallelBarrierNotify(const Parallel::Communicator & comm)
{
processor_id_type slave_processor_id;
if (comm.rank() == 0)
{
// The master process is already through, so report it
Moose::out << "Jobs complete: 1/" << comm.size() << (1 == comm.size() ? "\n" : "\r") << std::flush;
for (unsigned int i=2; i<=comm.size(); ++i)
{
comm.receive(MPI_ANY_SOURCE, slave_processor_id);
Moose::out << "Jobs complete: " << i << "/" << comm.size() << (i == comm.size() ? "\n" : "\r") << std::flush;
}
}
else
{
slave_processor_id = comm.rank();
comm.send(0, slave_processor_id);
}
comm.barrier();
}
bool
hasExtension(const std::string & filename, std::string ext, bool strip_exodus_ext)
{
// Extract the extension, w/o the '.'
std::string file_ext;
if (strip_exodus_ext)
{
pcrecpp::RE re(".*\\.([^\\.]*?)(?:-s\\d+)?\\s*$"); // capture the complete extension, ignoring -s*
re.FullMatch(filename, &file_ext);
}
else
{
pcrecpp::RE re(".*\\.([^\\.]*?)\\s*$"); // capture the complete extension
re.FullMatch(filename, &file_ext);
}
// Perform the comparision
if (file_ext == ext)
return true;
else
return false;
}
std::pair<std::string, std::string>
splitFileName(std::string full_file)
{
// Error if path ends with /
if (full_file[full_file.size()-1] == '/')
mooseError("Invalid full file name: " << full_file);
// Define the variables to output
std::string path;
std::string file;
// Locate the / sepearting the file from path
std::size_t found = full_file.find_last_of("/");
// If no / is found used "." for the path, otherwise seperate the two
if (found == std::string::npos)
{
path = ".";
file = full_file;
}
else
{
path = full_file.substr(0, found);
file = full_file.substr(found+1);
}
// Return the path and file as a pair
return std::pair<std::string, std::string>(path, file);
}
std::string
camelCaseToUnderscore(const std::string & camel_case_name)
{
string replaced = camel_case_name;
// Put underscores in front of each contiguous set of capital letters
pcrecpp::RE("(?!^)([A-Z]+)").GlobalReplace("_\\1", &replaced);
// Convert all capital letters to lower case
std::transform(replaced.begin(), replaced.end(), replaced.begin(), ::tolower);
return replaced;
}
std::string
underscoreToCamelCase(const std::string & underscore_name, bool leading_upper_case)
{
pcrecpp::StringPiece input(underscore_name);
pcrecpp::RE re("([^_]*)(_|$)");
std::string result;
std::string us, not_us;
bool make_upper = leading_upper_case;
while (re.Consume(&input, ¬_us, &us))
{
if (not_us.length() > 0)
{
if (make_upper)
{
result += std::toupper(not_us[0]);
if (not_us.length() > 1)
result += not_us.substr(1);
}
else
result += not_us;
}
if (us == "")
break;
// Toggle flag so next match is upper cased
make_upper = true;
}
return result;
}
std::string
shortName(const std::string & name)
{
return name.substr(name.find_last_of('/') != std::string::npos ? name.find_last_of('/') + 1 : 0);
}
bool
absoluteFuzzyEqual(const Real & var1, const Real & var2, const Real & tol)
{
return (std::abs(var1 - var2) < tol);
}
bool
absoluteFuzzyGreaterEqual(const Real & var1, const Real & var2, const Real & tol)
{
return (var1 >= (var2 - tol));
}
bool
absoluteFuzzyGreaterThan(const Real & var1, const Real & var2, const Real & tol)
{
return (var1 > (var2 + tol));
}
bool
absoluteFuzzyLessEqual(const Real & var1, const Real & var2, const Real & tol)
{
return (var1 <= (var2 + tol));
}
bool
absoluteFuzzyLessThan(const Real & var1, const Real & var2, const Real & tol)
{
return (var1 < (var2 - tol));
}
bool
relativeFuzzyEqual(const Real & var1, const Real & var2, const Real & tol)
{
return (absoluteFuzzyEqual(var1, var2, tol*(std::abs(var1)+std::abs(var2))));
}
bool
relativeFuzzyGreaterEqual(const Real & var1, const Real & var2, const Real & tol)
{
return (absoluteFuzzyGreaterEqual(var1, var2, tol*(std::abs(var1)+std::abs(var2))));
}
bool
relativeFuzzyGreaterThan(const Real & var1, const Real & var2, const Real & tol)
{
return (absoluteFuzzyGreaterThan(var1, var2, tol*(std::abs(var1)+std::abs(var2))));
}
bool
relativeFuzzyLessEqual(const Real & var1, const Real & var2, const Real & tol)
{
return (absoluteFuzzyLessEqual(var1, var2, tol*(std::abs(var1)+std::abs(var2))));
}
bool
relativeFuzzyLessThan(const Real & var1, const Real & var2, const Real & tol)
{
return (absoluteFuzzyLessThan(var1, var2, tol*(std::abs(var1)+std::abs(var2))));
}
void
MaterialPropertyStorageDump(const HashMap<const libMesh::Elem *, HashMap<unsigned int, MaterialProperties> > & props)
{
// Define the iterators
HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> >::const_iterator elem_it;
HashMap<unsigned int, MaterialProperties>::const_iterator side_it;
MaterialProperties::const_iterator prop_it;
// Loop through the elements
for (elem_it = props.begin(); elem_it != props.end(); ++elem_it)
{
Moose::out << "Element " << elem_it->first->id() << '\n';
// Loop through the sides
for (side_it = elem_it->second.begin(); side_it != elem_it->second.end(); ++side_it)
{
Moose::out << " Side " << side_it->first << '\n';
// Loop over properties
unsigned int cnt = 0;
for (prop_it = side_it->second.begin(); prop_it != side_it->second.end(); ++prop_it)
{
MaterialProperty<Real> * mp = dynamic_cast<MaterialProperty<Real> *>(*prop_it);
if (mp)
{
Moose::out << " Property " << cnt << '\n';
cnt++;
// Loop over quadrature points
for (unsigned int qp = 0; qp < mp->size(); ++qp)
Moose::out << " prop[" << qp << "] = " << (*mp)[qp] << '\n';
}
}
}
}
}
} // MooseUtils namespace
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <cstring>
using namespace std;
void isPalin(const char *str) {
int n = strlen(str);
bool P[n][n];
int i, j, L; // 表示字串的长度
// 长度为1的都是回文
for (i = 0; i < n; i++) {
P[i][i] = true;
}
// 长度可能从2开始
for (L = 2; L <= n; L++) {
for (i = 0; i < n - L + 1; i++) {
j = i + L - 1; // 设置结束的位置
if (L == 2) // 长度为2的情况
P[i][j] = (str[i] == str[j]);
else //其他情况
P[i][j] = (str[i] == str[j]) && P[i + 1][j - 1];
}
}
int maxi = 0, maxj = 0, maxlen = 0;
for (i = 0; i < n; i++) {
for (j = i; j < n; j++) {
if (P[i][j] && maxlen < j - i + 1) {
maxi = i;
maxj = j;
maxlen = j - i + 1;
}
}
}
printf("The longest palin substr is ");
for(i = maxi; i <= maxj; i++) {
printf("%c", str[i]);
}
printf(", maxlen is %d\n\n", maxlen);
cout << string(str + maxi, maxlen) << endl;
return;
}
int main() {
//isPalin("abccba");
isPalin(string("abccba").c_str());
}
<commit_msg>add time space description<commit_after>#include <iostream>
#include <string>
#include <cstring>
using namespace std;
// Manacher算法,时间复杂度O(n), 空间复杂度O(n)
// DP: Time O(n^2) Space O(n^2)
void isPalin(const char *str) {
int n = strlen(str);
bool P[n][n];
int i, j, L; // 表示字串的长度
// 长度为1的都是回文
for (i = 0; i < n; i++) {
P[i][i] = true;
}
// 长度可能从2开始
for (L = 2; L <= n; L++) {
for (i = 0; i < n - L + 1; i++) {
j = i + L - 1; // 设置结束的位置
if (L == 2) // 长度为2的情况
P[i][j] = (str[i] == str[j]);
else //其他情况
P[i][j] = (str[i] == str[j]) && P[i + 1][j - 1];
}
}
int maxi = 0, maxj = 0, maxlen = 0;
for (i = 0; i < n; i++) {
for (j = i; j < n; j++) {
if (P[i][j] && maxlen < j - i + 1) {
maxi = i;
maxj = j;
maxlen = j - i + 1;
}
}
}
printf("The longest palin substr is ");
for(i = maxi; i <= maxj; i++) {
printf("%c", str[i]);
}
printf(", maxlen is %d\n\n", maxlen);
cout << string(str + maxi, maxlen) << endl;
return;
}
int main() {
//isPalin("abccba");
isPalin(string("abccba").c_str());
}
<|endoftext|>
|
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2008 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 "OGLImagingContext.h"
#include "../base/Exception.h"
#include <assert.h>
#include <iostream>
namespace avg {
using namespace std;
#ifdef _WIN32
LONG WINAPI imagingWindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
return DefWindowProc(hwnd, msg, wParam, lParam);
}
void registerWindowClass()
{
static char * pClassName;
if (pClassName) {
return;
}
pClassName = "GLUT";
HINSTANCE hInstance = GetModuleHandle(NULL);
WNDCLASS wc;
memset(&wc, 0, sizeof(WNDCLASS));
wc.style = CS_OWNDC;
wc.lpfnWndProc = (WNDPROC)imagingWindowProc;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
wc.hCursor = LoadCursor(hInstance, IDC_ARROW);
wc.hbrBackground = NULL;
wc.lpszMenuName = NULL;
wc.lpszClassName = pClassName;
BOOL bOK = RegisterClass(&wc);
assert(bOK);
}
#endif
OGLImagingContext::OGLImagingContext(const IntPoint & size)
{
#ifdef __APPLE__
GLint attributes[] = {AGL_RGBA, AGL_ALL_RENDERERS,AGL_NONE};
AGLPixelFormat format;
format = aglChoosePixelFormat(NULL, 0, attributes);
assert(format);
m_Context = aglCreateContext(format, NULL);
assert(m_Context);
aglDestroyPixelFormat(format);
bool bOk = aglSetCurrentContext(m_Context);
assert (bOk);
#else
#ifdef linux
Display *dpy;
dpy = XOpenDisplay(0);
XVisualInfo *vi;
static int attributes[] = {GLX_RGBA, 0};
vi = glXChooseVisual(dpy, DefaultScreen(dpy), attributes);
m_Context = glXCreateContext(dpy, vi, 0, GL_TRUE);
assert(m_Context);
Pixmap pmp = XCreatePixmap(dpy, RootWindow(dpy, vi->screen),
8, 8, vi->depth);
GLXPixmap pixmap = glXCreateGLXPixmap(dpy, vi, pmp);
glXMakeCurrent(dpy, pixmap, m_Context);
#else
#ifdef _WIN32
registerWindowClass();
m_hwnd = CreateWindow("GLUT", "GLUT",
WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
0, 0, 500, 300, 0, 0, GetModuleHandle(NULL), 0);
winOGLErrorCheck(m_hDC != 0, "CreateWindow");
m_hDC = GetDC(m_hwnd);
winOGLErrorCheck(m_hDC != 0, "GetDC");
PIXELFORMATDESCRIPTOR pfd;
ZeroMemory(&pfd, sizeof(pfd));
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cDepthBits = 32;
pfd.iLayerType = PFD_MAIN_PLANE;
int iFormat = ChoosePixelFormat(m_hDC, &pfd);
winOGLErrorCheck(iFormat != 0, "ChoosePixelFormat");
SetPixelFormat(m_hDC, iFormat, &pfd);
m_Context = wglCreateContext(m_hDC);
winOGLErrorCheck(m_Context != 0, "wglCreateContext");
BOOL bOK = wglMakeCurrent(m_hDC, m_Context);
winOGLErrorCheck(bOK, "wglMakeCurrent");
#endif
#endif
#endif
glproc::init();
if (!isSupported()) {
throw Exception(AVG_ERR_VIDEO_GENERAL,
"GPU imaging not supported by current OpenGL configuration.");
}
// Coordinates
setSize(size);
// Shading etc.
glDisable(GL_BLEND);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glDisable(GL_BLEND)");
glShadeModel(GL_FLAT);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glShadeModel(GL_FLAT)");
glDisable(GL_DEPTH_TEST);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glDisable(GL_DEPTH_TEST)");
glDisable(GL_STENCIL_TEST);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glDisable(GL_STENCIL_TEST)");
// Texturing
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glTexEnvf()");
glBlendFunc(GL_ONE, GL_ZERO);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glBlendFunc()");
glEnable(GL_TEXTURE_RECTANGLE_ARB);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glEnable(GL_TEXTURE_RECTANGLE_ARB);");
glDisable(GL_MULTISAMPLE);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glDisable(GL_MULTISAMPLE);");
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
}
OGLImagingContext::~OGLImagingContext()
{
#ifdef __APPLE__
if (m_Context) {
aglSetCurrentContext(0);
aglDestroyContext(m_Context);
m_Context = 0;
}
#endif
#ifdef _WIN32
if (m_Context) {
wglDeleteContext(m_Context);
DeleteDC(m_hDC);
DestroyWindow(m_hwnd);
}
#endif
}
void OGLImagingContext::activate()
{
#ifdef __APPLE__
bool bOk = aglSetCurrentContext(m_Context);
assert(bOk);
#else
#endif
#ifdef _WIN32
wglDeleteContext( m_Context );
#endif
}
void OGLImagingContext::setSize(const IntPoint& size)
{
m_Size = size;
glViewport(0, 0, m_Size.x, m_Size.y);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glViewport()");
glMatrixMode(GL_PROJECTION);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glMatrixMode()");
glLoadIdentity();
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glLoadIdentity()");
gluOrtho2D(0, m_Size.x, m_Size.y, 0);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "gluOrtho2D()");
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glLoadIdentity()");
}
bool OGLImagingContext::isSupported()
{
int glMajorVer;
int glMinorVer;
int slMajorVer;
int slMinorVer;
getGLVersion(glMajorVer, glMinorVer);
getGLShadingLanguageVersion(slMajorVer, slMinorVer);
// Not sure if we need shader version 1.2 as well - we'll see.
return (glMajorVer > 1 && queryOGLExtension("GL_ARB_texture_rectangle") &&
queryOGLExtension("GL_ARB_pixel_buffer_object") &&
queryOGLExtension("GL_EXT_framebuffer_object"));
}
}
<commit_msg>Error instead of segfault in testgpu if X display is not available.<commit_after>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2008 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 "OGLImagingContext.h"
#include "../base/Exception.h"
#include <assert.h>
#include <iostream>
namespace avg {
using namespace std;
#ifdef _WIN32
LONG WINAPI imagingWindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
return DefWindowProc(hwnd, msg, wParam, lParam);
}
void registerWindowClass()
{
static char * pClassName;
if (pClassName) {
return;
}
pClassName = "GLUT";
HINSTANCE hInstance = GetModuleHandle(NULL);
WNDCLASS wc;
memset(&wc, 0, sizeof(WNDCLASS));
wc.style = CS_OWNDC;
wc.lpfnWndProc = (WNDPROC)imagingWindowProc;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
wc.hCursor = LoadCursor(hInstance, IDC_ARROW);
wc.hbrBackground = NULL;
wc.lpszMenuName = NULL;
wc.lpszClassName = pClassName;
BOOL bOK = RegisterClass(&wc);
assert(bOK);
}
#endif
OGLImagingContext::OGLImagingContext(const IntPoint & size)
{
#ifdef __APPLE__
GLint attributes[] = {AGL_RGBA, AGL_ALL_RENDERERS,AGL_NONE};
AGLPixelFormat format;
format = aglChoosePixelFormat(NULL, 0, attributes);
assert(format);
m_Context = aglCreateContext(format, NULL);
assert(m_Context);
aglDestroyPixelFormat(format);
bool bOk = aglSetCurrentContext(m_Context);
assert (bOk);
#else
#ifdef linux
Display *dpy;
dpy = XOpenDisplay(0);
if (!dpy) {
throw Exception(AVG_ERR_VIDEO_GENERAL, "No X windows display available.");
}
XVisualInfo *vi;
static int attributes[] = {GLX_RGBA, 0};
vi = glXChooseVisual(dpy, DefaultScreen(dpy), attributes);
m_Context = glXCreateContext(dpy, vi, 0, GL_TRUE);
assert(m_Context);
Pixmap pmp = XCreatePixmap(dpy, RootWindow(dpy, vi->screen),
8, 8, vi->depth);
GLXPixmap pixmap = glXCreateGLXPixmap(dpy, vi, pmp);
glXMakeCurrent(dpy, pixmap, m_Context);
#else
#ifdef _WIN32
registerWindowClass();
m_hwnd = CreateWindow("GLUT", "GLUT",
WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
0, 0, 500, 300, 0, 0, GetModuleHandle(NULL), 0);
winOGLErrorCheck(m_hDC != 0, "CreateWindow");
m_hDC = GetDC(m_hwnd);
winOGLErrorCheck(m_hDC != 0, "GetDC");
PIXELFORMATDESCRIPTOR pfd;
ZeroMemory(&pfd, sizeof(pfd));
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cDepthBits = 32;
pfd.iLayerType = PFD_MAIN_PLANE;
int iFormat = ChoosePixelFormat(m_hDC, &pfd);
winOGLErrorCheck(iFormat != 0, "ChoosePixelFormat");
SetPixelFormat(m_hDC, iFormat, &pfd);
m_Context = wglCreateContext(m_hDC);
winOGLErrorCheck(m_Context != 0, "wglCreateContext");
BOOL bOK = wglMakeCurrent(m_hDC, m_Context);
winOGLErrorCheck(bOK, "wglMakeCurrent");
#endif
#endif
#endif
glproc::init();
if (!isSupported()) {
throw Exception(AVG_ERR_VIDEO_GENERAL,
"GPU imaging not supported by current OpenGL configuration.");
}
// Coordinates
setSize(size);
// Shading etc.
glDisable(GL_BLEND);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glDisable(GL_BLEND)");
glShadeModel(GL_FLAT);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glShadeModel(GL_FLAT)");
glDisable(GL_DEPTH_TEST);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glDisable(GL_DEPTH_TEST)");
glDisable(GL_STENCIL_TEST);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glDisable(GL_STENCIL_TEST)");
// Texturing
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glTexEnvf()");
glBlendFunc(GL_ONE, GL_ZERO);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glBlendFunc()");
glEnable(GL_TEXTURE_RECTANGLE_ARB);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glEnable(GL_TEXTURE_RECTANGLE_ARB);");
glDisable(GL_MULTISAMPLE);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glDisable(GL_MULTISAMPLE);");
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
}
OGLImagingContext::~OGLImagingContext()
{
#ifdef __APPLE__
if (m_Context) {
aglSetCurrentContext(0);
aglDestroyContext(m_Context);
m_Context = 0;
}
#endif
#ifdef _WIN32
if (m_Context) {
wglDeleteContext(m_Context);
DeleteDC(m_hDC);
DestroyWindow(m_hwnd);
}
#endif
}
void OGLImagingContext::activate()
{
#ifdef __APPLE__
bool bOk = aglSetCurrentContext(m_Context);
assert(bOk);
#else
#endif
#ifdef _WIN32
wglDeleteContext( m_Context );
#endif
}
void OGLImagingContext::setSize(const IntPoint& size)
{
m_Size = size;
glViewport(0, 0, m_Size.x, m_Size.y);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glViewport()");
glMatrixMode(GL_PROJECTION);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glMatrixMode()");
glLoadIdentity();
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glLoadIdentity()");
gluOrtho2D(0, m_Size.x, m_Size.y, 0);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "gluOrtho2D()");
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "glLoadIdentity()");
}
bool OGLImagingContext::isSupported()
{
int glMajorVer;
int glMinorVer;
int slMajorVer;
int slMinorVer;
getGLVersion(glMajorVer, glMinorVer);
getGLShadingLanguageVersion(slMajorVer, slMinorVer);
// Not sure if we need shader version 1.2 as well - we'll see.
return (glMajorVer > 1 && queryOGLExtension("GL_ARB_texture_rectangle") &&
queryOGLExtension("GL_ARB_pixel_buffer_object") &&
queryOGLExtension("GL_EXT_framebuffer_object"));
}
}
<|endoftext|>
|
<commit_before>#include "tabs/image-preview.h"
#include <QDir>
#include <QEventLoop>
#include <QFile>
#include <QFileDialog>
#include <QLabel>
#include <QMenu>
#include <QMovie>
#include <QRandomGenerator>
#include <QSettings>
#include <QtMath>
#include <QUrl>
#include <QVBoxLayout>
#include <QWidget>
#include "downloader/download-queue.h"
#include "downloader/image-downloader.h"
#include "functions.h"
#include "helpers.h"
#include "image-context-menu.h"
#include "logger.h"
#include "models/image.h"
#include "models/profile.h"
#include "models/site.h"
#include "network/network-reply.h"
#include "ui/QBouton.h"
QMovie *ImagePreview::m_loadingMovie = nullptr;
ImagePreview::ImagePreview(QSharedPointer<Image> image, QWidget *container, Profile *profile, DownloadQueue *downloadQueue, MainWindow *mainWindow, QObject *parent)
: QObject(parent), m_image(image), m_container(container), m_profile(profile), m_downloadQueue(downloadQueue), m_mainWindow(mainWindow)
{
m_thumbnailUrl = image->url(Image::Size::Thumbnail);
m_name = image->name();
m_childrenCount = image->counter().toInt();
auto *layout = new QVBoxLayout();
layout->setContentsMargins(0, 0, 0, 0);
container->setLayout(layout);
container->setContextMenuPolicy(Qt::CustomContextMenu);
connect(container, &QWidget::customContextMenuRequested, this, &ImagePreview::customContextMenuRequested);
}
ImagePreview::~ImagePreview()
{
m_reply->deleteLater();
m_reply = nullptr;
}
void ImagePreview::showLoadingMessage()
{
if (m_loadingMovie == nullptr) {
auto *loadingMovie = new QMovie(":/images/loading.gif");
if (m_loadingMovie == nullptr) {
m_loadingMovie = loadingMovie;
m_loadingMovie->start();
} else {
loadingMovie->deleteLater();
}
}
auto *loadingLabel = new QLabel();
loadingLabel->setMovie(m_loadingMovie);
loadingLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
loadingLabel->setScaledContents(true);
auto *layout = m_container->layout();
layout->addWidget(loadingLabel);
}
void ImagePreview::load()
{
if (m_thumbnailUrl.isValid()) {
if (m_reply != nullptr) {
m_reply->deleteLater();
} else {
showLoadingMessage();
}
Site *site = m_image->parentSite();
m_reply = site->get(site->fixUrl(m_thumbnailUrl.toString()), Site::QueryType::Thumbnail, m_image->parentUrl(), "preview");
connect(m_reply, &NetworkReply::finished, this, &ImagePreview::finishedLoadingPreview);
} else {
finishedLoading();
}
}
void ImagePreview::abort()
{
m_aborted = true;
if (m_reply->isRunning()) {
m_reply->abort();
}
}
void ImagePreview::setChecked(bool checked)
{
m_checked = checked;
if (m_bouton != nullptr) {
m_bouton->setChecked(checked);
}
}
void ImagePreview::setDownloadProgress(qint64 v1, qint64 v2)
{
if (m_bouton != nullptr) {
m_bouton->setProgress(v1, v2);
}
}
void ImagePreview::finishedLoadingPreview()
{
if (m_aborted) {
return;
}
// Aborted
if (m_reply->error() == NetworkReply::NetworkError::OperationCanceledError) {
return;
}
// Check redirection
QUrl redirection = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
if (!redirection.isEmpty()) {
m_thumbnailUrl = redirection;
load();
return;
}
// Loading error
if (m_reply->error() != NetworkReply::NetworkError::NoError) {
const QString ext = getExtension(m_reply->url());
if (ext != "jpg") {
log(QStringLiteral("Error loading thumbnail (%1), new try with extension JPG").arg(m_reply->errorString()), Logger::Warning);
m_thumbnailUrl = setExtension(m_reply->url(), "jpg");
load();
} else {
log(QStringLiteral("Error loading thumbnail (%1)").arg(m_reply->errorString()), Logger::Error);
}
return;
}
// Load preview from result
QPixmap thumbnail;
thumbnail.loadFromData(m_reply->readAll());
if (thumbnail.isNull()) {
log(QStringLiteral("One of the thumbnails is empty (`%1`).").arg(m_image->url(Image::Size::Thumbnail).toString()), Logger::Error);
if (m_image->hasTag(QStringLiteral("flash"))) {
thumbnail.load(QStringLiteral(":/images/flash.png"));
} else {
return;
}
}
m_image->setPreviewImage(thumbnail);
finishedLoading();
}
void ImagePreview::finishedLoading()
{
auto *layout = m_container->layout();
clearLayout(layout);
if (m_reply != nullptr) {
QSettings *settings = m_profile->getSettings();
const bool resizeInsteadOfCropping = settings->value("resizeInsteadOfCropping", true).toBool();
const bool resultsScrollArea = settings->value("resultsScrollArea", true).toBool();
const int borderSize = settings->value("borders", 3).toInt();
const qreal upscale = settings->value("thumbnailUpscale", 1.0).toDouble();
const int imageSize = qFloor(150 * upscale);
QBouton *l = new QBouton(0, resizeInsteadOfCropping, resultsScrollArea, borderSize, m_image->color(), m_container);
l->setCheckable(true);
l->setFlat(true);
l->setChecked(m_checked);
l->setInvertToggle(settings->value("invertToggle", false).toBool());
l->setToolTip(m_image->tooltip());
const QPixmap &thumbnail = m_image->previewImage();
if (thumbnail.isNull()) {
l->scale(QPixmap(":/images/noimage.png"), QSize(imageSize, imageSize));
} else {
l->scale(thumbnail, QSize(imageSize, imageSize));
}
if (m_childrenCount > 0) {
l->setCounter(QString::number(m_childrenCount));
}
connect(l, SIGNAL(appui(int)), this, SIGNAL(clicked()));
connect(l, SIGNAL(toggled(int, bool, bool)), this, SLOT(toggledWithId(int, bool, bool)));
layout->addWidget(l);
m_bouton = l;
}
if (!m_name.isEmpty()) {
layout->addWidget(new QLabel(m_name));
}
emit finished();
}
void ImagePreview::toggledWithId(int id, bool toggle, bool range)
{
Q_UNUSED(id);
emit toggled(toggle, range);
}
QStringList getImageAlreadyExists(const QSharedPointer<Image> &img, Profile *profile)
{
QSettings *settings = profile->getSettings();
const QString path = settings->value("Save/path").toString().replace("\\", "/");
const QString fn = settings->value("Save/filename").toString();
if (Filename(fn).needExactTags(img->parentSite(), settings) == 0) {
QStringList ret;
QStringList files = img->paths(fn, path, 0);
for (const QString &file : files) {
if (QFile(file).exists()) {
ret.append(file);
}
}
if (!ret.isEmpty()) {
return ret;
}
}
return profile->md5Exists(img->md5());
}
void ImagePreview::customContextMenuRequested()
{
QMenu *menu = new ImageContextMenu(m_profile->getSettings(), m_image, m_mainWindow, m_container);
QAction *first = menu->actions().first();
// Save image
QAction *actionSave;
if (!getImageAlreadyExists(m_image, m_profile).isEmpty()) {
actionSave = new QAction(QIcon(":/images/status/error.png"), tr("Delete"), menu);
} else {
actionSave = new QAction(QIcon(":/images/icons/save.png"), tr("Save"), menu);
}
connect(actionSave, &QAction::triggered, this, &ImagePreview::contextSaveImage);
menu->insertAction(first, actionSave);
// Save image as...
QAction *actionSaveAs = new QAction(QIcon(":/images/icons/save-as.png"), tr("Save as..."), menu);
connect(actionSaveAs, &QAction::triggered, this, &ImagePreview::contextSaveImageAs);
menu->insertAction(first, actionSaveAs);
// Custom elements
if (m_customContextMenu != nullptr) {
m_customContextMenu(menu, m_image);
}
menu->insertSeparator(first);
menu->exec(QCursor::pos());
}
void ImagePreview::contextSaveImage()
{
QStringList already = getImageAlreadyExists(m_image, m_profile);
if (!already.isEmpty()) {
for (const QString &path : already) {
QFile(path).remove();
m_profile->removeMd5(m_image->md5(), path);
}
} else {
QSettings *settings = m_profile->getSettings();
const QString fn = settings->value("Save/filename").toString();
const QString path = settings->value("Save/path").toString();
auto downloader = new ImageDownloader(m_profile, m_image, fn, path, 1, true, true, m_downloadQueue);
connect(downloader, &ImageDownloader::downloadProgress, this, &ImagePreview::contextSaveImageProgress);
m_downloadQueue->add(DownloadQueue::Manual, downloader);
}
}
void ImagePreview::contextSaveImageAs()
{
QSettings *settings = m_profile->getSettings();
Filename format(settings->value("Save/filename").toString());
QString tmpPath;
// If the MD5 is required for the filename, we first download the image
if (format.needTemporaryFile(m_image->tokens(m_profile))) {
tmpPath = QDir::temp().absoluteFilePath("grabber-saveAs-" + QString::number(QRandomGenerator::global()->generate(), 16));
QEventLoop loop;
ImageDownloader downloader(m_profile, m_image, { tmpPath }, 1, true, true, this);
connect(&downloader, &ImageDownloader::saved, &loop, &QEventLoop::quit);
downloader.save();
loop.exec();
}
const QStringList filenames = format.path(*m_image, m_profile);
const QString filename = filenames.first().section(QDir::separator(), -1);
const QString lastDir = settings->value("Zoom/lastDir").toString();
QString path = QFileDialog::getSaveFileName(m_container, tr("Save image"), QDir::toNativeSeparators(lastDir + "/" + filename), "Images (*.png *.gif *.jpg *.jpeg)");
if (!path.isEmpty()) {
path = QDir::toNativeSeparators(path);
settings->setValue("Zoom/lastDir", path.section(QDir::separator(), 0, -2));
if (!tmpPath.isEmpty()) {
QFile::rename(tmpPath, path);
} else {
auto downloader = new ImageDownloader(m_profile, m_image, { path }, 1, true, true, this, true, false, Image::Size::Unknown, true, true);
connect(downloader, &ImageDownloader::downloadProgress, this, &ImagePreview::contextSaveImageProgress);
m_downloadQueue->add(DownloadQueue::Manual, downloader);
}
} else if (!tmpPath.isEmpty()) {
QFile::remove(tmpPath);
}
}
void ImagePreview::contextSaveImageProgress(const QSharedPointer<Image> &img, qint64 v1, qint64 v2)
{
Q_UNUSED(img);
setDownloadProgress(v1, v2);
}
void ImagePreview::setCustomContextMenu(std::function<void (QMenu *, const QSharedPointer<Image> &)> customContextMenu)
{
m_customContextMenu = customContextMenu;
}
<commit_msg>Load tags before 'save as...' when necessary (fix #2234)<commit_after>#include "tabs/image-preview.h"
#include <QDir>
#include <QEventLoop>
#include <QFile>
#include <QFileDialog>
#include <QLabel>
#include <QMenu>
#include <QMovie>
#include <QRandomGenerator>
#include <QSettings>
#include <QtMath>
#include <QUrl>
#include <QVBoxLayout>
#include <QWidget>
#include "downloader/download-queue.h"
#include "downloader/image-downloader.h"
#include "functions.h"
#include "helpers.h"
#include "image-context-menu.h"
#include "logger.h"
#include "models/image.h"
#include "models/profile.h"
#include "models/site.h"
#include "network/network-reply.h"
#include "ui/QBouton.h"
QMovie *ImagePreview::m_loadingMovie = nullptr;
ImagePreview::ImagePreview(QSharedPointer<Image> image, QWidget *container, Profile *profile, DownloadQueue *downloadQueue, MainWindow *mainWindow, QObject *parent)
: QObject(parent), m_image(image), m_container(container), m_profile(profile), m_downloadQueue(downloadQueue), m_mainWindow(mainWindow)
{
m_thumbnailUrl = image->url(Image::Size::Thumbnail);
m_name = image->name();
m_childrenCount = image->counter().toInt();
auto *layout = new QVBoxLayout();
layout->setContentsMargins(0, 0, 0, 0);
container->setLayout(layout);
container->setContextMenuPolicy(Qt::CustomContextMenu);
connect(container, &QWidget::customContextMenuRequested, this, &ImagePreview::customContextMenuRequested);
}
ImagePreview::~ImagePreview()
{
m_reply->deleteLater();
m_reply = nullptr;
}
void ImagePreview::showLoadingMessage()
{
if (m_loadingMovie == nullptr) {
auto *loadingMovie = new QMovie(":/images/loading.gif");
if (m_loadingMovie == nullptr) {
m_loadingMovie = loadingMovie;
m_loadingMovie->start();
} else {
loadingMovie->deleteLater();
}
}
auto *loadingLabel = new QLabel();
loadingLabel->setMovie(m_loadingMovie);
loadingLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
loadingLabel->setScaledContents(true);
auto *layout = m_container->layout();
layout->addWidget(loadingLabel);
}
void ImagePreview::load()
{
if (m_thumbnailUrl.isValid()) {
if (m_reply != nullptr) {
m_reply->deleteLater();
} else {
showLoadingMessage();
}
Site *site = m_image->parentSite();
m_reply = site->get(site->fixUrl(m_thumbnailUrl.toString()), Site::QueryType::Thumbnail, m_image->parentUrl(), "preview");
connect(m_reply, &NetworkReply::finished, this, &ImagePreview::finishedLoadingPreview);
} else {
finishedLoading();
}
}
void ImagePreview::abort()
{
m_aborted = true;
if (m_reply->isRunning()) {
m_reply->abort();
}
}
void ImagePreview::setChecked(bool checked)
{
m_checked = checked;
if (m_bouton != nullptr) {
m_bouton->setChecked(checked);
}
}
void ImagePreview::setDownloadProgress(qint64 v1, qint64 v2)
{
if (m_bouton != nullptr) {
m_bouton->setProgress(v1, v2);
}
}
void ImagePreview::finishedLoadingPreview()
{
if (m_aborted) {
return;
}
// Aborted
if (m_reply->error() == NetworkReply::NetworkError::OperationCanceledError) {
return;
}
// Check redirection
QUrl redirection = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
if (!redirection.isEmpty()) {
m_thumbnailUrl = redirection;
load();
return;
}
// Loading error
if (m_reply->error() != NetworkReply::NetworkError::NoError) {
const QString ext = getExtension(m_reply->url());
if (ext != "jpg") {
log(QStringLiteral("Error loading thumbnail (%1), new try with extension JPG").arg(m_reply->errorString()), Logger::Warning);
m_thumbnailUrl = setExtension(m_reply->url(), "jpg");
load();
} else {
log(QStringLiteral("Error loading thumbnail (%1)").arg(m_reply->errorString()), Logger::Error);
}
return;
}
// Load preview from result
QPixmap thumbnail;
thumbnail.loadFromData(m_reply->readAll());
if (thumbnail.isNull()) {
log(QStringLiteral("One of the thumbnails is empty (`%1`).").arg(m_image->url(Image::Size::Thumbnail).toString()), Logger::Error);
if (m_image->hasTag(QStringLiteral("flash"))) {
thumbnail.load(QStringLiteral(":/images/flash.png"));
} else {
return;
}
}
m_image->setPreviewImage(thumbnail);
finishedLoading();
}
void ImagePreview::finishedLoading()
{
auto *layout = m_container->layout();
clearLayout(layout);
if (m_reply != nullptr) {
QSettings *settings = m_profile->getSettings();
const bool resizeInsteadOfCropping = settings->value("resizeInsteadOfCropping", true).toBool();
const bool resultsScrollArea = settings->value("resultsScrollArea", true).toBool();
const int borderSize = settings->value("borders", 3).toInt();
const qreal upscale = settings->value("thumbnailUpscale", 1.0).toDouble();
const int imageSize = qFloor(150 * upscale);
QBouton *l = new QBouton(0, resizeInsteadOfCropping, resultsScrollArea, borderSize, m_image->color(), m_container);
l->setCheckable(true);
l->setFlat(true);
l->setChecked(m_checked);
l->setInvertToggle(settings->value("invertToggle", false).toBool());
l->setToolTip(m_image->tooltip());
const QPixmap &thumbnail = m_image->previewImage();
if (thumbnail.isNull()) {
l->scale(QPixmap(":/images/noimage.png"), QSize(imageSize, imageSize));
} else {
l->scale(thumbnail, QSize(imageSize, imageSize));
}
if (m_childrenCount > 0) {
l->setCounter(QString::number(m_childrenCount));
}
connect(l, SIGNAL(appui(int)), this, SIGNAL(clicked()));
connect(l, SIGNAL(toggled(int, bool, bool)), this, SLOT(toggledWithId(int, bool, bool)));
layout->addWidget(l);
m_bouton = l;
}
if (!m_name.isEmpty()) {
layout->addWidget(new QLabel(m_name));
}
emit finished();
}
void ImagePreview::toggledWithId(int id, bool toggle, bool range)
{
Q_UNUSED(id);
emit toggled(toggle, range);
}
QStringList getImageAlreadyExists(const QSharedPointer<Image> &img, Profile *profile)
{
QSettings *settings = profile->getSettings();
const QString path = settings->value("Save/path").toString().replace("\\", "/");
const QString fn = settings->value("Save/filename").toString();
if (Filename(fn).needExactTags(img->parentSite(), settings) == 0) {
QStringList ret;
QStringList files = img->paths(fn, path, 0);
for (const QString &file : files) {
if (QFile(file).exists()) {
ret.append(file);
}
}
if (!ret.isEmpty()) {
return ret;
}
}
return profile->md5Exists(img->md5());
}
void ImagePreview::customContextMenuRequested()
{
QMenu *menu = new ImageContextMenu(m_profile->getSettings(), m_image, m_mainWindow, m_container);
QAction *first = menu->actions().first();
// Save image
QAction *actionSave;
if (!getImageAlreadyExists(m_image, m_profile).isEmpty()) {
actionSave = new QAction(QIcon(":/images/status/error.png"), tr("Delete"), menu);
} else {
actionSave = new QAction(QIcon(":/images/icons/save.png"), tr("Save"), menu);
}
connect(actionSave, &QAction::triggered, this, &ImagePreview::contextSaveImage);
menu->insertAction(first, actionSave);
// Save image as...
QAction *actionSaveAs = new QAction(QIcon(":/images/icons/save-as.png"), tr("Save as..."), menu);
connect(actionSaveAs, &QAction::triggered, this, &ImagePreview::contextSaveImageAs);
menu->insertAction(first, actionSaveAs);
// Custom elements
if (m_customContextMenu != nullptr) {
m_customContextMenu(menu, m_image);
}
menu->insertSeparator(first);
menu->exec(QCursor::pos());
}
void ImagePreview::contextSaveImage()
{
QStringList already = getImageAlreadyExists(m_image, m_profile);
if (!already.isEmpty()) {
for (const QString &path : already) {
QFile(path).remove();
m_profile->removeMd5(m_image->md5(), path);
}
} else {
QSettings *settings = m_profile->getSettings();
const QString fn = settings->value("Save/filename").toString();
const QString path = settings->value("Save/path").toString();
auto downloader = new ImageDownloader(m_profile, m_image, fn, path, 1, true, true, m_downloadQueue);
connect(downloader, &ImageDownloader::downloadProgress, this, &ImagePreview::contextSaveImageProgress);
m_downloadQueue->add(DownloadQueue::Manual, downloader);
}
}
void ImagePreview::contextSaveImageAs()
{
QSettings *settings = m_profile->getSettings();
Filename format(settings->value("Save/filename").toString());
QString tmpPath;
// If we need detailed tags for the filename, we first load them
const int needTags = format.needExactTags(m_image->parentSite(), settings);
if (needTags == 2 || (needTags == 1 && m_image->hasUnknownTag())) {
QEventLoop loop;
m_image->loadDetails();
connect(m_image.data(), &Image::finishedLoadingTags, &loop, &QEventLoop::quit);
loop.exec();
}
// If the MD5 is required for the filename, we first download the image
if (format.needTemporaryFile(m_image->tokens(m_profile))) {
tmpPath = QDir::temp().absoluteFilePath("grabber-saveAs-" + QString::number(QRandomGenerator::global()->generate(), 16));
QEventLoop loop;
ImageDownloader downloader(m_profile, m_image, { tmpPath }, 1, true, true, this);
connect(&downloader, &ImageDownloader::saved, &loop, &QEventLoop::quit);
downloader.save();
loop.exec();
}
const QStringList filenames = format.path(*m_image, m_profile);
const QString filename = filenames.first().section(QDir::separator(), -1);
const QString lastDir = settings->value("Zoom/lastDir").toString();
QString path = QFileDialog::getSaveFileName(m_container, tr("Save image"), QDir::toNativeSeparators(lastDir + "/" + filename), "Images (*.png *.gif *.jpg *.jpeg)");
if (!path.isEmpty()) {
path = QDir::toNativeSeparators(path);
settings->setValue("Zoom/lastDir", path.section(QDir::separator(), 0, -2));
if (!tmpPath.isEmpty()) {
QFile::rename(tmpPath, path);
} else {
auto downloader = new ImageDownloader(m_profile, m_image, { path }, 1, true, true, this, true, false, Image::Size::Unknown, true, true);
connect(downloader, &ImageDownloader::downloadProgress, this, &ImagePreview::contextSaveImageProgress);
m_downloadQueue->add(DownloadQueue::Manual, downloader);
}
} else if (!tmpPath.isEmpty()) {
QFile::remove(tmpPath);
}
}
void ImagePreview::contextSaveImageProgress(const QSharedPointer<Image> &img, qint64 v1, qint64 v2)
{
Q_UNUSED(img);
setDownloadProgress(v1, v2);
}
void ImagePreview::setCustomContextMenu(std::function<void (QMenu *, const QSharedPointer<Image> &)> customContextMenu)
{
m_customContextMenu = customContextMenu;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2017-2018 Baidu 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 "openrasp_inject.h"
#include "openrasp_ini.h"
#include <string>
#include <vector>
#include <fstream>
#include <chrono>
#include <new>
ZEND_DECLARE_MODULE_GLOBALS(openrasp_inject)
std::vector<char> inject_html;
void openrasp_load_inject_html(TSRMLS_D)
{
std::vector<char> inject;
char *path;
spprintf(&path, 0, "%s%cassets%cinject.html", openrasp_ini.root_dir, DEFAULT_SLASH, DEFAULT_SLASH);
std::ifstream file(path, std::ios::binary | std::ios::ate);
efree(path);
if (file.is_open())
{
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
inject.resize(size);
file.read(inject.data(), size);
}
inject_html = std::move(inject);
}
PHP_GINIT_FUNCTION(openrasp_inject)
{
#ifdef ZTS
new (openrasp_inject_globals) _zend_openrasp_inject_globals;
#endif
}
PHP_GSHUTDOWN_FUNCTION(openrasp_inject)
{
#ifdef ZTS
openrasp_inject_globals->~_zend_openrasp_inject_globals();
#endif
}
PHP_MINIT_FUNCTION(openrasp_inject)
{
ZEND_INIT_MODULE_GLOBALS(openrasp_inject, PHP_GINIT(openrasp_inject), PHP_GSHUTDOWN(openrasp_inject));
openrasp_load_inject_html(TSRMLS_C);
return SUCCESS;
}
PHP_MSHUTDOWN_FUNCTION(openrasp_inject)
{
ZEND_SHUTDOWN_MODULE_GLOBALS(openrasp_inject, PHP_GSHUTDOWN(openrasp_inject));
return SUCCESS;
}
PHP_RINIT_FUNCTION(openrasp_inject)
{
{
auto time_point = std::chrono::steady_clock::now();
long long nano = time_point.time_since_epoch().count();
unsigned long hash = zend_inline_hash_func(reinterpret_cast<const char *>(&nano), sizeof(nano));
spprintf(&OPENRASP_INJECT_G(request_id), 32, "%016lx%016llx", hash, nano);
char *uuid_header = nullptr;
int uuid_header_len = spprintf(&uuid_header, 0, "X-Request-ID: %s", OPENRASP_INJECT_G(request_id));
if (uuid_header)
{
sapi_header_line header;
header.line = uuid_header;
header.line_len = uuid_header_len;
header.response_code = 0;
sapi_header_op(SAPI_HEADER_REPLACE, &header TSRMLS_CC);
}
efree(uuid_header);
}
{
sapi_header_line header;
header.line = "X-Protected-By: OpenRASP";
header.line_len = sizeof("X-Protected-By: OpenRASP") - 1;
header.response_code = 0;
sapi_header_op(SAPI_HEADER_REPLACE, &header TSRMLS_CC);
}
return SUCCESS;
}
PHP_RSHUTDOWN_FUNCTION(openrasp_inject)
{
static const char REQUEST_URI[] = "REQUEST_URI";
static const ulong REQUEST_URI_HASH = zend_get_hash_value(ZEND_STRS(REQUEST_URI));
if (inject_html.size())
{
bool is_match_inject_prefix = true;
if (openrasp_ini.inject_html_urlprefix && strlen(openrasp_ini.inject_html_urlprefix) > 0)
{
is_match_inject_prefix = false;
if (PG(http_globals)[TRACK_VARS_SERVER] || zend_is_auto_global(ZEND_STRL("_SERVER") TSRMLS_CC))
{
zval **value;
if (zend_hash_quick_find(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]), ZEND_STRS(REQUEST_URI), REQUEST_URI_HASH, (void **)&value) == SUCCESS &&
Z_TYPE_PP(value) == IS_STRING &&
strncasecmp(Z_STRVAL_PP(value), openrasp_ini.inject_html_urlprefix, strlen(openrasp_ini.inject_html_urlprefix)) == 0)
{
is_match_inject_prefix = true;
}
}
}
if (is_match_inject_prefix)
{
char target_header[] = "text/html";
for (zend_llist_element *element = SG(sapi_headers).headers.head; element; element = element->next)
{
sapi_header_struct *sapi_header = (sapi_header_struct *)element->data;
if (sapi_header->header_len > 0 &&
strncasecmp(sapi_header->header, "content-type", sizeof("content-type") - 1) == 0 &&
php_stristr(sapi_header->header, target_header, sapi_header->header_len, strlen(target_header)) != nullptr)
{
#if PHP_MINOR_VERSION > 3
php_output_write(inject_html.data(), inject_html.size() TSRMLS_CC);
#else
php_body_write(inject_html.data(), inject_html.size() TSRMLS_CC);
#endif
break;
}
}
}
}
efree(OPENRASP_INJECT_G(request_id));
return SUCCESS;
}<commit_msg>[PHP5]is_match_inject_prefix 初始值<commit_after>/*
* Copyright 2017-2018 Baidu 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 "openrasp_inject.h"
#include "openrasp_ini.h"
#include <string>
#include <vector>
#include <fstream>
#include <chrono>
#include <new>
ZEND_DECLARE_MODULE_GLOBALS(openrasp_inject)
std::vector<char> inject_html;
void openrasp_load_inject_html(TSRMLS_D)
{
std::vector<char> inject;
char *path;
spprintf(&path, 0, "%s%cassets%cinject.html", openrasp_ini.root_dir, DEFAULT_SLASH, DEFAULT_SLASH);
std::ifstream file(path, std::ios::binary | std::ios::ate);
efree(path);
if (file.is_open())
{
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
inject.resize(size);
file.read(inject.data(), size);
}
inject_html = std::move(inject);
}
PHP_GINIT_FUNCTION(openrasp_inject)
{
#ifdef ZTS
new (openrasp_inject_globals) _zend_openrasp_inject_globals;
#endif
}
PHP_GSHUTDOWN_FUNCTION(openrasp_inject)
{
#ifdef ZTS
openrasp_inject_globals->~_zend_openrasp_inject_globals();
#endif
}
PHP_MINIT_FUNCTION(openrasp_inject)
{
ZEND_INIT_MODULE_GLOBALS(openrasp_inject, PHP_GINIT(openrasp_inject), PHP_GSHUTDOWN(openrasp_inject));
openrasp_load_inject_html(TSRMLS_C);
return SUCCESS;
}
PHP_MSHUTDOWN_FUNCTION(openrasp_inject)
{
ZEND_SHUTDOWN_MODULE_GLOBALS(openrasp_inject, PHP_GSHUTDOWN(openrasp_inject));
return SUCCESS;
}
PHP_RINIT_FUNCTION(openrasp_inject)
{
{
auto time_point = std::chrono::steady_clock::now();
long long nano = time_point.time_since_epoch().count();
unsigned long hash = zend_inline_hash_func(reinterpret_cast<const char *>(&nano), sizeof(nano));
spprintf(&OPENRASP_INJECT_G(request_id), 32, "%016lx%016llx", hash, nano);
char *uuid_header = nullptr;
int uuid_header_len = spprintf(&uuid_header, 0, "X-Request-ID: %s", OPENRASP_INJECT_G(request_id));
if (uuid_header)
{
sapi_header_line header;
header.line = uuid_header;
header.line_len = uuid_header_len;
header.response_code = 0;
sapi_header_op(SAPI_HEADER_REPLACE, &header TSRMLS_CC);
}
efree(uuid_header);
}
{
sapi_header_line header;
header.line = "X-Protected-By: OpenRASP";
header.line_len = sizeof("X-Protected-By: OpenRASP") - 1;
header.response_code = 0;
sapi_header_op(SAPI_HEADER_REPLACE, &header TSRMLS_CC);
}
return SUCCESS;
}
PHP_RSHUTDOWN_FUNCTION(openrasp_inject)
{
static const char REQUEST_URI[] = "REQUEST_URI";
static const ulong REQUEST_URI_HASH = zend_get_hash_value(ZEND_STRS(REQUEST_URI));
if (inject_html.size())
{
bool is_match_inject_prefix = false;
if (openrasp_ini.inject_html_urlprefix && strlen(openrasp_ini.inject_html_urlprefix) > 0)
{
is_match_inject_prefix = false;
if (PG(http_globals)[TRACK_VARS_SERVER] || zend_is_auto_global(ZEND_STRL("_SERVER") TSRMLS_CC))
{
zval **value;
if (zend_hash_quick_find(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]), ZEND_STRS(REQUEST_URI), REQUEST_URI_HASH, (void **)&value) == SUCCESS &&
Z_TYPE_PP(value) == IS_STRING &&
strncasecmp(Z_STRVAL_PP(value), openrasp_ini.inject_html_urlprefix, strlen(openrasp_ini.inject_html_urlprefix)) == 0)
{
is_match_inject_prefix = true;
}
}
}
if (is_match_inject_prefix)
{
char target_header[] = "text/html";
for (zend_llist_element *element = SG(sapi_headers).headers.head; element; element = element->next)
{
sapi_header_struct *sapi_header = (sapi_header_struct *)element->data;
if (sapi_header->header_len > 0 &&
strncasecmp(sapi_header->header, "content-type", sizeof("content-type") - 1) == 0 &&
php_stristr(sapi_header->header, target_header, sapi_header->header_len, strlen(target_header)) != nullptr)
{
#if PHP_MINOR_VERSION > 3
php_output_write(inject_html.data(), inject_html.size() TSRMLS_CC);
#else
php_body_write(inject_html.data(), inject_html.size() TSRMLS_CC);
#endif
break;
}
}
}
}
efree(OPENRASP_INJECT_G(request_id));
return SUCCESS;
}<|endoftext|>
|
<commit_before>#include "LIBGPU.H"
#include "EMULATOR.H"
#define GL_GLEXT_PROTOTYPES 1
#include <SDL.h>
#include <SDL_opengl.h>
#include <SDL_opengl_glext.h>
#include <stdio.h>
#include <cstring>
#include <cassert>
#include <LIBETC.H>
unsigned short vram[1024 * 512];
DISPENV word_33BC;
int dword_3410 = 0;
char byte_3352 = 0;
void* off_3348[]=
{
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL
};
int ClearImage(RECT16* rect, u_char r, u_char g, u_char b)
{
#if USE_FRAME_BUFFERS
char* pixelData = new char[rect->w*rect->h * 3];
memset(pixelData, 0, rect->w*rect->h * 3);
for (int y = 0; y < rect->w*rect->h * 3; y += 3)
{
pixelData[y + 0] = r;
pixelData[y + 1] = g;
pixelData[y + 2] = b;
}
GLuint blitFramebufferName = 0;
glGenFramebuffers(1, &blitFramebufferName);
glBindFramebuffer(GL_FRAMEBUFFER, blitFramebufferName);
GLuint blitTexture = 0;
glGenTextures(1, &blitTexture);
glBindTexture(GL_TEXTURE_2D, blitTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, rect->w, rect->h, 0, GL_RGB, GL_UNSIGNED_BYTE, pixelData);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, blitTexture, 0);
glBindFramebuffer(GL_FRAMEBUFFER, blitFramebufferName);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, blitTexture, 0);
glReadBuffer(GL_COLOR_ATTACHMENT0);
glBindFramebuffer(GL_FRAMEBUFFER, vramFramebufferName);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, vramTexture, 0);
glDrawBuffer(GL_COLOR_ATTACHMENT1);
//tr glBlitNamedFramebuffer(blitFramebufferName, vramFramebufferName, 0, 0, rect->w, rect->h, 512, 0, 512+(rect->y*2), 256, GL_COLOR_BUFFER_BIT, GL_NEAREST);
//tl glBlitNamedFramebuffer(blitFramebufferName, vramFramebufferName, 0, 0, rect->w, rect->h, 0 , 0, 512+(rect->y*2), 256, GL_COLOR_BUFFER_BIT, GL_NEAREST);
//bl glBlitNamedFramebuffer(blitFramebufferName, vramFramebufferName, 0, 0, rect->w, rect->h, 0, 256, 512, 512 + (rect->y * 2), GL_COLOR_BUFFER_BIT, GL_NEAREST);
glBlitNamedFramebuffer(blitFramebufferName, vramFramebufferName, 0, 0, rect->w, rect->h, rect->x, rect->y, 512 + (rect->x * 2), 256 + rect->y, GL_COLOR_BUFFER_BIT, GL_NEAREST);
printf("X: %d Y: %d W: %d H: %d\n", 0, rect->y, 512 + (rect->x * 2), rect->h);
#else
for (int y = 0; y < 512; y++)
{
for (int x = 0; x < 1024; x++)
{
unsigned short* pixel = vram + (y * 1024 + x);
if (x >= rect->x && x < rect->x + rect->w &&
y >= rect->y && y < rect->y + rect->h)
{
pixel[0] = ((r >> 3) << 11) | ((g >> 3) << 6) | ((b >> 3) << 1) | 1;
}
}
}
#endif
return 0;
}
int DrawSync(int mode)
{
return 0;
}
int LoadImagePSX(RECT16* rect, u_long* p)
{
#if USE_FRAME_BUFFERS
GLuint blitFramebufferName = 0;
glGenFramebuffers(1, &blitFramebufferName);
glBindFramebuffer(GL_FRAMEBUFFER, blitFramebufferName);
GLuint blitTexture = 0;
glGenTextures(1, &blitTexture);
// "Bind" the newly created texture : all future texture functions will modify this texture
glBindTexture(GL_TEXTURE_2D, blitTexture);
// Give an empty image to OpenGL ( the last "0" )
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, rect->w, rect->h, 0, GL_RGB, GL_UNSIGNED_SHORT_4_4_4_4_REV, (unsigned short*)p);
///glCopyBufferSubData(blitTexture, vramTexture, 0, 0, rect->w * rect->h * 4)
// Poor filtering. Needed !
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, blitTexture, 0);
glBindFramebuffer(GL_FRAMEBUFFER, blitFramebufferName);
// Bind input FBO + texture to a color attachment
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, blitTexture, 0);
glReadBuffer(GL_COLOR_ATTACHMENT0);
// Bind destination FBO + texture to another color attachment
glBindFramebuffer(GL_FRAMEBUFFER, vramFramebufferName);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, vramTexture, 0);
glDrawBuffer(GL_COLOR_ATTACHMENT1);
// glBlitFramebuffer(0, 0, rect->w, rect->h, 0, 0, rect->w, rect->h, GL_COLOR_BUFFER_BIT, GL_NEAREST);
glBlitNamedFramebuffer(blitFramebufferName, vramFramebufferName, 0, 0, rect->w, rect->h, rect->x, rect->y, 512 + (rect->x * 2), 256 + rect->y, GL_COLOR_BUFFER_BIT, GL_NEAREST);
#else
unsigned short* dst = (unsigned short*)p;
for (int y = 0; y < 512; y++)
{
for (int x = 0; x < 1024; x++)
{
unsigned short* src = vram + (y * 1024 + x);
if (x >= rect->x && x < rect->x + rect->w &&
y >= rect->y && y < rect->y + rect->h)
{
src[0] = *dst++;
}
}
}
#endif
#if 1
FILE* f = fopen("VRAM.BIN", "wb");
fwrite(&vram[0], 1, 1024 * 512 * 2, f);
fclose(f);
#endif
return 0;
}
int ResetGraph(int mode)
{
return 0;
}
int SetGraphDebug(int level)
{
return 0;
}
int StoreImage(RECT16 * RECT16, u_long * p)
{
return 0;
}
u_long * ClearOTag(u_long * ot, int n)
{
assert(0);
return 0;
}
u_long* ClearOTagR(u_long* ot, int n)
{
//v0 = byte_3352;
//s0 = ot
//s1 = n
//v0 = v0 < 2 ? 1 : 0
if (byte_3352 > 1)
{
///GPU_printf("ClearOTagR(%08x,%d)...\n", ot, n);
}
//loc_CB0
// ((void*)off_3348[11])();
return 0;
}
void SetDispMask(int mask)
{
}
DISPENV* GetDispEnv(DISPENV* env)//(F)
{
memcpy(env, &word_33BC, sizeof(DISPENV));
return env;
}
DISPENV* PutDispEnv(DISPENV* env)//To Finish
{
memcpy((char*)&word_33BC, env, sizeof(DISPENV));
return 0;
}
DISPENV* SetDefDispEnv(DISPENV* env, int x, int y, int w, int h)//(F)
{
env->disp.x = x;
env->disp.y = y;
env->disp.w = w;
env->screen.x = 0;
env->screen.y = 0;
env->screen.w = 0;
env->screen.h = 0;
env->isrgb24 = 0;
env->isinter = 0;
env->pad1 = 0;
env->pad0 = 0;
env->disp.h = h;
return 0;
}
DRAWENV* PutDrawEnv(DRAWENV* env)
{
return NULL;
}
DRAWENV* SetDefDrawEnv(DRAWENV* env, int x, int y, int w, int h)//(F)
{
env->clip.x = x;
env->clip.y = y;
env->clip.w = w;
env->tw.x = 0;
env->tw.y = 0;
env->tw.w = 0;
env->tw.h = 0;
env->r0 = 0;
env->g0 = 0;
env->b0 = 0;
env->dtd = 1;
env->clip.h = h;
if (GetVideoMode() == 0)
{
env->dfe = h < 0x121 ? 1 : 0;
}
else
{
env->dfe = h < 0x101 ? 1 : 0;
}
env->ofs[0] = x;
env->ofs[1] = y;
env->tpage = 10;
env->isbg = 0;
return env;
}
u_long DrawSyncCallback(void(*func)(void))
{
return u_long();
}
void DrawOTagEnv(u_long* p, DRAWENV* env)
{
printf("Debug");
}
<commit_msg>Optimise LIBGPU.C and clean.<commit_after>#include "LIBGPU.H"
#include "EMULATOR.H"
#define GL_GLEXT_PROTOTYPES 1
#include <SDL.h>
#include <SDL_opengl.h>
#include <SDL_opengl_glext.h>
#include <stdio.h>
#include <cstring>
#include <cassert>
#include <LIBETC.H>
unsigned short vram[1024 * 512];
DISPENV word_33BC;
int dword_3410 = 0;
char byte_3352 = 0;
void* off_3348[]=
{
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL
};
int ClearImage(RECT16* rect, u_char r, u_char g, u_char b)
{
for (int y = rect->y; y < 512; y++)
{
for (int x = rect->x; x < 1024; x++)
{
unsigned short* pixel = vram + (y * 1024 + x);
if (x >= rect->x && x < rect->x + rect->w &&
y >= rect->y && y < rect->y + rect->h)
{
pixel[0] = ((r >> 3) << 11) | ((g >> 3) << 6) | ((b >> 3) << 1) | 0;
}
}
}
return 0;
}
int DrawSync(int mode)
{
return 0;
}
int LoadImagePSX(RECT16* rect, u_long* p)
{
unsigned short* dst = (unsigned short*)p;
for (int y = rect->y; y < 512; y++)
{
for (int x = rect->x; x < 1024; x++)
{
unsigned short* src = vram + (y * 1024 + x);
if (x >= rect->x && x < rect->x + rect->w &&
y >= rect->y && y < rect->y + rect->h)
{
src[0] = *dst++;
}
}
}
#if _DEBUG
FILE* f = fopen("VRAM.BIN", "wb");
fwrite(&vram[0], 1, 1024 * 512 * 2, f);
fclose(f);
#endif
return 0;
}
int ResetGraph(int mode)
{
return 0;
}
int SetGraphDebug(int level)
{
return 0;
}
int StoreImage(RECT16 * RECT16, u_long * p)
{
return 0;
}
u_long * ClearOTag(u_long * ot, int n)
{
assert(0);
return 0;
}
u_long* ClearOTagR(u_long* ot, int n)
{
//v0 = byte_3352;
//s0 = ot
//s1 = n
//v0 = v0 < 2 ? 1 : 0
if (byte_3352 > 1)
{
///GPU_printf("ClearOTagR(%08x,%d)...\n", ot, n);
}
//loc_CB0
// ((void*)off_3348[11])();
return 0;
}
void SetDispMask(int mask)
{
}
DISPENV* GetDispEnv(DISPENV* env)//(F)
{
memcpy(env, &word_33BC, sizeof(DISPENV));
return env;
}
DISPENV* PutDispEnv(DISPENV* env)//To Finish
{
memcpy((char*)&word_33BC, env, sizeof(DISPENV));
return 0;
}
DISPENV* SetDefDispEnv(DISPENV* env, int x, int y, int w, int h)//(F)
{
env->disp.x = x;
env->disp.y = y;
env->disp.w = w;
env->screen.x = 0;
env->screen.y = 0;
env->screen.w = 0;
env->screen.h = 0;
env->isrgb24 = 0;
env->isinter = 0;
env->pad1 = 0;
env->pad0 = 0;
env->disp.h = h;
return 0;
}
DRAWENV* PutDrawEnv(DRAWENV* env)
{
return NULL;
}
DRAWENV* SetDefDrawEnv(DRAWENV* env, int x, int y, int w, int h)//(F)
{
env->clip.x = x;
env->clip.y = y;
env->clip.w = w;
env->tw.x = 0;
env->tw.y = 0;
env->tw.w = 0;
env->tw.h = 0;
env->r0 = 0;
env->g0 = 0;
env->b0 = 0;
env->dtd = 1;
env->clip.h = h;
if (GetVideoMode() == 0)
{
env->dfe = h < 0x121 ? 1 : 0;
}
else
{
env->dfe = h < 0x101 ? 1 : 0;
}
env->ofs[0] = x;
env->ofs[1] = y;
env->tpage = 10;
env->isbg = 0;
return env;
}
u_long DrawSyncCallback(void(*func)(void))
{
return u_long();
}
void DrawOTagEnv(u_long* p, DRAWENV* env)
{
printf("Debug");
}
<|endoftext|>
|
<commit_before>#include "MISC.H"
#include "CONTROL.H"
#include "CAMERA.H"
#include "GPU.H"
#include "LOAD_LEV.H"
#include "SPECIFIC.H"
#include "TEXT_S.H"
#include <EMULATOR.H>
#include <LIBETC.H>
#if PSXPC_VERSION || PSXPC_TEST
#include <stdint.h>
#endif
#if PSX_VERSION && !PSXPC_TEST
typedef unsigned int uintptr_t;
#endif
void S_MemSet(char* p, int value, int length)
{
int size;
if (length != 0)
{
if (length > 3)
{
value |= value << 8;
value |= value << 16;
if (((uintptr_t)p) & 3)
{
size = 4 - (((uintptr_t)p) & 3);
length -= 4 - (((uintptr_t)p) & 3);
//loc_5E918
while (size--)
*p++ = value;
}
//loc_5E928
size = length >> 2;
if ((length >> 2))
{
length &= 3;
//loc_5E934
while (size--)
{
((int*)p)[0] = value;
p += 4;
}
}
}
//loc_5E94C
while (length-- != 0)
*p++ = value;
}
}
void S_LongMemCpy(unsigned long* pDest, unsigned long* pSrc, unsigned long size)//5E964(<), ? (F)
{
int i;
if (size > 0)
{
for (i = size / sizeof(unsigned long); i > 0; i--, pDest += 4, pSrc += 4)
{
//loc_5E974
pDest[0] = pSrc[0];
pDest[1] = pSrc[1];
pDest[2] = pSrc[2];
pDest[3] = pSrc[3];
}
//loc_5E9AC
for (i = size & 3; i > 0; i--)
{
*pDest++ = *pSrc++;
}
}
}
void DrawF4(unsigned short x, unsigned short y, unsigned short w, unsigned short h, int unk, int unk2)//5EDF8
{
UNIMPLEMENTED();
}
void DrawTPage(unsigned char a0, unsigned char a1)//5EE78(<), 5FB58(<)
{
UNIMPLEMENTED();
}
void DrawLineH(long a0, long a1, long a2, long a3, long a4, long a5)//5EECC(<)
{
UNIMPLEMENTED();
}
void DrawLineV(long a0, long a1, long a2, long a3, long a4, long a5)//5EF84(<),
{
UNIMPLEMENTED();
}
void LOAD_VSyncHandler()//5F074(<), 5FD54(<) (F)
{
int a0, a1, a2;
if (!LtLoadingBarEnabled)
{
return;
}
//loc_5F08C
GPU_BeginScene();
a0 = 440;//x?
a1 = 200;//y?
a2 = 64;//cd width or height?
if (_first_time_ever)
{
a0 += 24;
a1 += 8;
a2 = 48;
}
//loc_5F0B4
//PrintString(256, 192, 2, "Load Game", 0x8000);
draw_rotate_sprite(a0, a1, a2);
db.current_buffer ^= 1;
GnLastFrameCount = 0;
DrawOTagEnv(&db.ot[db.nOTSize - 1], &db.draw[0]);
return;
}
void LOAD_DrawEnable(unsigned char isEnabled)//5F2C8, 5FFA8
{
LtLoadingBarEnabled = isEnabled;
}
void GPU_BeginScene()//5F0F0(<), 5FDD0(<)
{
db.ot = db.order_table[db.current_buffer];
db.polyptr = (char*)db.poly_buffer[db.current_buffer];
db.curpolybuf = (char*)db.poly_buffer[db.current_buffer];
db.polybuf_limit = (char*)(db.poly_buffer[db.current_buffer]) + 26000;
db.pickup_ot = db.pickup_order_table[db.current_buffer];
ClearOTagR(db.order_table[db.current_buffer], db.nOTSize);
Emulator_BeginScene();
}
void draw_rotate_sprite(long a0, long a1, long a2)//5F134, 5FE14 (F)
{
long t0;
short* r_cossinptr;
long t6;
long t5;
long t1;
long t4;
DelRotAng = (DelRotAng - 52) & 0xFFF;
r_cossinptr = &rcossin_tbl[DelRotAng * 2];
t6 = ((-a2 / 2) * r_cossinptr[0]) / 4096;
t5 = ((-a2 / 2) * r_cossinptr[1]) / 4096;
*(long*) &db.polyptr[4] = 0x2C808080;
*(long*) &db.polyptr[12] = 0;
*(long*) &db.polyptr[20] = 0x1303F00;
t0 = t6 - t5;
a2 = -t6;
t4 = a2 - t5;
a2 += t5;
t1 = t6 + t5;
*(short*) &db.polyptr[8] = t0 + (t0 / 2) + a0;
*(short*) &db.polyptr[10] = t5 + t6 + a1;
*(short*) &db.polyptr[16] = t4 + (t4 / 2) + a0;
*(short*) &db.polyptr[18] = -t5 + t6 + a1;
*(short*) &db.polyptr[24] = t1 + (t1 / 2) + a0;
*(short*) &db.polyptr[26] = (t5 - t6) + a1;
*(short*) &db.polyptr[28] = 0x3F;//width/height of loading cd?
*(short*) &db.polyptr[36] = 0x3F3F;
*(short*) &db.polyptr[32] = a2 + (a2 / 2) + a0;
*(short*) &db.polyptr[34] = a1 + (-t5 - t6);
*(long*) &db.polyptr[0] = db.ot[0] | 0x09000000;
db.ot[0] = (unsigned long)&db.polyptr[0];
db.polyptr += 0x28;//sizeof(POLY_F3); * 2?
*(long*) &db.polyptr[4] = 0x2C808080;
*(long*) &db.polyptr[8] = 0x780100;
*(long*) &db.polyptr[12] = 0x6800;
*(long*) &db.polyptr[16] = 0x7801FF;
*(long*) &db.polyptr[20] = 0x13468FF;
*(long*) &db.polyptr[24] = 0xEF0100;
*(short*) &db.polyptr[28] = 0xDF00;
*(long*) &db.polyptr[32] = 0xEF01FF;
*(short*) &db.polyptr[36] = 0xDFFF;
*(long*) &db.polyptr[0] = db.ot[0] | 0x9000000;
db.ot[0] = (unsigned long)db.polyptr;
//sizeof(POLY_G3);
db.polyptr += 0x28;
return;
}
/* PSX VRAM (H)
* ----------- 1024px
* | TL | TR | |
* ----------- v
* | BL | BR |
* -----------
*(W)1024px-->
*
*/
void GPU_ClearVRAM()//5F2D0(<), 5FFB0(<) (F) (D) (ND)
{
RECT16 r;
//Clear TL
r.x = 0;
r.y = 0;
r.w = 512;
r.h = 256;
clear_a_rect(&r);
//Clear BL
r.y = 256;
clear_a_rect(&r);
//Clear BR
r.x = 512;
clear_a_rect(&r);
//Clear TR
r.y = 0;
clear_a_rect(&r);
return;
}
void clear_a_rect(RECT16* r)//5F334(<), 60014(<) (F) (D) (ND)
{
ClearImage(r, 0, 48, 0);
return;
}
void GPU_GetScreenPosition(short* x, short* y)//5F34C, ? (*) (F) (D) (ND)
{
*x = db.disp[0].screen.x;
*y = db.disp[0].screen.y;
return;
}
void GPU_SetScreenPosition(short x, short y)//5F360(<), 60040(<)
{
db.disp[0].screen.x = x;
db.disp[0].screen.y = y;
db.disp[1].screen.x = x;
db.disp[1].screen.y = y;
return;
}
void GPU_SyncBothScreens()//5F374(<), 60054(<)
{
db.current_buffer ^= 1;
if (db.current_buffer != 0)
{
//MoveImage(&db.disp[1].disp, db.disp[0].disp.x, db.disp[0].disp.y);
//TODO: Verify ra += 0x10;! prolly else skip loc_5F3A8 (implemented but should be checked).
}
else
{
//loc_5F3A8
//MoveImage(&db.disp[0].disp, db.disp[1].disp.x, db.disp[1].disp.y);
}
return;
}
///@Gh0stblade - Not sure why this is so unoptimal, we can basically &disp[db.current_buffer]... double check code.
void GPU_FlipToBuffer(int buffer_index)//5F3C8(<), 600A8(<) (F) (D) (ND)
{
DrawSync(0);
VSync(0);
if (buffer_index & 1)
{
PutDispEnv(&db.disp[1]);
}
else
{
PutDispEnv(&db.disp[0]);
}
if (buffer_index & 1)
{
PutDrawEnv(&db.draw[1]);
}
else
{
PutDrawEnv(&db.draw[0]);
}
db.current_buffer = buffer_index & 1 ^ 1;
return;
}
void S_AnimateTextures(long nFrames)
{
UNIMPLEMENTED();
}
void PrintGauge(int x, int y, int length)
{
UNIMPLEMENTED();
}
long GetRandomControl()//5E9F0, 926F8 (F)
{
rand_1 = (rand_1 * 0x41C64E6D) + 0x3039;
return (rand_1 >> 16) & 0x7FFF;
}
void SeedRandomControl(long seed)//(F)
{
rand_1 = seed;
}
long GetRandomDraw()//5EA18, 5F6F8 (F)
{
rand_2 = (rand_2 * 0x41C64E6D) + 0x3039;
return (rand_2 >> 16) * 0x7FFF;
}
void SeedRandomDraw(long seed)//(F)
{
rand_2 = seed;
}
void S_MemCpy(char* pSrc, char* pDest, int size)
{
if (size > 0)
{
while (size-- > 0)
*pSrc++ = *pDest++;
}
}
<commit_msg>Patches for GPU_SyncBothScreens<commit_after>#include "MISC.H"
#include "CONTROL.H"
#include "CAMERA.H"
#include "GPU.H"
#include "LOAD_LEV.H"
#include "SPECIFIC.H"
#include "TEXT_S.H"
#include <EMULATOR.H>
#include <LIBETC.H>
#if PSXPC_VERSION || PSXPC_TEST
#include <stdint.h>
#endif
#if PSX_VERSION && !PSXPC_TEST
typedef unsigned int uintptr_t;
#endif
void S_MemSet(char* p, int value, int length)
{
int size;
if (length != 0)
{
if (length > 3)
{
value |= value << 8;
value |= value << 16;
if (((uintptr_t)p) & 3)
{
size = 4 - (((uintptr_t)p) & 3);
length -= 4 - (((uintptr_t)p) & 3);
//loc_5E918
while (size--)
*p++ = value;
}
//loc_5E928
size = length >> 2;
if ((length >> 2))
{
length &= 3;
//loc_5E934
while (size--)
{
((int*)p)[0] = value;
p += 4;
}
}
}
//loc_5E94C
while (length-- != 0)
*p++ = value;
}
}
void S_LongMemCpy(unsigned long* pDest, unsigned long* pSrc, unsigned long size)//5E964(<), ? (F)
{
int i;
if (size > 0)
{
for (i = size / sizeof(unsigned long); i > 0; i--, pDest += 4, pSrc += 4)
{
//loc_5E974
pDest[0] = pSrc[0];
pDest[1] = pSrc[1];
pDest[2] = pSrc[2];
pDest[3] = pSrc[3];
}
//loc_5E9AC
for (i = size & 3; i > 0; i--)
{
*pDest++ = *pSrc++;
}
}
}
void DrawF4(unsigned short x, unsigned short y, unsigned short w, unsigned short h, int unk, int unk2)//5EDF8
{
UNIMPLEMENTED();
}
void DrawTPage(unsigned char a0, unsigned char a1)//5EE78(<), 5FB58(<)
{
UNIMPLEMENTED();
}
void DrawLineH(long a0, long a1, long a2, long a3, long a4, long a5)//5EECC(<)
{
UNIMPLEMENTED();
}
void DrawLineV(long a0, long a1, long a2, long a3, long a4, long a5)//5EF84(<),
{
UNIMPLEMENTED();
}
void LOAD_VSyncHandler()//5F074(<), 5FD54(<) (F)
{
int a0, a1, a2;
if (!LtLoadingBarEnabled)
{
return;
}
//loc_5F08C
GPU_BeginScene();
a0 = 440;//x?
a1 = 200;//y?
a2 = 64;//cd width or height?
if (_first_time_ever)
{
a0 += 24;
a1 += 8;
a2 = 48;
}
//loc_5F0B4
draw_rotate_sprite(a0, a1, a2);
db.current_buffer ^= 1;
GnLastFrameCount = 0;
DrawOTagEnv(&db.ot[db.nOTSize - 1], &db.draw[0]);
return;
}
void LOAD_DrawEnable(unsigned char isEnabled)//5F2C8, 5FFA8
{
LtLoadingBarEnabled = isEnabled;
}
void GPU_BeginScene()//5F0F0(<), 5FDD0(<)
{
db.ot = db.order_table[db.current_buffer];
db.polyptr = (char*)db.poly_buffer[db.current_buffer];
db.curpolybuf = (char*)db.poly_buffer[db.current_buffer];
db.polybuf_limit = (char*)(db.poly_buffer[db.current_buffer] + 26000);
db.pickup_ot = db.pickup_order_table[db.current_buffer];
ClearOTagR(db.order_table[db.current_buffer], db.nOTSize);
Emulator_BeginScene();
}
void draw_rotate_sprite(long a0, long a1, long a2)//5F134, 5FE14 (F)
{
long t0;
short* r_cossinptr;
long t6;
long t5;
long t1;
long t4;
DelRotAng = (DelRotAng - 52) & 0xFFF;
r_cossinptr = &rcossin_tbl[DelRotAng * 2];
t6 = ((-a2 / 2) * r_cossinptr[0]) / 4096;
t5 = ((-a2 / 2) * r_cossinptr[1]) / 4096;
*(long*) &db.polyptr[4] = 0x2C808080;
*(long*) &db.polyptr[12] = 0;
*(long*) &db.polyptr[20] = 0x1303F00;
t0 = t6 - t5;
a2 = -t6;
t4 = a2 - t5;
a2 += t5;
t1 = t6 + t5;
*(short*) &db.polyptr[8] = t0 + (t0 / 2) + a0;
*(short*) &db.polyptr[10] = t5 + t6 + a1;
*(short*) &db.polyptr[16] = t4 + (t4 / 2) + a0;
*(short*) &db.polyptr[18] = -t5 + t6 + a1;
*(short*) &db.polyptr[24] = t1 + (t1 / 2) + a0;
*(short*) &db.polyptr[26] = (t5 - t6) + a1;
*(short*) &db.polyptr[28] = 0x3F;//width/height of loading cd?
*(short*) &db.polyptr[36] = 0x3F3F;
*(short*) &db.polyptr[32] = a2 + (a2 / 2) + a0;
*(short*) &db.polyptr[34] = a1 + (-t5 - t6);
*(long*) &db.polyptr[0] = db.ot[0] | 0x09000000;
db.ot[0] = (unsigned long)&db.polyptr[0];
db.polyptr += 0x28;//sizeof(POLY_F3); * 2?
*(long*) &db.polyptr[4] = 0x2C808080;
*(long*) &db.polyptr[8] = 0x780100;
*(long*) &db.polyptr[12] = 0x6800;
*(long*) &db.polyptr[16] = 0x7801FF;
*(long*) &db.polyptr[20] = 0x13468FF;
*(long*) &db.polyptr[24] = 0xEF0100;
*(short*) &db.polyptr[28] = 0xDF00;
*(long*) &db.polyptr[32] = 0xEF01FF;
*(short*) &db.polyptr[36] = 0xDFFF;
*(long*) &db.polyptr[0] = db.ot[0] | 0x9000000;
db.ot[0] = (unsigned long)db.polyptr;
//sizeof(POLY_G3);
db.polyptr += 0x28;
return;
}
/* PSX VRAM (H)
* ----------- 1024px
* | TL | TR | |
* ----------- v
* | BL | BR |
* -----------
*(W)1024px-->
*
*/
void GPU_ClearVRAM()//5F2D0(<), 5FFB0(<) (F) (D) (ND)
{
RECT16 r;
//Clear TL
r.x = 0;
r.y = 0;
r.w = 512;
r.h = 256;
clear_a_rect(&r);
//Clear BL
r.y = 256;
clear_a_rect(&r);
//Clear BR
r.x = 512;
clear_a_rect(&r);
//Clear TR
r.y = 0;
clear_a_rect(&r);
return;
}
void clear_a_rect(RECT16* r)//5F334(<), 60014(<) (F) (D) (ND)
{
ClearImage(r, 0, 48, 0);
return;
}
void GPU_GetScreenPosition(short* x, short* y)//5F34C, ? (*) (F) (D) (ND)
{
*x = db.disp[0].screen.x;
*y = db.disp[0].screen.y;
return;
}
void GPU_SetScreenPosition(short x, short y)//5F360(<), 60040(<)
{
db.disp[0].screen.x = x;
db.disp[0].screen.y = y;
db.disp[1].screen.x = x;
db.disp[1].screen.y = y;
return;
}
void GPU_SyncBothScreens()//5F374(<), 60054(<)
{
DrawSync(0);
db.current_buffer ^= 1;
if (db.current_buffer != 0)
{
MoveImage(&db.disp[1].disp, db.disp[0].disp.x, db.disp[0].disp.y);
}
else
{
//loc_5F3A8
MoveImage(&db.disp[0].disp, db.disp[1].disp.x, db.disp[1].disp.y);
}
DrawSync(0);
return;
}
///@Gh0stblade - Not sure why this is so unoptimal, we can basically &disp[db.current_buffer]... double check code.
void GPU_FlipToBuffer(int buffer_index)//5F3C8(<), 600A8(<) (F) (D) (ND)
{
DrawSync(0);
VSync(0);
if (buffer_index & 1)
{
PutDispEnv(&db.disp[1]);
}
else
{
PutDispEnv(&db.disp[0]);
}
if (buffer_index & 1)
{
PutDrawEnv(&db.draw[1]);
}
else
{
PutDrawEnv(&db.draw[0]);
}
db.current_buffer = buffer_index & 1 ^ 1;
return;
}
void S_AnimateTextures(long nFrames)
{
UNIMPLEMENTED();
}
void PrintGauge(int x, int y, int length)
{
UNIMPLEMENTED();
}
long GetRandomControl()//5E9F0, 926F8 (F)
{
rand_1 = (rand_1 * 0x41C64E6D) + 0x3039;
return (rand_1 >> 16) & 0x7FFF;
}
void SeedRandomControl(long seed)//(F)
{
rand_1 = seed;
}
long GetRandomDraw()//5EA18, 5F6F8 (F)
{
rand_2 = (rand_2 * 0x41C64E6D) + 0x3039;
return (rand_2 >> 16) * 0x7FFF;
}
void SeedRandomDraw(long seed)//(F)
{
rand_2 = seed;
}
void S_MemCpy(char* pSrc, char* pDest, int size)
{
if (size > 0)
{
while (size-- > 0)
*pSrc++ = *pDest++;
}
}
<|endoftext|>
|
<commit_before><commit_msg>(IMU main): fix IMU example by increasing IMU task stack depth<commit_after><|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 "chrome/browser/extensions/api/permissions/permissions_api.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_prefs.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension_permission_set.h"
#include "net/base/mock_host_resolver.h"
namespace {
static void AddPattern(URLPatternSet* extent, const std::string& pattern) {
int schemes = URLPattern::SCHEME_ALL;
extent->AddPattern(URLPattern(schemes, pattern));
}
} // namespace
class ExperimentalApiTest : public ExtensionApiTest {
public:
void SetUpCommandLine(CommandLine* command_line) {
ExtensionApiTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
}
};
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, PermissionsFail) {
ASSERT_TRUE(RunExtensionTest("permissions/disabled")) << message_;
// Since the experimental APIs require a flag, this will fail even though
// it's enabled.
// TODO(erikkay) This test is currently broken because LoadExtension in
// ExtensionBrowserTest doesn't actually fail, it just times out. To fix this
// I'll need to add an EXTENSION_LOAD_ERROR notification, which is probably
// too much for the branch. I'll enable this on trunk later.
//ASSERT_FALSE(RunExtensionTest("permissions/enabled"))) << message_;
}
IN_PROC_BROWSER_TEST_F(ExperimentalApiTest, PermissionsSucceed) {
ASSERT_TRUE(RunExtensionTest("permissions/enabled")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ExperimentalPermissionsFail) {
// At the time this test is being created, there is no experimental
// function that will not be graduating soon, and does not require a
// tab id as an argument. So, we need the tab permission to get
// a tab id.
ASSERT_TRUE(RunExtensionTest("permissions/experimental_disabled"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FaviconPermission) {
ASSERT_TRUE(RunExtensionTest("permissions/favicon")) << message_;
}
// Test functions and APIs that are always allowed (even if you ask for no
// permissions).
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, AlwaysAllowed) {
ASSERT_TRUE(RunExtensionTest("permissions/always_allowed")) << message_;
}
// Tests that the optional permissions API works correctly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsGranted) {
// Mark all the tested APIs as granted to bypass the confirmation UI.
ExtensionAPIPermissionSet apis;
apis.insert(ExtensionAPIPermission::kTab);
URLPatternSet explicit_hosts;
AddPattern(&explicit_hosts, "http://*.c.com/*");
scoped_refptr<ExtensionPermissionSet> granted_permissions =
new ExtensionPermissionSet(apis, explicit_hosts, URLPatternSet());
ExtensionPrefs* prefs =
browser()->profile()->GetExtensionService()->extension_prefs();
prefs->AddGrantedPermissions("kjmkgkdkpedkejedfhmfcenooemhbpbo",
granted_permissions);
RequestPermissionsFunction::SetIgnoreUserGestureForTests(true);
host_resolver()->AddRule("*.com", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
EXPECT_TRUE(RunExtensionTest("permissions/optional")) << message_;
}
// Tests that the optional permissions API works correctly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsAutoConfirm) {
// Rather than setting the granted permissions, set the UI autoconfirm flag
// and run the same tests.
RequestPermissionsFunction::SetAutoConfirmForTests(true);
RequestPermissionsFunction::SetIgnoreUserGestureForTests(true);
host_resolver()->AddRule("*.com", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
EXPECT_TRUE(RunExtensionTest("permissions/optional")) << message_;
}
// Test that denying the optional permissions confirmation dialog works.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsDeny) {
RequestPermissionsFunction::SetAutoConfirmForTests(false);
RequestPermissionsFunction::SetIgnoreUserGestureForTests(true);
host_resolver()->AddRule("*.com", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
EXPECT_TRUE(RunExtensionTest("permissions/optional_deny")) << message_;
}
// Tests that the permissions.request function must be called from within a
// user gesture.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsGesture) {
RequestPermissionsFunction::SetIgnoreUserGestureForTests(false);
host_resolver()->AddRule("*.com", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
EXPECT_TRUE(RunExtensionTest("permissions/optional_gesture")) << message_;
}
<commit_msg>Disable ExtensionApiTest.AlwaysAllowed (crashes on Mac)<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 "chrome/browser/extensions/api/permissions/permissions_api.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_prefs.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension_permission_set.h"
#include "net/base/mock_host_resolver.h"
namespace {
static void AddPattern(URLPatternSet* extent, const std::string& pattern) {
int schemes = URLPattern::SCHEME_ALL;
extent->AddPattern(URLPattern(schemes, pattern));
}
} // namespace
class ExperimentalApiTest : public ExtensionApiTest {
public:
void SetUpCommandLine(CommandLine* command_line) {
ExtensionApiTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
}
};
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, PermissionsFail) {
ASSERT_TRUE(RunExtensionTest("permissions/disabled")) << message_;
// Since the experimental APIs require a flag, this will fail even though
// it's enabled.
// TODO(erikkay) This test is currently broken because LoadExtension in
// ExtensionBrowserTest doesn't actually fail, it just times out. To fix this
// I'll need to add an EXTENSION_LOAD_ERROR notification, which is probably
// too much for the branch. I'll enable this on trunk later.
//ASSERT_FALSE(RunExtensionTest("permissions/enabled"))) << message_;
}
IN_PROC_BROWSER_TEST_F(ExperimentalApiTest, PermissionsSucceed) {
ASSERT_TRUE(RunExtensionTest("permissions/enabled")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ExperimentalPermissionsFail) {
// At the time this test is being created, there is no experimental
// function that will not be graduating soon, and does not require a
// tab id as an argument. So, we need the tab permission to get
// a tab id.
ASSERT_TRUE(RunExtensionTest("permissions/experimental_disabled"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FaviconPermission) {
ASSERT_TRUE(RunExtensionTest("permissions/favicon")) << message_;
}
// Test functions and APIs that are always allowed (even if you ask for no
// permissions).
// Disabled: http://crbug.com/125193
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_AlwaysAllowed) {
ASSERT_TRUE(RunExtensionTest("permissions/always_allowed")) << message_;
}
// Tests that the optional permissions API works correctly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsGranted) {
// Mark all the tested APIs as granted to bypass the confirmation UI.
ExtensionAPIPermissionSet apis;
apis.insert(ExtensionAPIPermission::kTab);
URLPatternSet explicit_hosts;
AddPattern(&explicit_hosts, "http://*.c.com/*");
scoped_refptr<ExtensionPermissionSet> granted_permissions =
new ExtensionPermissionSet(apis, explicit_hosts, URLPatternSet());
ExtensionPrefs* prefs =
browser()->profile()->GetExtensionService()->extension_prefs();
prefs->AddGrantedPermissions("kjmkgkdkpedkejedfhmfcenooemhbpbo",
granted_permissions);
RequestPermissionsFunction::SetIgnoreUserGestureForTests(true);
host_resolver()->AddRule("*.com", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
EXPECT_TRUE(RunExtensionTest("permissions/optional")) << message_;
}
// Tests that the optional permissions API works correctly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsAutoConfirm) {
// Rather than setting the granted permissions, set the UI autoconfirm flag
// and run the same tests.
RequestPermissionsFunction::SetAutoConfirmForTests(true);
RequestPermissionsFunction::SetIgnoreUserGestureForTests(true);
host_resolver()->AddRule("*.com", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
EXPECT_TRUE(RunExtensionTest("permissions/optional")) << message_;
}
// Test that denying the optional permissions confirmation dialog works.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsDeny) {
RequestPermissionsFunction::SetAutoConfirmForTests(false);
RequestPermissionsFunction::SetIgnoreUserGestureForTests(true);
host_resolver()->AddRule("*.com", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
EXPECT_TRUE(RunExtensionTest("permissions/optional_deny")) << message_;
}
// Tests that the permissions.request function must be called from within a
// user gesture.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsGesture) {
RequestPermissionsFunction::SetIgnoreUserGestureForTests(false);
host_resolver()->AddRule("*.com", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
EXPECT_TRUE(RunExtensionTest("permissions/optional_gesture")) << message_;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: b3dentty.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2007-04-11 20:32:22 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _B3D_B3DENTITY_HXX
#define _B3D_B3DENTITY_HXX
#ifndef _B3D_B3DCOLOR_HXX
#include <goodies/b3dcolor.hxx>
#endif
#ifndef _B3D_BUCKET_HXX
#include <goodies/bucket.hxx>
#endif
#ifndef _BGFX_POINT_B3DPOINT_HXX
#include <basegfx/point/b3dpoint.hxx>
#endif
#ifndef _BGFX_POINT_B2DPOINT_HXX
#include <basegfx/point/b2dpoint.hxx>
#endif
#ifndef _BGFX_VECTOR_B3DVECTOR_HXX
#include <basegfx/vector/b3dvector.hxx>
#endif
/*************************************************************************
|*
|* Merkt sich einen Punkt plus Normale plus Texturkoordinate
|* (in Zukunft noch weitere Attribute, bsp. Farbe, Kante, Linienmodus
|*
\************************************************************************/
// predeclarations
class B3dTransformationSet;
namespace basegfx
{
class B3DHomMatrix;
} // end of namespace basegfx
class B3dEntity
{
private:
// Data defining this point, it's normal and texture coordinates
basegfx::B3DPoint maPoint;
basegfx::B3DVector maNormal;
basegfx::B3DVector maPlaneNormal;
basegfx::B2DPoint maTexCoor;
B3dColor maColor;
// Ist die diesem Punkt folgende Kante sichtbar ?
// EdgeFlag bool NOT in bitfield to be able to access it from OpenGL driver
sal_uInt8 mbEdgeFlag;
// bitfield
// Gueltigkeit der geometrischen Daten
unsigned mbValid : 1;
// Wird eine Normale verwendet ?
unsigned mbNormalUsed : 1;
// Wird eine Texturkoordinate verwendet ?
unsigned mbTexCoorUsed : 1;
// Sind die geometrischen Daten schon in DeviceKoordinaten
// umgerechnet ?
unsigned mbDeviceCoor : 1;
public:
B3dEntity() { Reset(); }
sal_Bool IsValid() const { return mbValid; }
void SetValid(sal_Bool bNew=sal_True) { mbValid = bNew; }
sal_Bool IsNormalUsed() const { return mbNormalUsed; }
void SetNormalUsed(sal_Bool bNew=sal_True) { mbNormalUsed = bNew; }
sal_Bool IsTexCoorUsed() const { return mbTexCoorUsed; }
void SetTexCoorUsed(sal_Bool bNew=sal_True) { mbTexCoorUsed = bNew; }
sal_Bool IsDeviceCoor() const { return mbDeviceCoor; }
void SetDeviceCoor(sal_Bool bNew=sal_True) { mbDeviceCoor = bNew; }
sal_Bool IsEdgeVisible() const { return mbEdgeFlag; }
void SetEdgeVisible(sal_Bool bNew=sal_True) { mbEdgeFlag = bNew; }
basegfx::B3DPoint& Point() { return maPoint; }
const basegfx::B3DPoint& Point() const { return maPoint; }
basegfx::B3DVector& Normal() { return maNormal; }
const basegfx::B3DVector& Normal() const { return maNormal; }
basegfx::B3DVector& PlaneNormal() { return maPlaneNormal; }
const basegfx::B3DVector& PlaneNormal() const { return maPlaneNormal; }
basegfx::B2DPoint& TexCoor() { return maTexCoor; }
const basegfx::B2DPoint& TexCoor() const { return maTexCoor; }
B3dColor& Color() { return maColor; }
const B3dColor& Color() const { return maColor; }
sal_uInt8& EdgeFlag() { return mbEdgeFlag; }
const sal_uInt8& EdgeFlag() const { return mbEdgeFlag; }
double GetX() const { return maPoint.getX(); }
void SetX(double fNew) { maPoint.setX(fNew); }
double GetY() const { return maPoint.getY(); }
void SetY(double fNew) { maPoint.setY(fNew); }
double GetZ() const { return maPoint.getZ(); }
void SetZ(double fNew) { maPoint.setZ(fNew); }
void Reset();
void Copy(B3dEntity& rEnt);
void ToDeviceCoor(B3dTransformationSet* pSet)
{ if(!IsDeviceCoor()) ImplToDeviceCoor(pSet); }
void To3DCoor(B3dTransformationSet* pSet)
{ if(IsDeviceCoor()) ImplTo3DCoor(pSet); }
void ForceEqualBase(B3dTransformationSet* pSet, B3dEntity& rOld);
void ForceEqualBase(B3dTransformationSet* pSet, B3dEntity& rOld1,
B3dEntity& rOld2);
void CalcInBetween(B3dEntity& rOld1,
B3dEntity& rOld2, double t);
void CalcMiddle(B3dEntity& rOld1,
B3dEntity& rOld2);
void CalcMiddle(B3dEntity& rOld1,
B3dEntity& rOld2, B3dEntity& rOld3);
// Eine beliebige Transformation auf die Geometrie anwenden
void Transform(const basegfx::B3DHomMatrix& rMat);
protected:
void ImplToDeviceCoor(B3dTransformationSet* pSet);
void ImplTo3DCoor(B3dTransformationSet* pSet);
};
/*************************************************************************
|*
|* Bucket fuer geometrische Daten
|*
\************************************************************************/
BASE3D_DECL_BUCKET(B3dEntity, Bucket)
#endif // _B3D_B3DENTITY_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.2.86); FILE MERGED 2008/04/01 15:19:26 thb 1.2.86.3: #i85898# Stripping all external header guards 2008/04/01 12:31:02 thb 1.2.86.2: #i85898# Stripping all external header guards 2008/03/31 13:39:30 rt 1.2.86.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: b3dentty.hxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _B3D_B3DENTITY_HXX
#define _B3D_B3DENTITY_HXX
#include <goodies/b3dcolor.hxx>
#include <goodies/bucket.hxx>
#include <basegfx/point/b3dpoint.hxx>
#include <basegfx/point/b2dpoint.hxx>
#include <basegfx/vector/b3dvector.hxx>
/*************************************************************************
|*
|* Merkt sich einen Punkt plus Normale plus Texturkoordinate
|* (in Zukunft noch weitere Attribute, bsp. Farbe, Kante, Linienmodus
|*
\************************************************************************/
// predeclarations
class B3dTransformationSet;
namespace basegfx
{
class B3DHomMatrix;
} // end of namespace basegfx
class B3dEntity
{
private:
// Data defining this point, it's normal and texture coordinates
basegfx::B3DPoint maPoint;
basegfx::B3DVector maNormal;
basegfx::B3DVector maPlaneNormal;
basegfx::B2DPoint maTexCoor;
B3dColor maColor;
// Ist die diesem Punkt folgende Kante sichtbar ?
// EdgeFlag bool NOT in bitfield to be able to access it from OpenGL driver
sal_uInt8 mbEdgeFlag;
// bitfield
// Gueltigkeit der geometrischen Daten
unsigned mbValid : 1;
// Wird eine Normale verwendet ?
unsigned mbNormalUsed : 1;
// Wird eine Texturkoordinate verwendet ?
unsigned mbTexCoorUsed : 1;
// Sind die geometrischen Daten schon in DeviceKoordinaten
// umgerechnet ?
unsigned mbDeviceCoor : 1;
public:
B3dEntity() { Reset(); }
sal_Bool IsValid() const { return mbValid; }
void SetValid(sal_Bool bNew=sal_True) { mbValid = bNew; }
sal_Bool IsNormalUsed() const { return mbNormalUsed; }
void SetNormalUsed(sal_Bool bNew=sal_True) { mbNormalUsed = bNew; }
sal_Bool IsTexCoorUsed() const { return mbTexCoorUsed; }
void SetTexCoorUsed(sal_Bool bNew=sal_True) { mbTexCoorUsed = bNew; }
sal_Bool IsDeviceCoor() const { return mbDeviceCoor; }
void SetDeviceCoor(sal_Bool bNew=sal_True) { mbDeviceCoor = bNew; }
sal_Bool IsEdgeVisible() const { return mbEdgeFlag; }
void SetEdgeVisible(sal_Bool bNew=sal_True) { mbEdgeFlag = bNew; }
basegfx::B3DPoint& Point() { return maPoint; }
const basegfx::B3DPoint& Point() const { return maPoint; }
basegfx::B3DVector& Normal() { return maNormal; }
const basegfx::B3DVector& Normal() const { return maNormal; }
basegfx::B3DVector& PlaneNormal() { return maPlaneNormal; }
const basegfx::B3DVector& PlaneNormal() const { return maPlaneNormal; }
basegfx::B2DPoint& TexCoor() { return maTexCoor; }
const basegfx::B2DPoint& TexCoor() const { return maTexCoor; }
B3dColor& Color() { return maColor; }
const B3dColor& Color() const { return maColor; }
sal_uInt8& EdgeFlag() { return mbEdgeFlag; }
const sal_uInt8& EdgeFlag() const { return mbEdgeFlag; }
double GetX() const { return maPoint.getX(); }
void SetX(double fNew) { maPoint.setX(fNew); }
double GetY() const { return maPoint.getY(); }
void SetY(double fNew) { maPoint.setY(fNew); }
double GetZ() const { return maPoint.getZ(); }
void SetZ(double fNew) { maPoint.setZ(fNew); }
void Reset();
void Copy(B3dEntity& rEnt);
void ToDeviceCoor(B3dTransformationSet* pSet)
{ if(!IsDeviceCoor()) ImplToDeviceCoor(pSet); }
void To3DCoor(B3dTransformationSet* pSet)
{ if(IsDeviceCoor()) ImplTo3DCoor(pSet); }
void ForceEqualBase(B3dTransformationSet* pSet, B3dEntity& rOld);
void ForceEqualBase(B3dTransformationSet* pSet, B3dEntity& rOld1,
B3dEntity& rOld2);
void CalcInBetween(B3dEntity& rOld1,
B3dEntity& rOld2, double t);
void CalcMiddle(B3dEntity& rOld1,
B3dEntity& rOld2);
void CalcMiddle(B3dEntity& rOld1,
B3dEntity& rOld2, B3dEntity& rOld3);
// Eine beliebige Transformation auf die Geometrie anwenden
void Transform(const basegfx::B3DHomMatrix& rMat);
protected:
void ImplToDeviceCoor(B3dTransformationSet* pSet);
void ImplTo3DCoor(B3dTransformationSet* pSet);
};
/*************************************************************************
|*
|* Bucket fuer geometrische Daten
|*
\************************************************************************/
BASE3D_DECL_BUCKET(B3dEntity, Bucket)
#endif // _B3D_B3DENTITY_HXX
<|endoftext|>
|
<commit_before><commit_msg>A few more helgrind cleanups (https://stroika.atlassian.net/browse/STK-471_<commit_after><|endoftext|>
|
<commit_before>#pragma ident "$Id$"
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// any later version.
//
// The GPSTk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
// release, distribution is unlimited.
//
//=============================================================================
/**
* @file TabularEphemerisStore.hpp
* Store a tabular list of Xvt data (such as a table of precise ephemeris data
* in an SP3 file) and compute Xvt from this table. A Lagrange interpolation
* is used to compute the Xvt for times that are not in the table but do have
* sufficient data.
*/
#ifndef GPSTK_TABULAR_EPHEMERIS_STORE_HPP
#define GPSTK_TABULAR_EPHEMERIS_STORE_HPP
#include <iostream>
#include "SatID.hpp"
#include "DayTime.hpp"
#include "XvtStore.hpp"
#include "SP3Data.hpp"
namespace gpstk
{
/** @addtogroup ephemstore */
//@{
/// Store a tabular list of Xvt data (such as a table of precise
/// ephemeris data in an SP3 file) and compute Xvt from this table.
/// A Lagrange interpolation is used to compute the Xvt for times that
/// are not in the table but do have sufficient data.
class TabularEphemerisStore : public XvtStore<SatID>
{
public:
/// Default constructor
TabularEphemerisStore()
throw()
: haveVelocity(true), initialTime(DayTime::END_OF_TIME),
finalTime(DayTime::BEGINNING_OF_TIME), checkDataGap(false),
gapInterval(901.0), checkInterval(false), maxInterval(8105.0)
{};
/// Destructor
virtual ~TabularEphemerisStore() {};
/** Returns the position, velocity, and clock offset of the indicated
* object in ECEF coordinates (meters) at the indicated time.
*
* @param[in] id the object's identifier
* @param[in] t the time to look up
*
* @return the Xvt of the object at the indicated time
*
* @throw InvalidRequest If the request can not be completed for any
* reason, this is thrown. The text may have additional
* information as to why the request failed.
*/
virtual Xvt getXvt( const SatID id,
const DayTime& t )
const throw(InvalidRequest);
/** Returns the acceleration of the indicated object in ECEF
* coordinates (meters) at the indicated time.
*
* @param[in] id the object's identifier
* @param[in] t the time to look up
*
* @return the Triple holding the acceleration of the object at the
* indicated time
*
* @throw InvalidRequest If the request can not be completed for any
* reason, this is thrown. The text may have additional
* information as to why the request failed.
*/
virtual Triple getAccel( const SatID id,
const DayTime& t )
const throw(InvalidRequest);
/** A debugging function that outputs in human readable form,
* all data stored in this object.
*
* @param[in] s the stream to receive the output; defaults to cout
* @param[in] detail the level of detail to provide
*/
virtual void dump( std::ostream& s = std::cout,
short detail = 0 )
const throw();
/** Edit the dataset, removing data outside the indicated time
* interval.
*
* @param[in] tmin defines the beginning of the time interval
* @param[in] tmax defines the end of the time interval
*/
virtual void edit( const DayTime& tmin,
const DayTime& tmax = DayTime(DayTime::END_OF_TIME) )
throw();
/** Determine the earliest time for which this object can successfully
* determine the Xvt for any object.
*
* @return The initial time
*
* @throw InvalidRequest This is thrown if the object has no data.
*/
virtual DayTime getInitialTime()
const throw(InvalidRequest)
{ return initialTime; };
/** Determine the latest time for which this object can successfully
* determine the Xvt for any object.
*
* @return The final time
*
* @throw InvalidRequest This is thrown if the object has no data.
*/
virtual DayTime getFinalTime()
const throw(InvalidRequest)
{ return finalTime; };
/// Check if this ephemeris contains velocity information in all
/// datasets loaded.
virtual bool velocityIsPresent()
const throw()
{ return haveVelocity; }
/// Check if this ephemeris contains clock information.
virtual bool clockIsPresent()
const throw()
{ return true; };
/// Get number of satellite maps
int nsats(void) throw() { return pe.size(); }
/// Get total number of ephemerides, all sats
int neph(void) throw() {
int n(0);
std::map<SatID, SvEphMap>::const_iterator it(pe.begin());
while(it != pe.end()) {
n += it->second.size();
++it;
}
return n;
}
//---------------------------------------------------------------
// Below are interfaces that are unique to this class (i.e. not
// in the parent class)
//---------------------------------------------------------------
/// Insert a new SP3Data object into the store
void addEphemeris(const SP3Data& data)
throw();
/// Remove all data
void clear() throw();
/// Enable checking of data gaps.
void enableDataGapCheck(void)
{ checkDataGap = true; };
/// Disable checking of data gaps.
void disableDataGapCheck(void)
{ checkDataGap = false; };
/// Get current gap interval.
double getGapInterval(void)
{ return gapInterval; };
/// Set gap interval.
void setGapInterval(double interval)
{ gapInterval = interval; return; };
/// Enable checking of maximum interval.
void enableIntervalCheck(void)
{ checkInterval = true; };
/// Disable checking of maximum interval.
void disableIntervalCheck(void)
{ checkInterval = false; };
/// Get current maximum interval.
double getMaxInterval(void)
{ return maxInterval; };
/// Set maximum interval.
void setMaxInterval(double interval)
{ maxInterval = interval; return; };
protected:
/// Flag indicating that velocity data present in all datasets loaded.
bool haveVelocity;
private:
/// The key to this map is the time
typedef std::map<DayTime, Xvt> SvEphMap;
/// The key to this map is the svid of the satellite (usually the prn)
typedef std::map<SatID, SvEphMap> EphMap;
/// the map of SVs and XVTs
EphMap pe;
/** These give the overall span of time for which this object
* contains data.
*
* NB there may be gaps in the data, i.e. the data may not be
* continuous.
*/
DayTime initialTime, finalTime;
/** Flag to check for data gaps.
*
* If this flag is enabled, data gaps wider than "gapInterval" will
* generate an "InvalidRequest" exception when using method "getXvt()".
*
* This flag is disabled by default.
*/
bool checkDataGap;
/** Maximum interval of time (in seconds) to declare a data gap.
*
* Recommended value is (SP3 sample period) + 1, in seconds, which
* means 900 s + 1 s = 901 s for a typical 15-minutes-per-sample
* SP3 file.
*
* This field is useful only if "checkDataGap" is enabled. Use method
* "enableDataGapCheck()" for this.
*/
double gapInterval;
/** Flag to check for interpolation interval.
*
* If this flag is enabled, interpolation intervals wider than
* "maxInterval" will generate an "InvalidRequest" exception when
* using method "getXvt()".
*
* This flag is disabled by default.
*/
bool checkInterval;
/** Maximum interval of time (in seconds) allowed to carry out the
* interpolation process.
*
* Recommended value is (10 - 1) * (SP3 sample period) + 5, in
* seconds, which means 8100 s + 5 s = 8105 s for a typical
* 15-minutes-per-sample SP3 file (please note that the order of the
* Lagrange interpolation is usually 10).
*
* This field is useful only if "checkInterval" is enabled. Use method
* "enableIntervalCheck()" for this.
*/
double maxInterval;
};
//@}
} // End of namespace gpstk
#endif // GPSTK_TABULAR_EPHEMERIS_STORE_HPP
<commit_msg>change the class members to 'protected' from 'private' to make inherited classes to access these members. a new class 'IGSEphemerisStore' to process igs sp3 and clk files will be implemented, and the getXvt() function can be rewritten to process daily data with daily ephemeris but not three days ephemeris<commit_after>#pragma ident "$Id$"
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// any later version.
//
// The GPSTk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
// release, distribution is unlimited.
//
//=============================================================================
/**
* @file TabularEphemerisStore.hpp
* Store a tabular list of Xvt data (such as a table of precise ephemeris data
* in an SP3 file) and compute Xvt from this table. A Lagrange interpolation
* is used to compute the Xvt for times that are not in the table but do have
* sufficient data.
*/
#ifndef GPSTK_TABULAR_EPHEMERIS_STORE_HPP
#define GPSTK_TABULAR_EPHEMERIS_STORE_HPP
#include <iostream>
#include "SatID.hpp"
#include "DayTime.hpp"
#include "XvtStore.hpp"
#include "SP3Data.hpp"
namespace gpstk
{
/** @addtogroup ephemstore */
//@{
/// Store a tabular list of Xvt data (such as a table of precise
/// ephemeris data in an SP3 file) and compute Xvt from this table.
/// A Lagrange interpolation is used to compute the Xvt for times that
/// are not in the table but do have sufficient data.
class TabularEphemerisStore : public XvtStore<SatID>
{
public:
/// Default constructor
TabularEphemerisStore()
throw()
: haveVelocity(true), initialTime(DayTime::END_OF_TIME),
finalTime(DayTime::BEGINNING_OF_TIME), checkDataGap(false),
gapInterval(901.0), checkInterval(false), maxInterval(8105.0)
{};
/// Destructor
virtual ~TabularEphemerisStore() {};
/** Returns the position, velocity, and clock offset of the indicated
* object in ECEF coordinates (meters) at the indicated time.
*
* @param[in] id the object's identifier
* @param[in] t the time to look up
*
* @return the Xvt of the object at the indicated time
*
* @throw InvalidRequest If the request can not be completed for any
* reason, this is thrown. The text may have additional
* information as to why the request failed.
*/
virtual Xvt getXvt( const SatID id,
const DayTime& t )
const throw(InvalidRequest);
/** Returns the acceleration of the indicated object in ECEF
* coordinates (meters) at the indicated time.
*
* @param[in] id the object's identifier
* @param[in] t the time to look up
*
* @return the Triple holding the acceleration of the object at the
* indicated time
*
* @throw InvalidRequest If the request can not be completed for any
* reason, this is thrown. The text may have additional
* information as to why the request failed.
*/
virtual Triple getAccel( const SatID id,
const DayTime& t )
const throw(InvalidRequest);
/** A debugging function that outputs in human readable form,
* all data stored in this object.
*
* @param[in] s the stream to receive the output; defaults to cout
* @param[in] detail the level of detail to provide
*/
virtual void dump( std::ostream& s = std::cout,
short detail = 0 )
const throw();
/** Edit the dataset, removing data outside the indicated time
* interval.
*
* @param[in] tmin defines the beginning of the time interval
* @param[in] tmax defines the end of the time interval
*/
virtual void edit( const DayTime& tmin,
const DayTime& tmax = DayTime(DayTime::END_OF_TIME) )
throw();
/** Determine the earliest time for which this object can successfully
* determine the Xvt for any object.
*
* @return The initial time
*
* @throw InvalidRequest This is thrown if the object has no data.
*/
virtual DayTime getInitialTime()
const throw(InvalidRequest)
{ return initialTime; };
/** Determine the latest time for which this object can successfully
* determine the Xvt for any object.
*
* @return The final time
*
* @throw InvalidRequest This is thrown if the object has no data.
*/
virtual DayTime getFinalTime()
const throw(InvalidRequest)
{ return finalTime; };
/// Check if this ephemeris contains velocity information in all
/// datasets loaded.
virtual bool velocityIsPresent()
const throw()
{ return haveVelocity; }
/// Check if this ephemeris contains clock information.
virtual bool clockIsPresent()
const throw()
{ return true; };
/// Get number of satellite maps
int nsats(void) throw() { return pe.size(); }
/// Get total number of ephemerides, all sats
int neph(void) throw() {
int n(0);
std::map<SatID, SvEphMap>::const_iterator it(pe.begin());
while(it != pe.end()) {
n += it->second.size();
++it;
}
return n;
}
//---------------------------------------------------------------
// Below are interfaces that are unique to this class (i.e. not
// in the parent class)
//---------------------------------------------------------------
/// Insert a new SP3Data object into the store
void addEphemeris(const SP3Data& data)
throw();
/// Remove all data
void clear() throw();
/// Enable checking of data gaps.
void enableDataGapCheck(void)
{ checkDataGap = true; };
/// Disable checking of data gaps.
void disableDataGapCheck(void)
{ checkDataGap = false; };
/// Get current gap interval.
double getGapInterval(void)
{ return gapInterval; };
/// Set gap interval.
void setGapInterval(double interval)
{ gapInterval = interval; return; };
/// Enable checking of maximum interval.
void enableIntervalCheck(void)
{ checkInterval = true; };
/// Disable checking of maximum interval.
void disableIntervalCheck(void)
{ checkInterval = false; };
/// Get current maximum interval.
double getMaxInterval(void)
{ return maxInterval; };
/// Set maximum interval.
void setMaxInterval(double interval)
{ maxInterval = interval; return; };
protected:
/// Flag indicating that velocity data present in all datasets loaded.
bool haveVelocity;
protected:
/// The key to this map is the time
typedef std::map<DayTime, Xvt> SvEphMap;
/// The key to this map is the svid of the satellite (usually the prn)
typedef std::map<SatID, SvEphMap> EphMap;
/// the map of SVs and XVTs
EphMap pe;
/** These give the overall span of time for which this object
* contains data.
*
* NB there may be gaps in the data, i.e. the data may not be
* continuous.
*/
DayTime initialTime, finalTime;
/** Flag to check for data gaps.
*
* If this flag is enabled, data gaps wider than "gapInterval" will
* generate an "InvalidRequest" exception when using method "getXvt()".
*
* This flag is disabled by default.
*/
bool checkDataGap;
/** Maximum interval of time (in seconds) to declare a data gap.
*
* Recommended value is (SP3 sample period) + 1, in seconds, which
* means 900 s + 1 s = 901 s for a typical 15-minutes-per-sample
* SP3 file.
*
* This field is useful only if "checkDataGap" is enabled. Use method
* "enableDataGapCheck()" for this.
*/
double gapInterval;
/** Flag to check for interpolation interval.
*
* If this flag is enabled, interpolation intervals wider than
* "maxInterval" will generate an "InvalidRequest" exception when
* using method "getXvt()".
*
* This flag is disabled by default.
*/
bool checkInterval;
/** Maximum interval of time (in seconds) allowed to carry out the
* interpolation process.
*
* Recommended value is (10 - 1) * (SP3 sample period) + 5, in
* seconds, which means 8100 s + 5 s = 8105 s for a typical
* 15-minutes-per-sample SP3 file (please note that the order of the
* Lagrange interpolation is usually 10).
*
* This field is useful only if "checkInterval" is enabled. Use method
* "enableIntervalCheck()" for this.
*/
double maxInterval;
};
//@}
} // End of namespace gpstk
#endif // GPSTK_TABULAR_EPHEMERIS_STORE_HPP
<|endoftext|>
|
<commit_before>//
//
// Description: This file is part of FET
//
//
// Author: Lalescu Liviu <Please see https://lalescu.ro/liviu/ for details about contacting Liviu Lalescu (in particular, you can find here the e-mail address)>
// Copyright (C) 2005 Liviu Lalescu <https://lalescu.ro/liviu/>
//
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#include "timetable_defs.h"
#include "timetable.h"
#include "fet.h"
#include "activitytagsform.h"
#include "studentsset.h"
#include "teacher.h"
#include "subject.h"
#include "activitytag.h"
#include <QInputDialog>
#include <QMessageBox>
#include <QListWidget>
#include <QAbstractItemView>
#include <QSplitter>
#include <QSettings>
#include <QObject>
#include <QMetaObject>
extern const QString COMPANY;
extern const QString PROGRAM;
ActivityTagsForm::ActivityTagsForm(QWidget* parent): QDialog(parent)
{
setupUi(this);
currentActivityTagTextEdit->setReadOnly(true);
renameActivityTagPushButton->setDefault(true);
activityTagsListWidget->setSelectionMode(QAbstractItemView::SingleSelection);
connect(closePushButton, SIGNAL(clicked()), this, SLOT(close()));
connect(addActivityTagPushButton, SIGNAL(clicked()), this, SLOT(addActivityTag()));
connect(removeActivityTagPushButton, SIGNAL(clicked()), this, SLOT(removeActivityTag()));
connect(renameActivityTagPushButton, SIGNAL(clicked()), this, SLOT(renameActivityTag()));
connect(moveActivityTagUpPushButton, SIGNAL(clicked()), this, SLOT(moveActivityTagUp()));
connect(moveActivityTagDownPushButton, SIGNAL(clicked()), this, SLOT(moveActivityTagDown()));
connect(sortActivityTagsPushButton, SIGNAL(clicked()), this, SLOT(sortActivityTags()));
connect(activityTagsListWidget, SIGNAL(currentRowChanged(int)), this, SLOT(activityTagChanged(int)));
connect(activateActivityTagPushButton, SIGNAL(clicked()), this, SLOT(activateActivityTag()));
connect(deactivateActivityTagPushButton, SIGNAL(clicked()), this, SLOT(deactivateActivityTag()));
connect(activityTagsListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(renameActivityTag()));
connect(helpPushButton, SIGNAL(clicked()), this, SLOT(help()));
connect(printablePushButton, SIGNAL(clicked()), this, SLOT(printableActivityTag()));
connect(notPrintablePushButton, SIGNAL(clicked()), this, SLOT(notPrintableActivityTag()));
connect(commentsPushButton, SIGNAL(clicked()), this, SLOT(comments()));
centerWidgetOnScreen(this);
restoreFETDialogGeometry(this);
//restore splitter state
QSettings settings(COMPANY, PROGRAM);
if(settings.contains(this->metaObject()->className()+QString("/splitter-state")))
splitter->restoreState(settings.value(this->metaObject()->className()+QString("/splitter-state")).toByteArray());
activityTagsListWidget->clear();
for(int i=0; i<gt.rules.activityTagsList.size(); i++){
ActivityTag* sbt=gt.rules.activityTagsList[i];
activityTagsListWidget->addItem(sbt->name);
}
if(activityTagsListWidget->count()>0)
activityTagsListWidget->setCurrentRow(0);
}
ActivityTagsForm::~ActivityTagsForm()
{
saveFETDialogGeometry(this);
//save splitter state
QSettings settings(COMPANY, PROGRAM);
settings.setValue(this->metaObject()->className()+QString("/splitter-state"), splitter->saveState());
}
void ActivityTagsForm::addActivityTag()
{
bool ok = false;
ActivityTag* sbt=new ActivityTag();
sbt->name = QInputDialog::getText( this, tr("Add activity tag"), tr("Please enter activity tag's name") ,
QLineEdit::Normal, QString(), &ok );
if ( ok && !((sbt->name).isEmpty()) ){
// user entered something and pressed OK
if(!gt.rules.addActivityTag(sbt)){
QMessageBox::information( this, tr("Activity tag insertion dialog"),
tr("Could not insert item. Must be a duplicate"));
delete sbt;
}
else{
activityTagsListWidget->addItem(sbt->name);
activityTagsListWidget->setCurrentRow(activityTagsListWidget->count()-1);
}
}
else{
if(ok){ //the user entered nothing
QMessageBox::information(this, tr("FET information"), tr("Incorrect name"));
}
delete sbt;// user entered nothing or pressed Cancel
}
}
void ActivityTagsForm::removeActivityTag()
{
int i=activityTagsListWidget->currentRow();
if(activityTagsListWidget->currentRow()<0){
QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
return;
}
QString text=activityTagsListWidget->currentItem()->text();
int activity_tag_ID=gt.rules.searchActivityTag(text);
if(activity_tag_ID<0){
QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
return;
}
if(QMessageBox::warning( this, tr("FET"),
tr("Are you sure you want to delete this activity tag?"),
tr("Yes"), tr("No"), 0, 0, 1 ) == 1)
return;
int tmp=gt.rules.removeActivityTag(text);
if(tmp){
activityTagsListWidget->setCurrentRow(-1);
QListWidgetItem* item;
item=activityTagsListWidget->takeItem(i);
delete item;
if(i>=activityTagsListWidget->count())
i=activityTagsListWidget->count()-1;
if(i>=0)
activityTagsListWidget->setCurrentRow(i);
else
currentActivityTagTextEdit->setPlainText(QString(""));
}
}
void ActivityTagsForm::renameActivityTag()
{
int i=activityTagsListWidget->currentRow();
if(activityTagsListWidget->currentRow()<0){
QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
return;
}
QString initialActivityTagName=activityTagsListWidget->currentItem()->text();
int activity_tag_ID=gt.rules.searchActivityTag(initialActivityTagName);
if(activity_tag_ID<0){
QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
return;
}
bool ok = false;
QString finalActivityTagName;
finalActivityTagName = QInputDialog::getText( this, tr("Rename activity tag"), tr("Please enter new activity tag's name") ,
QLineEdit::Normal, initialActivityTagName, &ok );
if ( ok && !(finalActivityTagName.isEmpty()) ){
// user entered something and pressed OK
if(gt.rules.searchActivityTag(finalActivityTagName)>=0){
QMessageBox::information( this, tr("Activity tag insertion dialog"),
tr("Could not modify item. New name must be a duplicate"));
}
else{
gt.rules.modifyActivityTag(initialActivityTagName, finalActivityTagName);
activityTagsListWidget->item(i)->setText(finalActivityTagName);
activityTagChanged(activityTagsListWidget->currentRow());
}
}
}
void ActivityTagsForm::moveActivityTagUp()
{
if(activityTagsListWidget->count()<=1)
return;
int i=activityTagsListWidget->currentRow();
if(i<0 || i>=activityTagsListWidget->count())
return;
if(i==0)
return;
QString s1=activityTagsListWidget->item(i)->text();
QString s2=activityTagsListWidget->item(i-1)->text();
ActivityTag* at1=gt.rules.activityTagsList.at(i);
ActivityTag* at2=gt.rules.activityTagsList.at(i-1);
gt.rules.internalStructureComputed=false;
setRulesModifiedAndOtherThings(>.rules);
activityTagsListWidget->item(i)->setText(s2);
activityTagsListWidget->item(i-1)->setText(s1);
gt.rules.activityTagsList[i]=at2;
gt.rules.activityTagsList[i-1]=at1;
activityTagsListWidget->setCurrentRow(i-1);
activityTagChanged(i-1);
}
void ActivityTagsForm::moveActivityTagDown()
{
if(activityTagsListWidget->count()<=1)
return;
int i=activityTagsListWidget->currentRow();
if(i<0 || i>=activityTagsListWidget->count())
return;
if(i==activityTagsListWidget->count()-1)
return;
QString s1=activityTagsListWidget->item(i)->text();
QString s2=activityTagsListWidget->item(i+1)->text();
ActivityTag* at1=gt.rules.activityTagsList.at(i);
ActivityTag* at2=gt.rules.activityTagsList.at(i+1);
gt.rules.internalStructureComputed=false;
setRulesModifiedAndOtherThings(>.rules);
activityTagsListWidget->item(i)->setText(s2);
activityTagsListWidget->item(i+1)->setText(s1);
gt.rules.activityTagsList[i]=at2;
gt.rules.activityTagsList[i+1]=at1;
activityTagsListWidget->setCurrentRow(i+1);
activityTagChanged(i+1);
}
void ActivityTagsForm::sortActivityTags()
{
gt.rules.sortActivityTagsAlphabetically();
activityTagsListWidget->clear();
for(int i=0; i<gt.rules.activityTagsList.size(); i++){
ActivityTag* sbt=gt.rules.activityTagsList[i];
activityTagsListWidget->addItem(sbt->name);
}
if(activityTagsListWidget->count()>0)
activityTagsListWidget->setCurrentRow(0);
}
void ActivityTagsForm::activityTagChanged(int index)
{
if(index<0){
currentActivityTagTextEdit->setPlainText(QString(""));
return;
}
ActivityTag* st=gt.rules.activityTagsList.at(index);
assert(st);
QString s=st->getDetailedDescriptionWithConstraints(gt.rules);
currentActivityTagTextEdit->setPlainText(s);
}
void ActivityTagsForm::activateActivityTag()
{
if(activityTagsListWidget->currentRow()<0){
QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
return;
}
QString text=activityTagsListWidget->currentItem()->text();
int count=gt.rules.activateActivityTag(text);
QMessageBox::information(this, tr("FET information"), tr("Activated a number of %1 activities").arg(count));
}
void ActivityTagsForm::deactivateActivityTag()
{
if(activityTagsListWidget->currentRow()<0){
QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
return;
}
QString text=activityTagsListWidget->currentItem()->text();
int count=gt.rules.deactivateActivityTag(text);
QMessageBox::information(this, tr("FET information"), tr("De-activated a number of %1 activities").arg(count));
}
void ActivityTagsForm::printableActivityTag()
{
if(activityTagsListWidget->currentRow()<0){
QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
return;
}
QString text=activityTagsListWidget->currentItem()->text();
gt.rules.makeActivityTagPrintable(text);
activityTagChanged(activityTagsListWidget->currentRow());
}
void ActivityTagsForm::notPrintableActivityTag()
{
if(activityTagsListWidget->currentRow()<0){
QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
return;
}
QString text=activityTagsListWidget->currentItem()->text();
gt.rules.makeActivityTagNotPrintable(text);
activityTagChanged(activityTagsListWidget->currentRow());
}
void ActivityTagsForm::help()
{
QMessageBox::information(this, tr("FET help on activity tags"),
tr("Activity tag is a field which can be used or not, depending on your wish (optional field)."
" It is designed to help you with some constraints. Each activity has a possible empty list of activity tags"
" (if you don't use activity tags, the list will be empty)"));
}
void ActivityTagsForm::comments()
{
int ind=activityTagsListWidget->currentRow();
if(ind<0){
QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
return;
}
ActivityTag* at=gt.rules.activityTagsList[ind];
assert(at!=NULL);
QDialog getCommentsDialog(this);
getCommentsDialog.setWindowTitle(tr("Activity tag comments"));
QPushButton* okPB=new QPushButton(tr("OK"));
okPB->setDefault(true);
QPushButton* cancelPB=new QPushButton(tr("Cancel"));
connect(okPB, SIGNAL(clicked()), &getCommentsDialog, SLOT(accept()));
connect(cancelPB, SIGNAL(clicked()), &getCommentsDialog, SLOT(reject()));
QHBoxLayout* hl=new QHBoxLayout();
hl->addStretch();
hl->addWidget(okPB);
hl->addWidget(cancelPB);
QVBoxLayout* vl=new QVBoxLayout();
QPlainTextEdit* commentsPT=new QPlainTextEdit();
commentsPT->setPlainText(at->comments);
commentsPT->selectAll();
commentsPT->setFocus();
vl->addWidget(commentsPT);
vl->addLayout(hl);
getCommentsDialog.setLayout(vl);
const QString settingsName=QString("ActivityTagCommentsDialog");
getCommentsDialog.resize(500, 320);
centerWidgetOnScreen(&getCommentsDialog);
restoreFETDialogGeometry(&getCommentsDialog, settingsName);
int t=getCommentsDialog.exec();
saveFETDialogGeometry(&getCommentsDialog, settingsName);
if(t==QDialog::Accepted){
at->comments=commentsPT->toPlainText();
gt.rules.internalStructureComputed=false;
setRulesModifiedAndOtherThings(>.rules);
activityTagChanged(ind);
}
}
<commit_msg>activity tag help string clarification<commit_after>//
//
// Description: This file is part of FET
//
//
// Author: Lalescu Liviu <Please see https://lalescu.ro/liviu/ for details about contacting Liviu Lalescu (in particular, you can find here the e-mail address)>
// Copyright (C) 2005 Liviu Lalescu <https://lalescu.ro/liviu/>
//
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#include "timetable_defs.h"
#include "timetable.h"
#include "fet.h"
#include "activitytagsform.h"
#include "studentsset.h"
#include "teacher.h"
#include "subject.h"
#include "activitytag.h"
#include <QInputDialog>
#include <QMessageBox>
#include <QListWidget>
#include <QAbstractItemView>
#include <QSplitter>
#include <QSettings>
#include <QObject>
#include <QMetaObject>
extern const QString COMPANY;
extern const QString PROGRAM;
ActivityTagsForm::ActivityTagsForm(QWidget* parent): QDialog(parent)
{
setupUi(this);
currentActivityTagTextEdit->setReadOnly(true);
renameActivityTagPushButton->setDefault(true);
activityTagsListWidget->setSelectionMode(QAbstractItemView::SingleSelection);
connect(closePushButton, SIGNAL(clicked()), this, SLOT(close()));
connect(addActivityTagPushButton, SIGNAL(clicked()), this, SLOT(addActivityTag()));
connect(removeActivityTagPushButton, SIGNAL(clicked()), this, SLOT(removeActivityTag()));
connect(renameActivityTagPushButton, SIGNAL(clicked()), this, SLOT(renameActivityTag()));
connect(moveActivityTagUpPushButton, SIGNAL(clicked()), this, SLOT(moveActivityTagUp()));
connect(moveActivityTagDownPushButton, SIGNAL(clicked()), this, SLOT(moveActivityTagDown()));
connect(sortActivityTagsPushButton, SIGNAL(clicked()), this, SLOT(sortActivityTags()));
connect(activityTagsListWidget, SIGNAL(currentRowChanged(int)), this, SLOT(activityTagChanged(int)));
connect(activateActivityTagPushButton, SIGNAL(clicked()), this, SLOT(activateActivityTag()));
connect(deactivateActivityTagPushButton, SIGNAL(clicked()), this, SLOT(deactivateActivityTag()));
connect(activityTagsListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(renameActivityTag()));
connect(helpPushButton, SIGNAL(clicked()), this, SLOT(help()));
connect(printablePushButton, SIGNAL(clicked()), this, SLOT(printableActivityTag()));
connect(notPrintablePushButton, SIGNAL(clicked()), this, SLOT(notPrintableActivityTag()));
connect(commentsPushButton, SIGNAL(clicked()), this, SLOT(comments()));
centerWidgetOnScreen(this);
restoreFETDialogGeometry(this);
//restore splitter state
QSettings settings(COMPANY, PROGRAM);
if(settings.contains(this->metaObject()->className()+QString("/splitter-state")))
splitter->restoreState(settings.value(this->metaObject()->className()+QString("/splitter-state")).toByteArray());
activityTagsListWidget->clear();
for(int i=0; i<gt.rules.activityTagsList.size(); i++){
ActivityTag* sbt=gt.rules.activityTagsList[i];
activityTagsListWidget->addItem(sbt->name);
}
if(activityTagsListWidget->count()>0)
activityTagsListWidget->setCurrentRow(0);
}
ActivityTagsForm::~ActivityTagsForm()
{
saveFETDialogGeometry(this);
//save splitter state
QSettings settings(COMPANY, PROGRAM);
settings.setValue(this->metaObject()->className()+QString("/splitter-state"), splitter->saveState());
}
void ActivityTagsForm::addActivityTag()
{
bool ok = false;
ActivityTag* sbt=new ActivityTag();
sbt->name = QInputDialog::getText( this, tr("Add activity tag"), tr("Please enter activity tag's name") ,
QLineEdit::Normal, QString(), &ok );
if ( ok && !((sbt->name).isEmpty()) ){
// user entered something and pressed OK
if(!gt.rules.addActivityTag(sbt)){
QMessageBox::information( this, tr("Activity tag insertion dialog"),
tr("Could not insert item. Must be a duplicate"));
delete sbt;
}
else{
activityTagsListWidget->addItem(sbt->name);
activityTagsListWidget->setCurrentRow(activityTagsListWidget->count()-1);
}
}
else{
if(ok){ //the user entered nothing
QMessageBox::information(this, tr("FET information"), tr("Incorrect name"));
}
delete sbt;// user entered nothing or pressed Cancel
}
}
void ActivityTagsForm::removeActivityTag()
{
int i=activityTagsListWidget->currentRow();
if(activityTagsListWidget->currentRow()<0){
QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
return;
}
QString text=activityTagsListWidget->currentItem()->text();
int activity_tag_ID=gt.rules.searchActivityTag(text);
if(activity_tag_ID<0){
QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
return;
}
if(QMessageBox::warning( this, tr("FET"),
tr("Are you sure you want to delete this activity tag?"),
tr("Yes"), tr("No"), 0, 0, 1 ) == 1)
return;
int tmp=gt.rules.removeActivityTag(text);
if(tmp){
activityTagsListWidget->setCurrentRow(-1);
QListWidgetItem* item;
item=activityTagsListWidget->takeItem(i);
delete item;
if(i>=activityTagsListWidget->count())
i=activityTagsListWidget->count()-1;
if(i>=0)
activityTagsListWidget->setCurrentRow(i);
else
currentActivityTagTextEdit->setPlainText(QString(""));
}
}
void ActivityTagsForm::renameActivityTag()
{
int i=activityTagsListWidget->currentRow();
if(activityTagsListWidget->currentRow()<0){
QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
return;
}
QString initialActivityTagName=activityTagsListWidget->currentItem()->text();
int activity_tag_ID=gt.rules.searchActivityTag(initialActivityTagName);
if(activity_tag_ID<0){
QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
return;
}
bool ok = false;
QString finalActivityTagName;
finalActivityTagName = QInputDialog::getText( this, tr("Rename activity tag"), tr("Please enter new activity tag's name") ,
QLineEdit::Normal, initialActivityTagName, &ok );
if ( ok && !(finalActivityTagName.isEmpty()) ){
// user entered something and pressed OK
if(gt.rules.searchActivityTag(finalActivityTagName)>=0){
QMessageBox::information( this, tr("Activity tag insertion dialog"),
tr("Could not modify item. New name must be a duplicate"));
}
else{
gt.rules.modifyActivityTag(initialActivityTagName, finalActivityTagName);
activityTagsListWidget->item(i)->setText(finalActivityTagName);
activityTagChanged(activityTagsListWidget->currentRow());
}
}
}
void ActivityTagsForm::moveActivityTagUp()
{
if(activityTagsListWidget->count()<=1)
return;
int i=activityTagsListWidget->currentRow();
if(i<0 || i>=activityTagsListWidget->count())
return;
if(i==0)
return;
QString s1=activityTagsListWidget->item(i)->text();
QString s2=activityTagsListWidget->item(i-1)->text();
ActivityTag* at1=gt.rules.activityTagsList.at(i);
ActivityTag* at2=gt.rules.activityTagsList.at(i-1);
gt.rules.internalStructureComputed=false;
setRulesModifiedAndOtherThings(>.rules);
activityTagsListWidget->item(i)->setText(s2);
activityTagsListWidget->item(i-1)->setText(s1);
gt.rules.activityTagsList[i]=at2;
gt.rules.activityTagsList[i-1]=at1;
activityTagsListWidget->setCurrentRow(i-1);
activityTagChanged(i-1);
}
void ActivityTagsForm::moveActivityTagDown()
{
if(activityTagsListWidget->count()<=1)
return;
int i=activityTagsListWidget->currentRow();
if(i<0 || i>=activityTagsListWidget->count())
return;
if(i==activityTagsListWidget->count()-1)
return;
QString s1=activityTagsListWidget->item(i)->text();
QString s2=activityTagsListWidget->item(i+1)->text();
ActivityTag* at1=gt.rules.activityTagsList.at(i);
ActivityTag* at2=gt.rules.activityTagsList.at(i+1);
gt.rules.internalStructureComputed=false;
setRulesModifiedAndOtherThings(>.rules);
activityTagsListWidget->item(i)->setText(s2);
activityTagsListWidget->item(i+1)->setText(s1);
gt.rules.activityTagsList[i]=at2;
gt.rules.activityTagsList[i+1]=at1;
activityTagsListWidget->setCurrentRow(i+1);
activityTagChanged(i+1);
}
void ActivityTagsForm::sortActivityTags()
{
gt.rules.sortActivityTagsAlphabetically();
activityTagsListWidget->clear();
for(int i=0; i<gt.rules.activityTagsList.size(); i++){
ActivityTag* sbt=gt.rules.activityTagsList[i];
activityTagsListWidget->addItem(sbt->name);
}
if(activityTagsListWidget->count()>0)
activityTagsListWidget->setCurrentRow(0);
}
void ActivityTagsForm::activityTagChanged(int index)
{
if(index<0){
currentActivityTagTextEdit->setPlainText(QString(""));
return;
}
ActivityTag* st=gt.rules.activityTagsList.at(index);
assert(st);
QString s=st->getDetailedDescriptionWithConstraints(gt.rules);
currentActivityTagTextEdit->setPlainText(s);
}
void ActivityTagsForm::activateActivityTag()
{
if(activityTagsListWidget->currentRow()<0){
QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
return;
}
QString text=activityTagsListWidget->currentItem()->text();
int count=gt.rules.activateActivityTag(text);
QMessageBox::information(this, tr("FET information"), tr("Activated a number of %1 activities").arg(count));
}
void ActivityTagsForm::deactivateActivityTag()
{
if(activityTagsListWidget->currentRow()<0){
QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
return;
}
QString text=activityTagsListWidget->currentItem()->text();
int count=gt.rules.deactivateActivityTag(text);
QMessageBox::information(this, tr("FET information"), tr("De-activated a number of %1 activities").arg(count));
}
void ActivityTagsForm::printableActivityTag()
{
if(activityTagsListWidget->currentRow()<0){
QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
return;
}
QString text=activityTagsListWidget->currentItem()->text();
gt.rules.makeActivityTagPrintable(text);
activityTagChanged(activityTagsListWidget->currentRow());
}
void ActivityTagsForm::notPrintableActivityTag()
{
if(activityTagsListWidget->currentRow()<0){
QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
return;
}
QString text=activityTagsListWidget->currentItem()->text();
gt.rules.makeActivityTagNotPrintable(text);
activityTagChanged(activityTagsListWidget->currentRow());
}
void ActivityTagsForm::help()
{
QMessageBox::information(this, tr("FET help on activity tags"),
tr("Activity tag is a field which can be used or not, depending on your wish (optional field)."
" It is designed to help you with some constraints. Each activity has a list of activity tags"
" (which may be empty)."));
}
void ActivityTagsForm::comments()
{
int ind=activityTagsListWidget->currentRow();
if(ind<0){
QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag"));
return;
}
ActivityTag* at=gt.rules.activityTagsList[ind];
assert(at!=NULL);
QDialog getCommentsDialog(this);
getCommentsDialog.setWindowTitle(tr("Activity tag comments"));
QPushButton* okPB=new QPushButton(tr("OK"));
okPB->setDefault(true);
QPushButton* cancelPB=new QPushButton(tr("Cancel"));
connect(okPB, SIGNAL(clicked()), &getCommentsDialog, SLOT(accept()));
connect(cancelPB, SIGNAL(clicked()), &getCommentsDialog, SLOT(reject()));
QHBoxLayout* hl=new QHBoxLayout();
hl->addStretch();
hl->addWidget(okPB);
hl->addWidget(cancelPB);
QVBoxLayout* vl=new QVBoxLayout();
QPlainTextEdit* commentsPT=new QPlainTextEdit();
commentsPT->setPlainText(at->comments);
commentsPT->selectAll();
commentsPT->setFocus();
vl->addWidget(commentsPT);
vl->addLayout(hl);
getCommentsDialog.setLayout(vl);
const QString settingsName=QString("ActivityTagCommentsDialog");
getCommentsDialog.resize(500, 320);
centerWidgetOnScreen(&getCommentsDialog);
restoreFETDialogGeometry(&getCommentsDialog, settingsName);
int t=getCommentsDialog.exec();
saveFETDialogGeometry(&getCommentsDialog, settingsName);
if(t==QDialog::Accepted){
at->comments=commentsPT->toPlainText();
gt.rules.internalStructureComputed=false;
setRulesModifiedAndOtherThings(>.rules);
activityTagChanged(ind);
}
}
<|endoftext|>
|
<commit_before>// MaterialTests.cpp
#include <gtest/gtest.h>
#include "MaterialTests.h"
#include <cmath>
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, Constructors){
EXPECT_EQ(test_mat_->units(), "kg");
EXPECT_EQ(test_mat_->type(), MATERIAL_RES);
EXPECT_GE(test_mat_->ID(),0);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, Clone) {
rsrc_ptr clone_mat;
ASSERT_NO_THROW(clone_mat = test_mat_->clone());
// in order to acommodate discrete material tracking, all ID's mush be unique
EXPECT_NE(test_mat_->ID(), clone_mat->ID());
EXPECT_EQ(test_mat_->quantity(), clone_mat->quantity());
EXPECT_EQ(test_mat_->type(), clone_mat->type());
EXPECT_TRUE(test_mat_->checkQuality(clone_mat));
EXPECT_DOUBLE_EQ(test_mat_->quantity(), clone_mat->quantity());
EXPECT_TRUE(clone_mat->checkQuality(test_mat_));
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, CheckQuality) {
rsrc_ptr test(test_mat_);
rsrc_ptr diff(diff_mat_);
rsrc_ptr gen(new GenericResource("kg", "foo", 10));
EXPECT_TRUE(test->checkQuality(diff));
EXPECT_TRUE(diff->checkQuality(test));
EXPECT_FALSE(test->checkQuality(gen));
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, CheckIsoMass) {
// check total mass, you'll use it later.
EXPECT_FLOAT_EQ(test_mat_->quantity(),test_size_);
// you should be able to get the mass per isotope
EXPECT_NO_THROW(test_mat_->mass(u235_));
// if the material has only one isotope, it should be the same as the total
// the u235 mass should be (mol/mat)(1kg/1000g)(235g/mol)
ASSERT_FLOAT_EQ(test_mat_->mass(u235_) , test_mat_->moles(u235_)*0.235);
// if the mat has many isotopes, their individual masses should scale with
// their atomic numbers.
double test_total = 0;
CompMap::iterator comp;
int i;
for( comp = (*test_comp_).begin(); comp != (*test_comp_).end(); ++comp){
i = (*comp).first;
test_total += test_mat_->mass(i);
}
ASSERT_FLOAT_EQ(test_mat_->quantity(), test_total);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, CheckIsoAtoms){
// you should be able to get to the atoms of a certain iso in your material
EXPECT_NO_THROW(test_mat_->moles(u235_));
EXPECT_FLOAT_EQ(one_mol_,test_mat_->moles(u235_));
// a mat's total atoms should be the total of all the contained isotopes.
double test_total = 0;
CompMap::iterator comp;
int i;
for( comp = (*test_comp_).begin(); comp != (*test_comp_).end(); ++comp){
i = (*comp).first;
total_atoms += test_mat_->moles(i);
}
ASSERT_FLOAT_EQ(test_mat_->moles(), test_total);
// you should be able to get to the total atoms in your material
total_atoms = test_mat_->moles();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, CheckConvertFromKg){
// check total mass, you'll use it later.
EXPECT_FLOAT_EQ(test_mat_->quantity(),test_size_);
// you should be able to get the mass per isotope
EXPECT_NO_THROW(test_mat_->mass(u235_));
ASSERT_FLOAT_EQ(test_mat_->mass(u235_), test_mat_->mass(u235_,KG));
ASSERT_FLOAT_EQ(1000.0*test_mat_->mass(u235_), test_mat_->mass(u235_,G));
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, CheckConvertToKg){
// check total mass, you'll use it later.
EXPECT_FLOAT_EQ(test_mat_->quantity(),test_size_);
ASSERT_FLOAT_EQ(test_size_, test_mat_->mass(KG));
EXPECT_NO_THROW(test_mat_->setQuantity(test_size_*1000.0,G));
ASSERT_FLOAT_EQ(test_size_, test_mat_->mass(KG));
EXPECT_NO_THROW(test_mat_->setQuantity(test_size_,G));
ASSERT_FLOAT_EQ(test_size_, test_mat_->mass(KG)/1000.0);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, AbsorbLikeMaterial) {
mat_rsrc_ptr one_test_mat;
mat_rsrc_ptr two_test_mat;
mat_rsrc_ptr ten_test_mat;
one_test_mat = mat_rsrc_ptr(new Material(test_comp_));
int one = 1;
one_test_mat->setQuantity(one*test_size_);
two_test_mat = mat_rsrc_ptr(new Material(test_comp_));
int two = 2;
two_test_mat->setQuantity(two*test_size_);
ten_test_mat = mat_rsrc_ptr(new Material(test_comp_));
int ten = 10;
ten_test_mat->setQuantity(ten*test_size_);
// see that two materials with the same composition do the right thing
double orig = test_mat_->quantity();
int factor = 1+one;
ASSERT_NO_THROW(test_mat_->absorb(one_test_mat));
EXPECT_FLOAT_EQ(test_mat_->quantity(), factor * orig );
factor += two;
ASSERT_NO_THROW(test_mat_->absorb(two_test_mat));
EXPECT_FLOAT_EQ(test_mat_->quantity(), factor * orig );
factor += ten;
ASSERT_NO_THROW(test_mat_->absorb(ten_test_mat));
EXPECT_FLOAT_EQ(test_mat_->quantity(), factor * orig );
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, AbsorbUnLikeMaterial) {
// make a number of materials masses 1, 2, and 10
mat_rsrc_ptr same_as_orig_test_mat = mat_rsrc_ptr(new Material(test_comp_));
CompMapPtr diff_test_comp = CompMapPtr(new CompMap(MASS));
(*diff_test_comp)[pb208_] = 1.0;
(*diff_test_comp)[am241_] = 1.0;
(*diff_test_comp)[th228_] = 1.0;
mat_rsrc_ptr diff_test_mat = mat_rsrc_ptr(new Material(diff_test_comp));
diff_test_mat->setQuantity(test_size_/2);
double orig = test_mat_->quantity();
double origdiff = diff_test_mat->quantity();
// see that materials with different compositions do the right thing
ASSERT_NO_THROW(test_mat_->absorb(diff_test_mat));
EXPECT_FLOAT_EQ(orig + origdiff, test_mat_->quantity() );
EXPECT_TRUE(std::abs(same_as_orig_test_mat->quantity() -
test_mat_->quantity()) > EPS_KG);
EXPECT_TRUE(same_as_orig_test_mat->checkQuality(test_mat_));
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, ExtractMass) {
double amt = test_size_ / 3;
double diff = test_size_ - amt;
mat_rsrc_ptr extracted;
EXPECT_FLOAT_EQ(test_mat_->quantity(),test_size_); // we expect this amt
EXPECT_NO_THROW(extracted = test_mat_->extract(amt)); // extract an amt
EXPECT_FLOAT_EQ(extracted->quantity(),amt); // check correctness
EXPECT_FLOAT_EQ(test_mat_->quantity(),diff); // check correctness
EXPECT_EQ(test_mat_->isoVector(),extracted->isoVector());
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, Extract) {
mat_rsrc_ptr m1;
ASSERT_NO_THROW(m1 = test_mat_->extract(test_comp_));
EXPECT_FLOAT_EQ(test_mat_->quantity(), 0 );
EXPECT_FLOAT_EQ(m1->quantity(), test_size_ );
mat_rsrc_ptr m2;
ASSERT_NO_THROW(m2 = diff_mat_->extract(test_comp_));
EXPECT_FLOAT_EQ(diff_mat_->quantity(), test_size_*fraction );
EXPECT_FLOAT_EQ(m2->quantity(), test_size_*(1-fraction) );
// ASSERT_THROW(two_test_mat->extract(ten_test_comp), CycException);
}
<commit_msg>all tests compile<commit_after>// MaterialTests.cpp
#include <gtest/gtest.h>
#include "MaterialTests.h"
#include <cmath>
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, Constructors){
EXPECT_EQ(test_mat_->units(), "kg");
EXPECT_EQ(test_mat_->type(), MATERIAL_RES);
EXPECT_GE(test_mat_->ID(),0);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, Clone) {
rsrc_ptr clone_mat;
ASSERT_NO_THROW(clone_mat = test_mat_->clone());
// in order to acommodate discrete material tracking, all ID's mush be unique
EXPECT_NE(test_mat_->ID(), clone_mat->ID());
EXPECT_EQ(test_mat_->quantity(), clone_mat->quantity());
EXPECT_EQ(test_mat_->type(), clone_mat->type());
EXPECT_TRUE(test_mat_->checkQuality(clone_mat));
EXPECT_DOUBLE_EQ(test_mat_->quantity(), clone_mat->quantity());
EXPECT_TRUE(clone_mat->checkQuality(test_mat_));
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, CheckQuality) {
rsrc_ptr test(test_mat_);
rsrc_ptr diff(diff_mat_);
rsrc_ptr gen(new GenericResource("kg", "foo", 10));
EXPECT_TRUE(test->checkQuality(diff));
EXPECT_TRUE(diff->checkQuality(test));
EXPECT_FALSE(test->checkQuality(gen));
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, CheckIsoMass) {
// check total mass, you'll use it later.
EXPECT_FLOAT_EQ(test_mat_->quantity(),test_size_);
// you should be able to get the mass per isotope
EXPECT_NO_THROW(test_mat_->mass(u235_));
// if the material has only one isotope, it should be the same as the total
// the u235 mass should be (mol/mat)(1kg/1000g)(235g/mol)
ASSERT_FLOAT_EQ(test_mat_->mass(u235_) , test_mat_->moles(u235_)*0.235);
// if the mat has many isotopes, their individual masses should scale with
// their atomic numbers.
double test_total = 0;
CompMap::iterator comp;
int i;
for( comp = (*test_comp_).begin(); comp != (*test_comp_).end(); ++comp){
i = (*comp).first;
test_total += test_mat_->mass(i);
}
ASSERT_FLOAT_EQ(test_mat_->quantity(), test_total);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, CheckIsoAtoms){
// you should be able to get to the atoms of a certain iso in your material
EXPECT_NO_THROW(test_mat_->moles(u235_));
EXPECT_FLOAT_EQ(one_mol_,test_mat_->moles(u235_));
// a mat's total atoms should be the total of all the contained isotopes.
double total_atoms = 0;
CompMap::iterator comp;
int i;
for( comp = (*test_comp_).begin(); comp != (*test_comp_).end(); ++comp){
i = (*comp).first;
total_atoms += test_mat_->moles(i);
}
// you should be able to get to the total atoms in your material
ASSERT_FLOAT_EQ(test_mat_->moles(), total_atoms);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, CheckConvertFromKg){
// check total mass, you'll use it later.
EXPECT_FLOAT_EQ(test_mat_->quantity(),test_size_);
// you should be able to get the mass per isotope
EXPECT_NO_THROW(test_mat_->mass(u235_));
ASSERT_FLOAT_EQ(test_mat_->mass(u235_), test_mat_->mass(u235_,KG));
ASSERT_FLOAT_EQ(1000.0*test_mat_->mass(u235_), test_mat_->mass(u235_,G));
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, CheckConvertToKg){
// check total mass, you'll use it later.
EXPECT_FLOAT_EQ(test_mat_->quantity(),test_size_);
ASSERT_FLOAT_EQ(test_size_, test_mat_->mass(KG));
EXPECT_NO_THROW(test_mat_->setQuantity(test_size_*1000.0,G));
ASSERT_FLOAT_EQ(test_size_, test_mat_->mass(KG));
EXPECT_NO_THROW(test_mat_->setQuantity(test_size_,G));
ASSERT_FLOAT_EQ(test_size_, test_mat_->mass(KG)/1000.0);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, AbsorbLikeMaterial) {
mat_rsrc_ptr one_test_mat;
mat_rsrc_ptr two_test_mat;
mat_rsrc_ptr ten_test_mat;
one_test_mat = mat_rsrc_ptr(new Material(test_comp_));
int one = 1;
one_test_mat->setQuantity(one*test_size_);
two_test_mat = mat_rsrc_ptr(new Material(test_comp_));
int two = 2;
two_test_mat->setQuantity(two*test_size_);
ten_test_mat = mat_rsrc_ptr(new Material(test_comp_));
int ten = 10;
ten_test_mat->setQuantity(ten*test_size_);
// see that two materials with the same composition do the right thing
double orig = test_mat_->quantity();
int factor = 1+one;
ASSERT_NO_THROW(test_mat_->absorb(one_test_mat));
EXPECT_FLOAT_EQ(test_mat_->quantity(), factor * orig );
factor += two;
ASSERT_NO_THROW(test_mat_->absorb(two_test_mat));
EXPECT_FLOAT_EQ(test_mat_->quantity(), factor * orig );
factor += ten;
ASSERT_NO_THROW(test_mat_->absorb(ten_test_mat));
EXPECT_FLOAT_EQ(test_mat_->quantity(), factor * orig );
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, AbsorbUnLikeMaterial) {
// make a number of materials masses 1, 2, and 10
mat_rsrc_ptr same_as_orig_test_mat = mat_rsrc_ptr(new Material(test_comp_));
CompMapPtr diff_test_comp = CompMapPtr(new CompMap(MASS));
(*diff_test_comp)[pb208_] = 1.0;
(*diff_test_comp)[am241_] = 1.0;
(*diff_test_comp)[th228_] = 1.0;
mat_rsrc_ptr diff_test_mat = mat_rsrc_ptr(new Material(diff_test_comp));
diff_test_mat->setQuantity(test_size_/2);
double orig = test_mat_->quantity();
double origdiff = diff_test_mat->quantity();
// see that materials with different compositions do the right thing
ASSERT_NO_THROW(test_mat_->absorb(diff_test_mat));
EXPECT_FLOAT_EQ(orig + origdiff, test_mat_->quantity() );
EXPECT_TRUE(std::abs(same_as_orig_test_mat->quantity() -
test_mat_->quantity()) > EPS_KG);
EXPECT_TRUE(same_as_orig_test_mat->checkQuality(test_mat_));
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, ExtractMass) {
double amt = test_size_ / 3;
double diff = test_size_ - amt;
mat_rsrc_ptr extracted;
EXPECT_FLOAT_EQ(test_mat_->quantity(),test_size_); // we expect this amt
EXPECT_NO_THROW(extracted = test_mat_->extract(amt)); // extract an amt
EXPECT_FLOAT_EQ(extracted->quantity(),amt); // check correctness
EXPECT_FLOAT_EQ(test_mat_->quantity(),diff); // check correctness
EXPECT_EQ(test_mat_->isoVector(),extracted->isoVector());
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MaterialTest, Extract) {
mat_rsrc_ptr m1;
ASSERT_NO_THROW(m1 = test_mat_->extract(test_comp_));
EXPECT_FLOAT_EQ(test_mat_->quantity(), 0 );
EXPECT_FLOAT_EQ(m1->quantity(), test_size_ );
mat_rsrc_ptr m2;
ASSERT_NO_THROW(m2 = diff_mat_->extract(test_comp_));
EXPECT_FLOAT_EQ(diff_mat_->quantity(), test_size_*fraction );
EXPECT_FLOAT_EQ(m2->quantity(), test_size_*(1-fraction) );
// ASSERT_THROW(two_test_mat->extract(ten_test_comp), CycException);
}
<|endoftext|>
|
<commit_before>#include "Support/IRPrettyPrinter.h"
#include "IR/Type.h"
#include "IR/Value.h"
#include "IR/Instruction.h"
#include "IR/BasicBlock.h"
#include "IR/Constants.h"
IRPrettyPrinter::IRPrettyPrinter(BasicBlock const* bb, std::ostream& out) :
bb_(bb), out_(out)
{
}
IRPrettyPrinter::~IRPrettyPrinter() {
}
void IRPrettyPrinter::prettyPrint() {
printBasicBlock(bb_);
}
void IRPrettyPrinter::printValue(Value const* v) {
switch (v->getValueType()) {
case Value::BasicBlockV:
printBasicBlock(dynamic_cast<BasicBlock const*>(v));
break;
case Value::InstructionV:
printInstruction(dynamic_cast<Instruction const*>(v));
break;
default:
out_ << "<unknown value>\n";
break;
}
}
void IRPrettyPrinter::printBasicBlock(BasicBlock const* bb) {
out_ << bb->getName() << ":\n";
for (Value const* v : *bb) {
printValue(v);
}
}
void IRPrettyPrinter::printInstruction(Instruction const* inst) {
if (inst->isBinaryOp()) {
BinaryOperator const* binst = dynamic_cast<BinaryOperator const*>(inst);
out_ << " "
<< binst->getName() << " = "
<< binst->getOpcodeName() << ' '
//<< typeToString(binst->getType()) << ' '
<< binst->getLHS()->getName() << ", "
<< binst->getRHS()->getName() << '\n';
}
}
std::string IRPrettyPrinter::typeToString(Type const* type) {
if (type == Type::getInt64Ty())
return "i64";
return "utype";
}
<commit_msg>Fix IRPrettyPrinter<commit_after>#include "Support/IRPrettyPrinter.h"
#include "IR/Type.h"
#include "IR/Value.h"
#include "IR/Instruction.h"
#include "IR/BasicBlock.h"
#include "IR/Constants.h"
IRPrettyPrinter::IRPrettyPrinter(BasicBlock const* bb, std::ostream& out) :
bb_(bb), out_(out)
{
}
IRPrettyPrinter::~IRPrettyPrinter() {
}
void IRPrettyPrinter::prettyPrint() {
printBasicBlock(bb_);
}
void IRPrettyPrinter::printValue(Value const* v) {
switch (v->getValueType()) {
case Value::BasicBlockV:
printBasicBlock(dynamic_cast<BasicBlock const*>(v));
break;
case Value::InstructionV:
printInstruction(dynamic_cast<Instruction const*>(v));
break;
default:
out_ << "<unknown value>\n";
break;
}
}
void IRPrettyPrinter::printBasicBlock(BasicBlock const* bb) {
out_ << bb->getName() << ":\n";
for (Value const* v : *bb) {
printValue(v);
}
}
void IRPrettyPrinter::printInstruction(Instruction const* inst) {
if (inst->isBinaryOp()) {
BinaryOperator const* binst = dynamic_cast<BinaryOperator const*>(inst);
out_ << " "
<< binst->getName() << " = "
<< binst->getOpcodeName() << ' '
<< typeToString(binst->getType()) << ' '
<< binst->getLHS()->getName() << ", "
<< binst->getRHS()->getName() << '\n';
}
}
std::string IRPrettyPrinter::typeToString(Type const* type) {
if (type == Type::getInt64Ty())
return "i64";
return "utype";
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: listeneriter.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 09:53:44 $
*
* 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 _SVT_LISTENERITER_HXX
#define _SVT_LISTENERITER_HXX
#ifndef INCLUDED_SVLDLLAPI_H
#include "svtools/svldllapi.h"
#endif
#ifndef _RTTI_HXX //autogen
#include <tools/rtti.hxx>
#endif
class SvtListener;
class SvtListenerBase;
class SvtBroadcaster;
//-------------------------------------------------------------------------
class SVL_DLLPUBLIC SvtListenerIter
{
friend class SvtListenerBase;
SvtBroadcaster& rRoot;
SvtListenerBase *pAkt, *pDelNext;
// for the update of all iterator's, if a listener is added or removed
// at the same time.
static SvtListenerIter *pListenerIters;
SvtListenerIter *pNxtIter;
TypeId aSrchId; // fuer First/Next - suche diesen Type
SVL_DLLPRIVATE static void RemoveListener( SvtListenerBase& rDel,
SvtListenerBase* pNext );
public:
SvtListenerIter( SvtBroadcaster& );
~SvtListenerIter();
const SvtBroadcaster& GetBroadcaster() const { return rRoot; }
SvtBroadcaster& GetBroadcaster() { return rRoot; }
SvtListener* GoNext(); // to the next
SvtListener* GoPrev(); // to the previous
SvtListener* GoStart(); // to the start of the list
SvtListener* GoEnd(); // to the end of the list
SvtListener* GoRoot(); // to the root
SvtListener* GetCurr() const; // returns the current
int IsChanged() const { return pDelNext != pAkt; }
SvtListener* First( TypeId nType );
SvtListener* Next();
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.3.772); FILE MERGED 2008/04/01 15:44:22 thb 1.3.772.3: #i85898# Stripping all external header guards 2008/04/01 12:43:07 thb 1.3.772.2: #i85898# Stripping all external header guards 2008/03/31 13:00:53 rt 1.3.772.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: listeneriter.hxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _SVT_LISTENERITER_HXX
#define _SVT_LISTENERITER_HXX
#include "svtools/svldllapi.h"
#include <tools/rtti.hxx>
class SvtListener;
class SvtListenerBase;
class SvtBroadcaster;
//-------------------------------------------------------------------------
class SVL_DLLPUBLIC SvtListenerIter
{
friend class SvtListenerBase;
SvtBroadcaster& rRoot;
SvtListenerBase *pAkt, *pDelNext;
// for the update of all iterator's, if a listener is added or removed
// at the same time.
static SvtListenerIter *pListenerIters;
SvtListenerIter *pNxtIter;
TypeId aSrchId; // fuer First/Next - suche diesen Type
SVL_DLLPRIVATE static void RemoveListener( SvtListenerBase& rDel,
SvtListenerBase* pNext );
public:
SvtListenerIter( SvtBroadcaster& );
~SvtListenerIter();
const SvtBroadcaster& GetBroadcaster() const { return rRoot; }
SvtBroadcaster& GetBroadcaster() { return rRoot; }
SvtListener* GoNext(); // to the next
SvtListener* GoPrev(); // to the previous
SvtListener* GoStart(); // to the start of the list
SvtListener* GoEnd(); // to the end of the list
SvtListener* GoRoot(); // to the root
SvtListener* GetCurr() const; // returns the current
int IsChanged() const { return pDelNext != pAkt; }
SvtListener* First( TypeId nType );
SvtListener* Next();
};
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fmobjfac.cxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: hr $ $Date: 2007-06-27 18:13:34 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _SVDOBJ_HXX
#include <svx/svdobj.hxx>
#endif
#ifndef _SVX_FMTOOLS_HXX
#include "fmtools.hxx"
#endif
#ifndef _SVX_FMSERVS_HXX
#include "fmservs.hxx"
#endif
#ifndef _FM_FMOBJFAC_HXX
#include "fmobjfac.hxx"
#endif
#ifndef _FM_FMGLOB_HXX
#include <svx/fmglob.hxx>
#endif
#ifndef _FM_FMOBJ_HXX
#include "fmobj.hxx"
#endif
#ifndef _SVX_FMSHIMP_HXX
#include "fmshimp.hxx"
#endif
#ifndef _FM_FMSHELL_HXX
#include <svx/fmshell.hxx>
#endif
#ifndef _SVX_SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#ifndef _SVX_TBXFORM_HXX
#include "tbxform.hxx"
#endif
#ifndef _TOOLS_RESID_HXX //autogen
#include <tools/resid.hxx>
#endif
#ifndef _SVX_FMRESIDS_HRC
#include "fmresids.hrc"
#endif
#ifndef _SHL_HXX
#include <tools/shl.hxx>
#endif
#ifndef _SVX_DIALMGR_HXX
#include <svx/dialmgr.hxx>
#endif
#ifndef _SVX_FMSERVS_HXX
#include "fmservs.hxx"
#endif
#ifndef _SVX_TABWIN_HXX
#include "tabwin.hxx"
#endif
#ifndef _SVX_FMEXPL_HXX
#include "fmexpl.hxx"
#endif
#ifndef _SVX_FILTNAV_HXX
#include "filtnav.hxx"
#endif
#ifndef _SVX_FMPROP_HRC
#include "fmprop.hrc"
#endif
#ifndef SVX_FMPROPBRW_HXX
#include "fmPropBrw.hxx"
#endif
#ifndef _SVX_DATANAVI_HXX
#include "datanavi.hxx"
#endif
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::svxform;
static BOOL bInit = FALSE;
/*************************************************************************
|*
|* Ctor
|*
\************************************************************************/
FmFormObjFactory::FmFormObjFactory()
{
if ( !bInit )
{
SdrObjFactory::InsertMakeObjectHdl(LINK(this, FmFormObjFactory, MakeObject));
//////////////////////////////////////////////////////////////////////
// Konfigurations-::com::sun::star::frame::Controller und NavigationBar registrieren
SvxFmTbxCtlConfig::RegisterControl( SID_FM_CONFIG );
SvxFmTbxCtlAbsRec::RegisterControl( SID_FM_RECORD_ABSOLUTE );
SvxFmTbxCtlRecText::RegisterControl( SID_FM_RECORD_TEXT );
SvxFmTbxCtlRecFromText::RegisterControl( SID_FM_RECORD_FROM_TEXT );
SvxFmTbxCtlRecTotal::RegisterControl( SID_FM_RECORD_TOTAL );
SvxFmTbxPrevRec::RegisterControl( SID_FM_RECORD_PREV );
SvxFmTbxNextRec::RegisterControl( SID_FM_RECORD_NEXT );
ControlConversionMenuController::RegisterControl(SID_FM_CHANGECONTROLTYPE);
// Registrieung von globalen fenstern
FmFieldWinMgr::RegisterChildWindow();
FmPropBrwMgr::RegisterChildWindow();
NavigatorFrameManager::RegisterChildWindow();
DataNavigatorManager::RegisterChildWindow();
FmFilterNavigatorWinMgr::RegisterChildWindow();
//////////////////////////////////////////////////////////////////////
// Interface fuer die Formshell registrieren
FmFormShell::RegisterInterface(0);
ImplSmartRegisterUnoServices();
bInit = TRUE;
}
}
/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/
FmFormObjFactory::~FmFormObjFactory()
{
}
/*************************************************************************
|*
|* ::com::sun::star::form::Form-Objekte erzeugen
|*
\************************************************************************/
namespace
{
void lcl_initProperty( FmFormObj* _pObject, const ::rtl::OUString& _rPropName, const Any& _rValue )
{
try
{
Reference< XPropertySet > xModelSet( _pObject->GetUnoControlModel(), UNO_QUERY );
if ( xModelSet.is() )
xModelSet->setPropertyValue( _rPropName, _rValue );
}
catch( const Exception& )
{
DBG_ERROR( "lcl_initProperty: caught an exception!" );
}
}
}
IMPL_LINK(FmFormObjFactory, MakeObject, SdrObjFactory*, pObjFactory)
{
if (pObjFactory->nInventor == FmFormInventor)
{
::rtl::OUString sServiceSpecifier;
typedef ::std::vector< ::std::pair< ::rtl::OUString, Any > > PropertyValueArray;
PropertyValueArray aInitialProperties;
switch ( pObjFactory->nIdentifier )
{
case OBJ_FM_EDIT:
sServiceSpecifier = FM_COMPONENT_EDIT;
break;
case OBJ_FM_BUTTON:
sServiceSpecifier = FM_COMPONENT_COMMANDBUTTON;
break;
case OBJ_FM_FIXEDTEXT:
sServiceSpecifier = FM_COMPONENT_FIXEDTEXT;
break;
case OBJ_FM_LISTBOX:
sServiceSpecifier = FM_COMPONENT_LISTBOX;
break;
case OBJ_FM_CHECKBOX:
sServiceSpecifier = FM_COMPONENT_CHECKBOX;
break;
case OBJ_FM_RADIOBUTTON:
sServiceSpecifier = FM_COMPONENT_RADIOBUTTON;
break;
case OBJ_FM_GROUPBOX:
sServiceSpecifier = FM_COMPONENT_GROUPBOX;
break;
case OBJ_FM_COMBOBOX:
sServiceSpecifier = FM_COMPONENT_COMBOBOX;
break;
case OBJ_FM_GRID:
sServiceSpecifier = FM_COMPONENT_GRID;
break;
case OBJ_FM_IMAGEBUTTON:
sServiceSpecifier = FM_COMPONENT_IMAGEBUTTON;
break;
case OBJ_FM_FILECONTROL:
sServiceSpecifier = FM_COMPONENT_FILECONTROL;
break;
case OBJ_FM_DATEFIELD:
sServiceSpecifier = FM_COMPONENT_DATEFIELD;
break;
case OBJ_FM_TIMEFIELD:
sServiceSpecifier = FM_COMPONENT_TIMEFIELD;
aInitialProperties.push_back( PropertyValueArray::value_type( FM_PROP_TIMEMAX, makeAny( (sal_Int32)( Time( 23, 59, 59, 99 ).GetTime() ) ) ) );
break;
case OBJ_FM_NUMERICFIELD:
sServiceSpecifier = FM_COMPONENT_NUMERICFIELD;
break;
case OBJ_FM_CURRENCYFIELD:
sServiceSpecifier = FM_COMPONENT_CURRENCYFIELD;
break;
case OBJ_FM_PATTERNFIELD:
sServiceSpecifier = FM_COMPONENT_PATTERNFIELD;
break;
case OBJ_FM_HIDDEN:
sServiceSpecifier = FM_COMPONENT_HIDDEN;
break;
case OBJ_FM_IMAGECONTROL:
sServiceSpecifier = FM_COMPONENT_IMAGECONTROL;
break;
case OBJ_FM_FORMATTEDFIELD:
sServiceSpecifier = FM_COMPONENT_FORMATTEDFIELD;
break;
case OBJ_FM_NAVIGATIONBAR:
sServiceSpecifier = FM_SUN_COMPONENT_NAVIGATIONBAR;
break;
case OBJ_FM_SCROLLBAR:
sServiceSpecifier = FM_SUN_COMPONENT_SCROLLBAR;
aInitialProperties.push_back( PropertyValueArray::value_type( FM_PROP_BORDER, makeAny( (sal_Int16)0 ) ) );
break;
case OBJ_FM_SPINBUTTON:
sServiceSpecifier = FM_SUN_COMPONENT_SPINBUTTON;
aInitialProperties.push_back( PropertyValueArray::value_type( FM_PROP_BORDER, makeAny( (sal_Int16)0 ) ) );
break;
}
// create the actual object
if ( sServiceSpecifier.getLength() )
pObjFactory->pNewObj = new FmFormObj( sServiceSpecifier, pObjFactory->nIdentifier );
else
pObjFactory->pNewObj = new FmFormObj( pObjFactory->nIdentifier );
// initialize some properties which we want to differ from the defaults
for ( PropertyValueArray::const_iterator aInitProp = aInitialProperties.begin();
aInitProp != aInitialProperties.end();
++aInitProp
)
{
lcl_initProperty(
static_cast< FmFormObj* >( pObjFactory->pNewObj ),
aInitProp->first,
aInitProp->second
);
}
}
return 0;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.17.368); FILE MERGED 2008/04/01 15:51:01 thb 1.17.368.3: #i85898# Stripping all external header guards 2008/04/01 12:48:51 thb 1.17.368.2: #i85898# Stripping all external header guards 2008/03/31 14:21:54 rt 1.17.368.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: fmobjfac.cxx,v $
* $Revision: 1.18 $
*
* 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_svx.hxx"
#include <comphelper/stl_types.hxx>
#include <svx/svdobj.hxx>
#include "fmtools.hxx"
#include "fmservs.hxx"
#ifndef _FM_FMOBJFAC_HXX
#include "fmobjfac.hxx"
#endif
#ifndef _FM_FMGLOB_HXX
#include <svx/fmglob.hxx>
#endif
#ifndef _FM_FMOBJ_HXX
#include "fmobj.hxx"
#endif
#include "fmshimp.hxx"
#ifndef _FM_FMSHELL_HXX
#include <svx/fmshell.hxx>
#endif
#ifndef _SVX_SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#include "tbxform.hxx"
#include <tools/resid.hxx>
#ifndef _SVX_FMRESIDS_HRC
#include "fmresids.hrc"
#endif
#include <tools/shl.hxx>
#include <svx/dialmgr.hxx>
#include "fmservs.hxx"
#include "tabwin.hxx"
#include "fmexpl.hxx"
#include "filtnav.hxx"
#ifndef _SVX_FMPROP_HRC
#include "fmprop.hrc"
#endif
#include "fmPropBrw.hxx"
#include "datanavi.hxx"
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::svxform;
static BOOL bInit = FALSE;
/*************************************************************************
|*
|* Ctor
|*
\************************************************************************/
FmFormObjFactory::FmFormObjFactory()
{
if ( !bInit )
{
SdrObjFactory::InsertMakeObjectHdl(LINK(this, FmFormObjFactory, MakeObject));
//////////////////////////////////////////////////////////////////////
// Konfigurations-::com::sun::star::frame::Controller und NavigationBar registrieren
SvxFmTbxCtlConfig::RegisterControl( SID_FM_CONFIG );
SvxFmTbxCtlAbsRec::RegisterControl( SID_FM_RECORD_ABSOLUTE );
SvxFmTbxCtlRecText::RegisterControl( SID_FM_RECORD_TEXT );
SvxFmTbxCtlRecFromText::RegisterControl( SID_FM_RECORD_FROM_TEXT );
SvxFmTbxCtlRecTotal::RegisterControl( SID_FM_RECORD_TOTAL );
SvxFmTbxPrevRec::RegisterControl( SID_FM_RECORD_PREV );
SvxFmTbxNextRec::RegisterControl( SID_FM_RECORD_NEXT );
ControlConversionMenuController::RegisterControl(SID_FM_CHANGECONTROLTYPE);
// Registrieung von globalen fenstern
FmFieldWinMgr::RegisterChildWindow();
FmPropBrwMgr::RegisterChildWindow();
NavigatorFrameManager::RegisterChildWindow();
DataNavigatorManager::RegisterChildWindow();
FmFilterNavigatorWinMgr::RegisterChildWindow();
//////////////////////////////////////////////////////////////////////
// Interface fuer die Formshell registrieren
FmFormShell::RegisterInterface(0);
ImplSmartRegisterUnoServices();
bInit = TRUE;
}
}
/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/
FmFormObjFactory::~FmFormObjFactory()
{
}
/*************************************************************************
|*
|* ::com::sun::star::form::Form-Objekte erzeugen
|*
\************************************************************************/
namespace
{
void lcl_initProperty( FmFormObj* _pObject, const ::rtl::OUString& _rPropName, const Any& _rValue )
{
try
{
Reference< XPropertySet > xModelSet( _pObject->GetUnoControlModel(), UNO_QUERY );
if ( xModelSet.is() )
xModelSet->setPropertyValue( _rPropName, _rValue );
}
catch( const Exception& )
{
DBG_ERROR( "lcl_initProperty: caught an exception!" );
}
}
}
IMPL_LINK(FmFormObjFactory, MakeObject, SdrObjFactory*, pObjFactory)
{
if (pObjFactory->nInventor == FmFormInventor)
{
::rtl::OUString sServiceSpecifier;
typedef ::std::vector< ::std::pair< ::rtl::OUString, Any > > PropertyValueArray;
PropertyValueArray aInitialProperties;
switch ( pObjFactory->nIdentifier )
{
case OBJ_FM_EDIT:
sServiceSpecifier = FM_COMPONENT_EDIT;
break;
case OBJ_FM_BUTTON:
sServiceSpecifier = FM_COMPONENT_COMMANDBUTTON;
break;
case OBJ_FM_FIXEDTEXT:
sServiceSpecifier = FM_COMPONENT_FIXEDTEXT;
break;
case OBJ_FM_LISTBOX:
sServiceSpecifier = FM_COMPONENT_LISTBOX;
break;
case OBJ_FM_CHECKBOX:
sServiceSpecifier = FM_COMPONENT_CHECKBOX;
break;
case OBJ_FM_RADIOBUTTON:
sServiceSpecifier = FM_COMPONENT_RADIOBUTTON;
break;
case OBJ_FM_GROUPBOX:
sServiceSpecifier = FM_COMPONENT_GROUPBOX;
break;
case OBJ_FM_COMBOBOX:
sServiceSpecifier = FM_COMPONENT_COMBOBOX;
break;
case OBJ_FM_GRID:
sServiceSpecifier = FM_COMPONENT_GRID;
break;
case OBJ_FM_IMAGEBUTTON:
sServiceSpecifier = FM_COMPONENT_IMAGEBUTTON;
break;
case OBJ_FM_FILECONTROL:
sServiceSpecifier = FM_COMPONENT_FILECONTROL;
break;
case OBJ_FM_DATEFIELD:
sServiceSpecifier = FM_COMPONENT_DATEFIELD;
break;
case OBJ_FM_TIMEFIELD:
sServiceSpecifier = FM_COMPONENT_TIMEFIELD;
aInitialProperties.push_back( PropertyValueArray::value_type( FM_PROP_TIMEMAX, makeAny( (sal_Int32)( Time( 23, 59, 59, 99 ).GetTime() ) ) ) );
break;
case OBJ_FM_NUMERICFIELD:
sServiceSpecifier = FM_COMPONENT_NUMERICFIELD;
break;
case OBJ_FM_CURRENCYFIELD:
sServiceSpecifier = FM_COMPONENT_CURRENCYFIELD;
break;
case OBJ_FM_PATTERNFIELD:
sServiceSpecifier = FM_COMPONENT_PATTERNFIELD;
break;
case OBJ_FM_HIDDEN:
sServiceSpecifier = FM_COMPONENT_HIDDEN;
break;
case OBJ_FM_IMAGECONTROL:
sServiceSpecifier = FM_COMPONENT_IMAGECONTROL;
break;
case OBJ_FM_FORMATTEDFIELD:
sServiceSpecifier = FM_COMPONENT_FORMATTEDFIELD;
break;
case OBJ_FM_NAVIGATIONBAR:
sServiceSpecifier = FM_SUN_COMPONENT_NAVIGATIONBAR;
break;
case OBJ_FM_SCROLLBAR:
sServiceSpecifier = FM_SUN_COMPONENT_SCROLLBAR;
aInitialProperties.push_back( PropertyValueArray::value_type( FM_PROP_BORDER, makeAny( (sal_Int16)0 ) ) );
break;
case OBJ_FM_SPINBUTTON:
sServiceSpecifier = FM_SUN_COMPONENT_SPINBUTTON;
aInitialProperties.push_back( PropertyValueArray::value_type( FM_PROP_BORDER, makeAny( (sal_Int16)0 ) ) );
break;
}
// create the actual object
if ( sServiceSpecifier.getLength() )
pObjFactory->pNewObj = new FmFormObj( sServiceSpecifier, pObjFactory->nIdentifier );
else
pObjFactory->pNewObj = new FmFormObj( pObjFactory->nIdentifier );
// initialize some properties which we want to differ from the defaults
for ( PropertyValueArray::const_iterator aInitProp = aInitialProperties.begin();
aInitProp != aInitialProperties.end();
++aInitProp
)
{
lcl_initProperty(
static_cast< FmFormObj* >( pObjFactory->pNewObj ),
aInitProp->first,
aInitProp->second
);
}
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
* XMSS Tools
* (C) 2017 Matthias Gierlings
*
* Botan is released under the Simplified BSD License (see license.txt)
**/
#include <botan/xmss_tools.h>
namespace Botan {
#if defined(BOTAN_TARGET_OS_HAS_THREADS)
size_t XMSS_Tools::max_threads()
{
static const size_t threads { bench_threads() };
return threads;
}
size_t XMSS_Tools::bench_threads()
{
if(std::thread::hardware_concurrency() <= 1)
{
return 1;
}
const size_t BENCH_ITERATIONS = 1000;
std::vector<std::thread> threads;
threads.reserve(std::thread::hardware_concurrency());
std::vector<std::chrono::nanoseconds> durations;
std::vector<size_t> concurrency { std::thread::hardware_concurrency(),
std::thread::hardware_concurrency() / 2 };
for(const auto& cc : concurrency)
{
AutoSeeded_RNG rng;
std::vector<XMSS_Hash> hash(std::thread::hardware_concurrency(),
XMSS_Hash("SHA-256"));
std::vector<secure_vector<uint8_t>> data(
std::thread::hardware_concurrency(),
rng.random_vec(hash[0].output_length()));
auto start = std::chrono::high_resolution_clock::now();
for(size_t i = 0; i < cc; ++i)
{
auto& hs = hash[i];
auto& d = data[i];
threads.emplace_back(
std::thread([&BENCH_ITERATIONS, &i, &cc, &hs, &d]()
{
for(size_t n = 0;
n < BENCH_ITERATIONS * (std::thread::hardware_concurrency() /
cc);
n++)
{
hs.h(d, d, d);
}
}
));
}
durations.emplace_back(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now() - start));
for(auto& t : threads)
{
t.join();
}
threads.clear();
}
if(durations[0].count() < durations[1].count())
{
return concurrency[0];
}
else
{
return concurrency[1];
}
}
#endif
}
<commit_msg>Clean up XMSS self-benchmark<commit_after>/*
* XMSS Tools
* (C) 2017 Matthias Gierlings
*
* Botan is released under the Simplified BSD License (see license.txt)
**/
#include <botan/xmss_tools.h>
namespace Botan {
#if defined(BOTAN_TARGET_OS_HAS_THREADS)
size_t XMSS_Tools::max_threads()
{
static const size_t threads { bench_threads() };
return threads;
}
size_t XMSS_Tools::bench_threads()
{
if(std::thread::hardware_concurrency() <= 1)
{
return 1;
}
const size_t BENCH_ITERATIONS = 1000;
std::vector<std::thread> threads;
threads.reserve(std::thread::hardware_concurrency());
std::vector<std::chrono::nanoseconds> durations;
std::vector<size_t> concurrency { std::thread::hardware_concurrency(),
std::thread::hardware_concurrency() / 2 };
for(const auto& cc : concurrency)
{
AutoSeeded_RNG rng;
std::vector<XMSS_Hash> hash(std::thread::hardware_concurrency(),
XMSS_Hash("SHA-256"));
std::vector<secure_vector<uint8_t>> data(
std::thread::hardware_concurrency(),
rng.random_vec(hash[0].output_length()));
auto start = std::chrono::high_resolution_clock::now();
for(size_t i = 0; i < cc; ++i)
{
auto& hs = hash[i];
auto& d = data[i];
const size_t n_iters = BENCH_ITERATIONS * (std::thread::hardware_concurrency() / cc);
threads.emplace_back(std::thread([n_iters, &hs, &d]()
{
for(size_t n = 0; n < n_iters; n++)
{
hs.h(d, d, d);
}
}
));
}
durations.emplace_back(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now() - start));
for(auto& t : threads)
{
t.join();
}
threads.clear();
}
if(durations[0].count() < durations[1].count())
{
return concurrency[0];
}
else
{
return concurrency[1];
}
}
#endif
}
<|endoftext|>
|
<commit_before>/*
* OS and machine specific utility functions
* (C) 2015,2016,2017 Jack Lloyd
* (C) 2016 Daniel Neus
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/internal/socket.h>
#include <botan/exceptn.h>
#include <chrono>
#if defined(BOTAN_HAS_BOOST_ASIO)
/*
* We don't need serial port support anyway, and asking for it
* causes macro conflicts with Darwin's termios.h when this
* file is included in the amalgamation. GH #350
*/
#define BOOST_ASIO_DISABLE_SERIAL_PORT
#include <boost/asio.hpp>
#endif
#if defined(BOTAN_TARGET_OS_TYPE_IS_UNIX)
#if !defined(BOTAN_HAS_BOOST_ASIO)
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#endif
#elif defined(BOTAN_TARGET_OS_TYPE_IS_WINDOWS)
#include <botan/mem_ops.h>
#define NOMINMAX 1
#if !defined(BOTAN_HAS_BOOST_ASIO)
#include <winsock2.h>
#include <ws2tcpip.h>
#endif
#include <windows.h>
#endif
namespace Botan {
namespace {
#if defined(BOTAN_HAS_BOOST_ASIO)
class Asio_Socket final : public OS::Socket
{
public:
Asio_Socket(const std::string& hostname, const std::string& service) :
m_tcp(m_io)
{
boost::asio::ip::tcp::resolver resolver(m_io);
boost::asio::ip::tcp::resolver::query query(hostname, service);
boost::asio::connect(m_tcp, resolver.resolve(query));
}
void write(const uint8_t buf[], size_t len) override
{
boost::asio::write(m_tcp, boost::asio::buffer(buf, len));
}
size_t read(uint8_t buf[], size_t len) override
{
boost::system::error_code error;
size_t got = m_tcp.read_some(boost::asio::buffer(buf, len), error);
if(error)
{
if(error == boost::asio::error::eof)
return 0;
throw boost::system::system_error(error); // Some other error.
}
return got;
}
private:
boost::asio::io_service m_io;
boost::asio::ip::tcp::socket m_tcp;
};
#elif defined(BOTAN_TARGET_OS_TYPE_IS_WINDOWS)
class Winsock_Socket final : public OS::Socket
{
public:
Winsock_Socket(const std::string& hostname, const std::string& service)
{
WSAData wsa_data;
WORD wsa_version = MAKEWORD(2, 2);
if (::WSAStartup(wsa_version, &wsa_data) != 0)
{
throw Exception("WSAStartup() failed: " + std::to_string(WSAGetLastError()));
}
if (LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2)
{
::WSACleanup();
throw Exception("Could not find a usable version of Winsock.dll");
}
addrinfo hints;
::memset(&hints, 0, sizeof(addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
addrinfo* res;
if(::getaddrinfo(hostname.c_str(), service.c_str(), &hints, &res) != 0)
{
throw Exception("Name resolution failed for " + hostname);
}
for(addrinfo* rp = res; (m_socket == INVALID_SOCKET) && (rp != nullptr); rp = rp->ai_next)
{
m_socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
// unsupported socket type?
if(m_socket == INVALID_SOCKET)
continue;
if(::connect(m_socket, rp->ai_addr, rp->ai_addrlen) != 0)
{
::closesocket(m_socket);
m_socket = INVALID_SOCKET;
continue;
}
}
::freeaddrinfo(res);
if(m_socket == INVALID_SOCKET)
{
throw Exception("Connecting to " + hostname +
" for service " + service + " failed");
}
}
~Winsock_Socket()
{
::closesocket(m_socket);
m_socket = INVALID_SOCKET;
::WSACleanup();
}
void write(const uint8_t buf[], size_t len) override
{
size_t sent_so_far = 0;
while(sent_so_far != len)
{
const size_t left = len - sent_so_far;
int sent = ::send(m_socket,
cast_uint8_ptr_to_char(buf + sent_so_far),
static_cast<int>(left),
0);
if(sent == SOCKET_ERROR)
throw Exception("Socket write failed with error " +
std::to_string(::WSAGetLastError()));
else
sent_so_far += static_cast<size_t>(sent);
}
}
size_t read(uint8_t buf[], size_t len) override
{
int got = ::recv(m_socket,
cast_uint8_ptr_to_char(buf),
static_cast<int>(len), 0);
if(got == SOCKET_ERROR)
throw Exception("Socket read failed with error " +
std::to_string(::WSAGetLastError()));
return static_cast<size_t>(got);
}
private:
SOCKET m_socket = INVALID_SOCKET;
};
#elif defined(BOTAN_TARGET_OS_TYPE_IS_UNIX)
class BSD_Socket final : public OS::Socket
{
public:
BSD_Socket(const std::string& hostname, const std::string& service)
{
addrinfo hints;
::memset(&hints, 0, sizeof(addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
addrinfo* res;
if(::getaddrinfo(hostname.c_str(), service.c_str(), &hints, &res) != 0)
{
throw Exception("Name resolution failed for " + hostname);
}
m_fd = -1;
for(addrinfo* rp = res; (m_fd < 0) && (rp != nullptr); rp = rp->ai_next)
{
m_fd = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if(m_fd < 0)
{
// unsupported socket type?
continue;
}
if(::connect(m_fd, rp->ai_addr, rp->ai_addrlen) != 0)
{
::close(m_fd);
m_fd = -1;
continue;
}
}
::freeaddrinfo(res);
if(m_fd < 0)
{
throw Exception("Connecting to " + hostname +
" for service " + service + " failed");
}
}
~BSD_Socket()
{
::close(m_fd);
m_fd = -1;
}
void write(const uint8_t buf[], size_t len) override
{
size_t sent_so_far = 0;
while(sent_so_far != len)
{
const size_t left = len - sent_so_far;
ssize_t sent = ::write(m_fd, &buf[sent_so_far], left);
if(sent < 0)
throw Exception("Socket write failed with error '" +
std::string(::strerror(errno)) + "'");
else
sent_so_far += static_cast<size_t>(sent);
}
}
size_t read(uint8_t buf[], size_t len) override
{
ssize_t got = ::read(m_fd, buf, len);
if(got < 0)
throw Exception("Socket read failed with error '" +
std::string(::strerror(errno)) + "'");
return static_cast<size_t>(got);
}
private:
int m_fd;
};
#endif
}
std::unique_ptr<OS::Socket>
OS::open_socket(const std::string& hostname,
const std::string& service)
{
#if defined(BOTAN_HAS_BOOST_ASIO)
return std::unique_ptr<OS::Socket>(new Asio_Socket(hostname, service));
#elif defined(BOTAN_TARGET_OS_TYPE_IS_WINDOWS)
return std::unique_ptr<OS::Socket>(new Winsock_Socket(hostname, service));
#elif defined(BOTAN_TARGET_OS_TYPE_IS_UNIX)
return std::unique_ptr<OS::Socket>(new BSD_Socket(hostname, service));
#else
// No sockets for you
return std::unique_ptr<Socket>();
#endif
}
}
<commit_msg>Simplify header includes in socket.cpp<commit_after>/*
* OS and machine specific utility functions
* (C) 2015,2016,2017 Jack Lloyd
* (C) 2016 Daniel Neus
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/internal/socket.h>
#include <botan/exceptn.h>
#include <botan/mem_ops.h>
#include <chrono>
#if defined(BOTAN_HAS_BOOST_ASIO)
/*
* We don't need serial port support anyway, and asking for it
* causes macro conflicts with Darwin's termios.h when this
* file is included in the amalgamation. GH #350
*/
#define BOOST_ASIO_DISABLE_SERIAL_PORT
#include <boost/asio.hpp>
#elif defined(BOTAN_TARGET_OS_TYPE_IS_UNIX)
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#elif defined(BOTAN_TARGET_OS_TYPE_IS_WINDOWS)
#define NOMINMAX 1
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#endif
namespace Botan {
namespace {
#if defined(BOTAN_HAS_BOOST_ASIO)
class Asio_Socket final : public OS::Socket
{
public:
Asio_Socket(const std::string& hostname, const std::string& service) :
m_tcp(m_io)
{
boost::asio::ip::tcp::resolver resolver(m_io);
boost::asio::ip::tcp::resolver::query query(hostname, service);
boost::asio::connect(m_tcp, resolver.resolve(query));
}
void write(const uint8_t buf[], size_t len) override
{
boost::asio::write(m_tcp, boost::asio::buffer(buf, len));
}
size_t read(uint8_t buf[], size_t len) override
{
boost::system::error_code error;
size_t got = m_tcp.read_some(boost::asio::buffer(buf, len), error);
if(error)
{
if(error == boost::asio::error::eof)
return 0;
throw boost::system::system_error(error); // Some other error.
}
return got;
}
private:
boost::asio::io_service m_io;
boost::asio::ip::tcp::socket m_tcp;
};
#elif defined(BOTAN_TARGET_OS_TYPE_IS_WINDOWS)
class Winsock_Socket final : public OS::Socket
{
public:
Winsock_Socket(const std::string& hostname, const std::string& service)
{
WSAData wsa_data;
WORD wsa_version = MAKEWORD(2, 2);
if (::WSAStartup(wsa_version, &wsa_data) != 0)
{
throw Exception("WSAStartup() failed: " + std::to_string(WSAGetLastError()));
}
if (LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2)
{
::WSACleanup();
throw Exception("Could not find a usable version of Winsock.dll");
}
addrinfo hints;
::memset(&hints, 0, sizeof(addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
addrinfo* res;
if(::getaddrinfo(hostname.c_str(), service.c_str(), &hints, &res) != 0)
{
throw Exception("Name resolution failed for " + hostname);
}
for(addrinfo* rp = res; (m_socket == INVALID_SOCKET) && (rp != nullptr); rp = rp->ai_next)
{
m_socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
// unsupported socket type?
if(m_socket == INVALID_SOCKET)
continue;
if(::connect(m_socket, rp->ai_addr, rp->ai_addrlen) != 0)
{
::closesocket(m_socket);
m_socket = INVALID_SOCKET;
continue;
}
}
::freeaddrinfo(res);
if(m_socket == INVALID_SOCKET)
{
throw Exception("Connecting to " + hostname +
" for service " + service + " failed");
}
}
~Winsock_Socket()
{
::closesocket(m_socket);
m_socket = INVALID_SOCKET;
::WSACleanup();
}
void write(const uint8_t buf[], size_t len) override
{
size_t sent_so_far = 0;
while(sent_so_far != len)
{
const size_t left = len - sent_so_far;
int sent = ::send(m_socket,
cast_uint8_ptr_to_char(buf + sent_so_far),
static_cast<int>(left),
0);
if(sent == SOCKET_ERROR)
throw Exception("Socket write failed with error " +
std::to_string(::WSAGetLastError()));
else
sent_so_far += static_cast<size_t>(sent);
}
}
size_t read(uint8_t buf[], size_t len) override
{
int got = ::recv(m_socket,
cast_uint8_ptr_to_char(buf),
static_cast<int>(len), 0);
if(got == SOCKET_ERROR)
throw Exception("Socket read failed with error " +
std::to_string(::WSAGetLastError()));
return static_cast<size_t>(got);
}
private:
SOCKET m_socket = INVALID_SOCKET;
};
#elif defined(BOTAN_TARGET_OS_TYPE_IS_UNIX)
class BSD_Socket final : public OS::Socket
{
public:
BSD_Socket(const std::string& hostname, const std::string& service)
{
addrinfo hints;
::memset(&hints, 0, sizeof(addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
addrinfo* res;
if(::getaddrinfo(hostname.c_str(), service.c_str(), &hints, &res) != 0)
{
throw Exception("Name resolution failed for " + hostname);
}
m_fd = -1;
for(addrinfo* rp = res; (m_fd < 0) && (rp != nullptr); rp = rp->ai_next)
{
m_fd = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if(m_fd < 0)
{
// unsupported socket type?
continue;
}
if(::connect(m_fd, rp->ai_addr, rp->ai_addrlen) != 0)
{
::close(m_fd);
m_fd = -1;
continue;
}
}
::freeaddrinfo(res);
if(m_fd < 0)
{
throw Exception("Connecting to " + hostname +
" for service " + service + " failed");
}
}
~BSD_Socket()
{
::close(m_fd);
m_fd = -1;
}
void write(const uint8_t buf[], size_t len) override
{
size_t sent_so_far = 0;
while(sent_so_far != len)
{
const size_t left = len - sent_so_far;
ssize_t sent = ::write(m_fd, &buf[sent_so_far], left);
if(sent < 0)
throw Exception("Socket write failed with error '" +
std::string(::strerror(errno)) + "'");
else
sent_so_far += static_cast<size_t>(sent);
}
}
size_t read(uint8_t buf[], size_t len) override
{
ssize_t got = ::read(m_fd, buf, len);
if(got < 0)
throw Exception("Socket read failed with error '" +
std::string(::strerror(errno)) + "'");
return static_cast<size_t>(got);
}
private:
int m_fd;
};
#endif
}
std::unique_ptr<OS::Socket>
OS::open_socket(const std::string& hostname,
const std::string& service)
{
#if defined(BOTAN_HAS_BOOST_ASIO)
return std::unique_ptr<OS::Socket>(new Asio_Socket(hostname, service));
#elif defined(BOTAN_TARGET_OS_TYPE_IS_WINDOWS)
return std::unique_ptr<OS::Socket>(new Winsock_Socket(hostname, service));
#elif defined(BOTAN_TARGET_OS_TYPE_IS_UNIX)
return std::unique_ptr<OS::Socket>(new BSD_Socket(hostname, service));
#else
// No sockets for you
return std::unique_ptr<Socket>();
#endif
}
}
<|endoftext|>
|
<commit_before>/*
* SamplePlayerSW.cpp
*
* Created on: Dec 28, 2013
* Author: lukas
*/
#include "SamplePlayer_SW.h"
SamplePlayer_SW::SamplePlayer_SW(std::vector<std::string> params) : SamplePlayer(params) {
m_StringToLoadPolicyMap["LOAD_ON_DEMAND"] = LOAD_ON_DEMAND;
m_StringToLoadPolicyMap["PRELOAD"] = PRELOAD;
m_StringToLoadPolicyMap["PRELOAD_DECOMPRESS"] = PRELOAD_DECOMPRESS;
m_LoadingPolicy = PRELOAD_DECOMPRESS; /* Set preload as default loading policy */
m_Playbackstate = STOP;
m_CompressedDataBuffer = NULL;
m_DecompressedDataBuffer = NULL;
m_CurrentPlaybackOffset = 0;
m_DecompressedDataSize = 0;
/* First parameter should be the filename */
if (params.size() > 0) {
m_SourceFile = params[0];
m_Codec = NULL;
m_Decoded_Frame = NULL;
m_CodecCtx = NULL;
m_ContainerCtx = NULL;
if(params.size() > 1){
std::string policyStr = params[1];
std::transform(policyStr.begin(), policyStr.end(), policyStr.begin(), ::toupper);
std::map<std::string, eLoadPolicy>::iterator iter = m_StringToLoadPolicyMap.find(params[1]);
if(iter != m_StringToLoadPolicyMap.end()){
m_LoadingPolicy = iter->second;
}else{
LOG_WARNING("Unknown loading policy: " << policyStr);
}
}
}
}
SamplePlayer_SW::~SamplePlayer_SW() {
avcodec_close(m_CodecCtx);
}
void SamplePlayer_SW::initCodec() {
avcodec_register_all();
av_register_all();
AVDictionary* dict;
int stream_index = -1;
if (avformat_open_input(&m_ContainerCtx, m_SourceFile.c_str(), NULL, NULL) < 0) {
LOG_ERROR("Cound not open file: " << m_SourceFile.c_str());
}
avformat_find_stream_info(m_ContainerCtx, NULL);
LOG_INFO("Loading audio file " << m_SourceFile);
LOG_INFO("#Streams: " << m_ContainerCtx->nb_streams);
for (unsigned int i = 0; i < m_ContainerCtx->nb_streams; i++) {
if (m_ContainerCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
stream_index = i;
break;
}
}
if(stream_index == -1){
LOG_ERROR("Could not find audio");
}
m_CodecCtx = m_ContainerCtx->streams[stream_index]->codec;
m_Codec = avcodec_find_decoder(m_CodecCtx->codec_id);
if (!m_Codec) {
LOG_ERROR("Codec not found");
avformat_close_input(&m_ContainerCtx);
exit(1);
}
/* request internal sample format */
LOG_INFO("Codec tag: "<< m_Codec->name << ", Codec ID: " << m_Codec->id);
LOG_DEBUG("#Channels: " << m_CodecCtx->channels);
/* open it */
if (avcodec_open2(m_CodecCtx, m_Codec, NULL) < 0) {
LOG_ERROR("Could not open codec");
exit(1);
}
}
void SamplePlayer_SW::init() {
AVPacket avpkt;
ReSampleContext* resmplCtx;
int compressed_bytes_consumed = 0;
int compressed_file_size = 0;
uint8_t* l_ResampleBuffer;
initCodec(); /* Initialize audio codec */
av_init_packet(&avpkt); /* Initialize packet */
// resmplCtx = av_audio_resample_init(m_CodecCtx->channels,
// m_CodecCtx->channels,
// Synthesizer::config::samplerate,
// m_CodecCtx->sample_rate,
// AV_SAMPLE_FMT_S32,
// m_CodecCtx->sample_fmt,
// 16, 10, 0, 1.0);
m_DecompressedDataBuffer = new uint8_t[AVCODEC_MAX_AUDIO_FRAME_SIZE * MAX_PLAYBACK_LENGTH_SEC];
memset(m_DecompressedDataBuffer, 0 ,AVCODEC_MAX_AUDIO_FRAME_SIZE * MAX_PLAYBACK_LENGTH_SEC);
LOG_DEBUG("Decoding audio file");
LOG_DEBUG("Sample format:" << av_get_sample_fmt_name(m_CodecCtx->sample_fmt));
while (!av_read_frame(m_ContainerCtx, &avpkt)) {
int got_frame = 0;
if (!m_Decoded_Frame) {
if (!(m_Decoded_Frame = avcodec_alloc_frame())) { /* allocate once */
LOG_ERROR("Could not allocate audio frame");
exit(1);
}
}else{
avcodec_get_frame_defaults(m_Decoded_Frame);
}
compressed_bytes_consumed = avcodec_decode_audio4(m_CodecCtx, m_Decoded_Frame, &got_frame, &avpkt);
if (compressed_bytes_consumed < 0) {
LOG_ERROR("Error while decoding audio frame");
exit(1);
}
if (got_frame) {
int samples_written = 0;
int data_size = 0;
size_t resampled_Bytes = 0;
/* if a frame has been decoded, output it */
data_size = av_samples_get_buffer_size(NULL, m_CodecCtx->channels, m_Decoded_Frame->nb_samples, m_CodecCtx->sample_fmt, 1);
int32_t* buf = (int32_t*) (m_DecompressedDataBuffer + m_DecompressedDataSize);
switch(m_CodecCtx->sample_fmt){
case AV_SAMPLE_FMT_NONE:
case AV_SAMPLE_FMT_U8:
// for(int i = 0; i < m_Decoded_Frame->nb_samples * m_CodecCtx->channels; i++){
// buf[i] = (int32_t)( ((int8_t*) m_Decoded_Frame->data[0])[i] << 24 );
// }
// break;
//FIXME: convert other sample formats
case AV_SAMPLE_FMT_S16:
for(int i = 0; i < m_Decoded_Frame->nb_samples * m_CodecCtx->channels; i++){
buf[i] = *(((short*)m_Decoded_Frame->data[0]) + i) << 16;
}
m_DecompressedDataSize += m_Decoded_Frame->nb_samples * m_CodecCtx->channels * av_get_bytes_per_sample(AV_SAMPLE_FMT_S32);
break;
case AV_SAMPLE_FMT_S32:
memcpy(m_DecompressedDataBuffer + m_DecompressedDataSize, m_Decoded_Frame->data[0], data_size);
m_DecompressedDataSize += data_size;
break;
case AV_SAMPLE_FMT_FLT:
case AV_SAMPLE_FMT_DBL:
case AV_SAMPLE_FMT_U8P:
case AV_SAMPLE_FMT_S16P:
case AV_SAMPLE_FMT_S32P:
case AV_SAMPLE_FMT_FLTP:
case AV_SAMPLE_FMT_DBLP:
default:
LOG_ERROR("Sample format is not supported");
}
}
}
char* writeLeftPortPtr = m_SoundOut_Left_1_Port->getWriteBuffer();
char* writeRightPortPtr = m_SoundOut_Right_2_Port->getWriteBuffer();
memset(writeLeftPortPtr, 0, Synthesizer::config::bytesPerBlock);
memset(writeRightPortPtr, 0, Synthesizer::config::bytesPerBlock);
m_Trigger_1_Port->registerCallback(ICallbackPtr(new OnValueChange<int, ControlPortPtr>(trigger, m_Trigger_1_Port)));
// audio_resample_close(resmplCtx);
// av_free(m_CodecCtx);
// av_free(m_Decoded_Frame);
// avformat_free_context(m_ContainerCtx);
}
void SamplePlayer_SW::process() {
int* writeLeftPortPtr = (int*)m_SoundOut_Left_1_Port->getWriteBuffer();
int* writeRightPortPtr = (int*)m_SoundOut_Right_2_Port->getWriteBuffer();
//int trigger = (int) m_Trigger_1_Port->pop();
if(trigger || (m_CurrentPlaybackOffset > 0 && m_CurrentPlaybackOffset < m_DecompressedDataSize)){
switch(m_CodecCtx->channels){
case 1:
/*
* Copy samples to left and right channel
*/
memcpy(writeLeftPortPtr, m_DecompressedDataBuffer + m_CurrentPlaybackOffset, Synthesizer::config::bytesPerBlock);
memcpy(writeRightPortPtr, m_DecompressedDataBuffer + m_CurrentPlaybackOffset, Synthesizer::config::bytesPerBlock);
m_CurrentPlaybackOffset += Synthesizer::config::bytesPerBlock;
//TODO: Add padding zeros when playbackoffset > n* blocksize
break;
case 2:
/*
* Copy interleaved audio samples to left and right channel
*/
for(int i = 0; i < Synthesizer::config::blocksize; i++){
writeLeftPortPtr[i] = *((int*)(m_DecompressedDataBuffer + m_CurrentPlaybackOffset));
writeRightPortPtr[i] = *((int*)(m_DecompressedDataBuffer + m_CurrentPlaybackOffset + Synthesizer::config::bytesPerSample));
m_CurrentPlaybackOffset += Synthesizer::config::bytesPerSample * 2;
if(m_CurrentPlaybackOffset >= m_DecompressedDataSize){
/* pad with zero */
for(int j = i; j < Synthesizer::config::blocksize; j++){
writeLeftPortPtr[j] = 0;
writeRightPortPtr[j] = 0;
}
break;
}
}
break;
default:
LOG_ERROR("Unsupported number of channels: " << m_CodecCtx->channels);
}
if(m_CurrentPlaybackOffset >= m_DecompressedDataSize){
m_CurrentPlaybackOffset = 0;
}
}else{
memset((char*)writeLeftPortPtr, 0, Synthesizer::config::bytesPerBlock);
memset((char*)writeRightPortPtr, 0, Synthesizer::config::bytesPerBlock);
m_CurrentPlaybackOffset = 0;
}
}
<commit_msg>Disabled the second sampleplayer channel. Has only one output in the component list and would otherwise be the only component with stereo support anyway<commit_after>/*
* SamplePlayerSW.cpp
*
* Created on: Dec 28, 2013
* Author: lukas
*/
#include "SamplePlayer_SW.h"
SamplePlayer_SW::SamplePlayer_SW(std::vector<std::string> params) : SamplePlayer(params) {
m_StringToLoadPolicyMap["LOAD_ON_DEMAND"] = LOAD_ON_DEMAND;
m_StringToLoadPolicyMap["PRELOAD"] = PRELOAD;
m_StringToLoadPolicyMap["PRELOAD_DECOMPRESS"] = PRELOAD_DECOMPRESS;
m_LoadingPolicy = PRELOAD_DECOMPRESS; /* Set preload as default loading policy */
m_Playbackstate = STOP;
m_CompressedDataBuffer = NULL;
m_DecompressedDataBuffer = NULL;
m_CurrentPlaybackOffset = 0;
m_DecompressedDataSize = 0;
/* First parameter should be the filename */
if (params.size() > 0) {
m_SourceFile = params[0];
m_Codec = NULL;
m_Decoded_Frame = NULL;
m_CodecCtx = NULL;
m_ContainerCtx = NULL;
if(params.size() > 1){
std::string policyStr = params[1];
std::transform(policyStr.begin(), policyStr.end(), policyStr.begin(), ::toupper);
std::map<std::string, eLoadPolicy>::iterator iter = m_StringToLoadPolicyMap.find(params[1]);
if(iter != m_StringToLoadPolicyMap.end()){
m_LoadingPolicy = iter->second;
}else{
LOG_WARNING("Unknown loading policy: " << policyStr);
}
}
}
}
SamplePlayer_SW::~SamplePlayer_SW() {
avcodec_close(m_CodecCtx);
}
void SamplePlayer_SW::initCodec() {
avcodec_register_all();
av_register_all();
AVDictionary* dict;
int stream_index = -1;
if (avformat_open_input(&m_ContainerCtx, m_SourceFile.c_str(), NULL, NULL) < 0) {
LOG_ERROR("Cound not open file: " << m_SourceFile.c_str());
}
avformat_find_stream_info(m_ContainerCtx, NULL);
LOG_INFO("Loading audio file " << m_SourceFile);
LOG_INFO("#Streams: " << m_ContainerCtx->nb_streams);
for (unsigned int i = 0; i < m_ContainerCtx->nb_streams; i++) {
if (m_ContainerCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
stream_index = i;
break;
}
}
if(stream_index == -1){
LOG_ERROR("Could not find audio");
}
m_CodecCtx = m_ContainerCtx->streams[stream_index]->codec;
m_Codec = avcodec_find_decoder(m_CodecCtx->codec_id);
if (!m_Codec) {
LOG_ERROR("Codec not found");
avformat_close_input(&m_ContainerCtx);
exit(1);
}
/* request internal sample format */
LOG_INFO("Codec tag: "<< m_Codec->name << ", Codec ID: " << m_Codec->id);
LOG_DEBUG("#Channels: " << m_CodecCtx->channels);
/* open it */
if (avcodec_open2(m_CodecCtx, m_Codec, NULL) < 0) {
LOG_ERROR("Could not open codec");
exit(1);
}
}
void SamplePlayer_SW::init() {
AVPacket avpkt;
ReSampleContext* resmplCtx;
int compressed_bytes_consumed = 0;
int compressed_file_size = 0;
uint8_t* l_ResampleBuffer;
initCodec(); /* Initialize audio codec */
av_init_packet(&avpkt); /* Initialize packet */
// resmplCtx = av_audio_resample_init(m_CodecCtx->channels,
// m_CodecCtx->channels,
// Synthesizer::config::samplerate,
// m_CodecCtx->sample_rate,
// AV_SAMPLE_FMT_S32,
// m_CodecCtx->sample_fmt,
// 16, 10, 0, 1.0);
m_DecompressedDataBuffer = new uint8_t[AVCODEC_MAX_AUDIO_FRAME_SIZE * MAX_PLAYBACK_LENGTH_SEC];
memset(m_DecompressedDataBuffer, 0 ,AVCODEC_MAX_AUDIO_FRAME_SIZE * MAX_PLAYBACK_LENGTH_SEC);
LOG_DEBUG("Decoding audio file");
LOG_DEBUG("Sample format:" << av_get_sample_fmt_name(m_CodecCtx->sample_fmt));
while (!av_read_frame(m_ContainerCtx, &avpkt)) {
int got_frame = 0;
if (!m_Decoded_Frame) {
if (!(m_Decoded_Frame = avcodec_alloc_frame())) { /* allocate once */
LOG_ERROR("Could not allocate audio frame");
exit(1);
}
}else{
avcodec_get_frame_defaults(m_Decoded_Frame);
}
compressed_bytes_consumed = avcodec_decode_audio4(m_CodecCtx, m_Decoded_Frame, &got_frame, &avpkt);
if (compressed_bytes_consumed < 0) {
LOG_ERROR("Error while decoding audio frame");
exit(1);
}
if (got_frame) {
int samples_written = 0;
int data_size = 0;
size_t resampled_Bytes = 0;
/* if a frame has been decoded, output it */
data_size = av_samples_get_buffer_size(NULL, m_CodecCtx->channels, m_Decoded_Frame->nb_samples, m_CodecCtx->sample_fmt, 1);
int32_t* buf = (int32_t*) (m_DecompressedDataBuffer + m_DecompressedDataSize);
switch(m_CodecCtx->sample_fmt){
case AV_SAMPLE_FMT_NONE:
case AV_SAMPLE_FMT_U8:
// for(int i = 0; i < m_Decoded_Frame->nb_samples * m_CodecCtx->channels; i++){
// buf[i] = (int32_t)( ((int8_t*) m_Decoded_Frame->data[0])[i] << 24 );
// }
// break;
//FIXME: convert other sample formats
case AV_SAMPLE_FMT_S16:
for(int i = 0; i < m_Decoded_Frame->nb_samples * m_CodecCtx->channels; i++){
buf[i] = *(((short*)m_Decoded_Frame->data[0]) + i) << 16;
}
m_DecompressedDataSize += m_Decoded_Frame->nb_samples * m_CodecCtx->channels * av_get_bytes_per_sample(AV_SAMPLE_FMT_S32);
break;
case AV_SAMPLE_FMT_S32:
memcpy(m_DecompressedDataBuffer + m_DecompressedDataSize, m_Decoded_Frame->data[0], data_size);
m_DecompressedDataSize += data_size;
break;
case AV_SAMPLE_FMT_FLT:
case AV_SAMPLE_FMT_DBL:
case AV_SAMPLE_FMT_U8P:
case AV_SAMPLE_FMT_S16P:
case AV_SAMPLE_FMT_S32P:
case AV_SAMPLE_FMT_FLTP:
case AV_SAMPLE_FMT_DBLP:
default:
LOG_ERROR("Sample format is not supported");
}
}
}
char* writeLeftPortPtr = m_SoundOut_Left_1_Port->getWriteBuffer();
char* writeRightPortPtr = m_SoundOut_Right_2_Port->getWriteBuffer();
memset(writeLeftPortPtr, 0, Synthesizer::config::bytesPerBlock);
// memset(writeRightPortPtr, 0, Synthesizer::config::bytesPerBlock);
m_Trigger_1_Port->registerCallback(ICallbackPtr(new OnValueChange<int, ControlPortPtr>(trigger, m_Trigger_1_Port)));
// audio_resample_close(resmplCtx);
// av_free(m_CodecCtx);
// av_free(m_Decoded_Frame);
// avformat_free_context(m_ContainerCtx);
}
void SamplePlayer_SW::process() {
int* writeLeftPortPtr = (int*)m_SoundOut_Left_1_Port->getWriteBuffer();
int* writeRightPortPtr = (int*)m_SoundOut_Right_2_Port->getWriteBuffer();
//int trigger = (int) m_Trigger_1_Port->pop();
if(trigger || (m_CurrentPlaybackOffset > 0 && m_CurrentPlaybackOffset < m_DecompressedDataSize)){
switch(m_CodecCtx->channels){
case 1:
/*
* Copy samples to left and right channel
*/
memcpy(writeLeftPortPtr, m_DecompressedDataBuffer + m_CurrentPlaybackOffset, Synthesizer::config::bytesPerBlock);
memcpy(writeRightPortPtr, m_DecompressedDataBuffer + m_CurrentPlaybackOffset, Synthesizer::config::bytesPerBlock);
m_CurrentPlaybackOffset += Synthesizer::config::bytesPerBlock;
//TODO: Add padding zeros when playbackoffset > n* blocksize
break;
case 2:
/*
* Copy interleaved audio samples to left and right channel
*/
for(int i = 0; i < Synthesizer::config::blocksize; i++){
writeLeftPortPtr[i] = *((int*)(m_DecompressedDataBuffer + m_CurrentPlaybackOffset));
// writeRightPortPtr[i] = *((int*)(m_DecompressedDataBuffer + m_CurrentPlaybackOffset + Synthesizer::config::bytesPerSample));
m_CurrentPlaybackOffset += Synthesizer::config::bytesPerSample * 2;
if(m_CurrentPlaybackOffset >= m_DecompressedDataSize){
/* pad with zero */
for(int j = i; j < Synthesizer::config::blocksize; j++){
writeLeftPortPtr[j] = 0;
// writeRightPortPtr[j] = 0;
}
break;
}
}
break;
default:
LOG_ERROR("Unsupported number of channels: " << m_CodecCtx->channels);
}
if(m_CurrentPlaybackOffset >= m_DecompressedDataSize){
m_CurrentPlaybackOffset = 0;
}
}else{
memset((char*)writeLeftPortPtr, 0, Synthesizer::config::bytesPerBlock);
// memset((char*)writeRightPortPtr, 0, Synthesizer::config::bytesPerBlock);
m_CurrentPlaybackOffset = 0;
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: IDocumentUndoRedo.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2007-05-25 12:59: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 IDOCUMENTUNDOREDO_HXX_INCLUDED
#define IDOCUMENTUNDOREDO_HXX_INCLUDED
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
class SwUndoIter;
class SwRewriter;
class String;
class SwUndoIds;
class SwNodes;
class SwUndo;
typedef sal_uInt16 SwUndoNoModifiedPosition;
/** IDocumentUndoRedo
*/
class IDocumentUndoRedo
{
public:
/**
*/
virtual void SetUndoNoResetModified() = 0;
/**
*/
virtual bool IsUndoNoResetModified() const = 0;
/** UndoHistory am Dokument pflegen
bei Save, SaveAs, Create wird UndoHistory zurueckgesetzt ???
*/
virtual void DoUndo(bool bUn) = 0;
/**
*/
virtual bool DoesUndo() const = 0;
/** Zusammenfassen von Kontinuierlichen Insert/Delete/Overwrite von
Charaktern. Default ist ::com::sun::star::sdbcx::Group-Undo.
*/
virtual void DoGroupUndo(bool bUn) = 0;
/**
*/
virtual bool DoesGroupUndo() const = 0;
/** macht rueckgaengig:
0 letzte Aktion, sonst Aktionen bis zum Start der Klammerung nUndoId
In rUndoRange wird der restaurierte Bereich gesetzt.
*/
virtual bool Undo( SwUndoIter& ) = 0; // -> #111827#
/** Opens undo block.
@param nUndoId undo ID for the start object
@param pRewriter rewriter for comments @see SwUndo::GetComment
If the given nUndoId is equal to zero an undo object with ID
UNDO_START will be generated.
@return the undo ID of the created object
*/
virtual sal_uInt16 StartUndo( sal_uInt16 nUndoId, const SwRewriter * pRewriter) = 0;
/**
Closes undo block.
@param nUndoId undo ID for the closure object
@param pRewriter rewriter for comments @see SwUndo::GetComment
If the given nUndoId is equal to zero an undo object with ID
UNDO_START will be generated.
If pRewriter is not equal to zero the given rewriter will be
set for the generated closure object and the corresponding
start object. Otherwise an existent rewriter in theIDocumentRedlineAccess
corresponding start object will be propagated to the generated
closure object.
*/
virtual sal_uInt16 EndUndo( sal_uInt16 nUndoId, const SwRewriter * pRewriter) = 0;
/** <- #111827#
loescht die gesamten UndoObjecte ( fuer Methoden die am Nodes
Array drehen ohne entsprechendes Undo !!)
*/
virtual void DelAllUndoObj() = 0;
/** liefert die Id der letzten undofaehigen Aktion zurueck
oder USHRT_MAX fuellt ggf. VARARR mit ::com::sun::star::sdbcx::User-UndoIds
*/
virtual sal_uInt16 GetUndoIds(String* pStr, SwUndoIds *pUndoIds) const = 0;
/**
*/
virtual String GetUndoIdsStr(String* pStr, SwUndoIds *pUndoIds) const = 0;
/** gibt es Klammerung mit der Id?
*/
virtual bool HasUndoId(sal_uInt16 nId) const = 0;
/* @@@MAINTAINABILITY-HORROR@@@
Implementation details made public.
die drei folgenden Methoden werden beim Undo und nur dort
benoetigt. Sollten sonst nicht aufgerufen werden.
*/
virtual const SwNodes* GetUndoNds() const = 0;
virtual SwUndo* RemoveLastUndo(sal_uInt16 nUndoId) = 0;
/** 2002-05-31 dvo, #95884#: To prevent an undo array overflow when
doing nested undos, undo may have to be disabled. Undo-intensive
actions (like auto-format) should check this manually.
*/
virtual bool HasTooManyUndos() const = 0;
/**
*/
virtual bool Redo( SwUndoIter& ) = 0;
/** liefert die Id der letzten Redofaehigen Aktion zurueck
fuellt ggf. VARARR mit RedoIds
*/
virtual sal_uInt16 GetRedoIds( String* pStr, SwUndoIds *pRedoIds) const = 0;
/**
*/
virtual String GetRedoIdsStr( String* pStr, SwUndoIds *pRedoIds) const = 0;
/**
*/
virtual bool Repeat( SwUndoIter&, sal_uInt16 nRepeatCnt) = 0;
/** liefert die Id der letzten Repeatfaehigen Aktion zurueck
fuellt ggf. VARARR mit RedoIds
*/
virtual sal_uInt16 GetRepeatIds( String* pStr, SwUndoIds *pRedoIds) const = 0;
/**
*/
virtual String GetRepeatIdsStr( String* pStr, SwUndoIds *pRedoIds) const = 0;
/** interne Verkuerzung fuer Insert am Ende
*/
virtual void AppendUndo(SwUndo*) = 0;
/** loescht alle UndoObjecte von nUndoPos
bis zum Ende des Undo-Arrays
*/
virtual void ClearRedo() = 0;
/** Manipulates the position of the undo stack which reset the modified flag
*/
virtual void setUndoNoModifiedPosition( SwUndoNoModifiedPosition ) = 0;
/** Gets the position of the undo stack which reset the modified flag
*/
virtual SwUndoNoModifiedPosition getUndoNoModifiedPosition() const = 0;
protected:
virtual ~IDocumentUndoRedo() {};
};
#endif
<commit_msg>INTEGRATION: CWS swwarnings (1.3.198); FILE MERGED 2007/08/22 09:17:47 tl 1.3.198.4: #i69287# warning-free code 2007/08/22 09:09:11 tl 1.3.198.3: #i69287# warning-free code 2007/06/28 11:47:57 os 1.3.198.2: RESYNC: (1.3-1.4); FILE MERGED 2007/04/03 12:57:03 tl 1.3.198.1: #i69287# warning-free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: IDocumentUndoRedo.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2007-09-27 07:54:26 $
*
* 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 IDOCUMENTUNDOREDO_HXX_INCLUDED
#define IDOCUMENTUNDOREDO_HXX_INCLUDED
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _SWUNDO_HXX
#include <swundo.hxx>
#endif
class SwUndoIter;
class SwRewriter;
class String;
class SwUndoIds;
class SwNodes;
class SwUndo;
typedef sal_uInt16 SwUndoNoModifiedPosition;
/** IDocumentUndoRedo
*/
class IDocumentUndoRedo
{
public:
/**
*/
virtual void SetUndoNoResetModified() = 0;
/**
*/
virtual bool IsUndoNoResetModified() const = 0;
/** UndoHistory am Dokument pflegen
bei Save, SaveAs, Create wird UndoHistory zurueckgesetzt ???
*/
virtual void DoUndo(bool bUn) = 0;
/**
*/
virtual bool DoesUndo() const = 0;
/** Zusammenfassen von Kontinuierlichen Insert/Delete/Overwrite von
Charaktern. Default ist ::com::sun::star::sdbcx::Group-Undo.
*/
virtual void DoGroupUndo(bool bUn) = 0;
/**
*/
virtual bool DoesGroupUndo() const = 0;
/** macht rueckgaengig:
0 letzte Aktion, sonst Aktionen bis zum Start der Klammerung nUndoId
In rUndoRange wird der restaurierte Bereich gesetzt.
*/
virtual bool Undo( SwUndoIter& ) = 0; // -> #111827#
/** Opens undo block.
@param nUndoId undo ID for the start object
@param pRewriter rewriter for comments @see SwUndo::GetComment
If the given nUndoId is equal to zero an undo object with ID
UNDO_START will be generated.
@return the undo ID of the created object
*/
virtual SwUndoId StartUndo( SwUndoId eUndoId, const SwRewriter * pRewriter) = 0;
/**
Closes undo block.
@param nUndoId undo ID for the closure object
@param pRewriter rewriter for comments @see SwUndo::GetComment
If the given nUndoId is equal to zero an undo object with ID
UNDO_START will be generated.
If pRewriter is not equal to zero the given rewriter will be
set for the generated closure object and the corresponding
start object. Otherwise an existent rewriter in theIDocumentRedlineAccess
corresponding start object will be propagated to the generated
closure object.
*/
virtual SwUndoId EndUndo( SwUndoId eUndoId, const SwRewriter * pRewriter) = 0;
/** <- #111827#
loescht die gesamten UndoObjecte ( fuer Methoden die am Nodes
Array drehen ohne entsprechendes Undo !!)
*/
virtual void DelAllUndoObj() = 0;
/** liefert die Id der letzten undofaehigen Aktion zurueck
oder USHRT_MAX fuellt ggf. VARARR mit ::com::sun::star::sdbcx::User-UndoIds
*/
virtual SwUndoId GetUndoIds(String* pStr, SwUndoIds *pUndoIds) const = 0;
/**
*/
virtual String GetUndoIdsStr(String* pStr, SwUndoIds *pUndoIds) const = 0;
/** gibt es Klammerung mit der Id?
*/
virtual bool HasUndoId(SwUndoId eId) const = 0;
/* @@@MAINTAINABILITY-HORROR@@@
Implementation details made public.
die drei folgenden Methoden werden beim Undo und nur dort
benoetigt. Sollten sonst nicht aufgerufen werden.
*/
virtual const SwNodes* GetUndoNds() const = 0;
virtual SwUndo* RemoveLastUndo(SwUndoId eUndoId) = 0;
/** 2002-05-31 dvo, #95884#: To prevent an undo array overflow when
doing nested undos, undo may have to be disabled. Undo-intensive
actions (like auto-format) should check this manually.
*/
virtual bool HasTooManyUndos() const = 0;
/**
*/
virtual bool Redo( SwUndoIter& ) = 0;
/** liefert die Id der letzten Redofaehigen Aktion zurueck
fuellt ggf. VARARR mit RedoIds
*/
virtual SwUndoId GetRedoIds( String* pStr, SwUndoIds *pRedoIds) const = 0;
/**
*/
virtual String GetRedoIdsStr( String* pStr, SwUndoIds *pRedoIds) const = 0;
/**
*/
virtual bool Repeat( SwUndoIter&, sal_uInt16 nRepeatCnt) = 0;
/** liefert die Id der letzten Repeatfaehigen Aktion zurueck
fuellt ggf. VARARR mit RedoIds
*/
virtual SwUndoId GetRepeatIds( String* pStr, SwUndoIds *pRedoIds) const = 0;
/**
*/
virtual String GetRepeatIdsStr( String* pStr, SwUndoIds *pRedoIds) const = 0;
/** interne Verkuerzung fuer Insert am Ende
*/
virtual void AppendUndo(SwUndo*) = 0;
/** loescht alle UndoObjecte von nUndoPos
bis zum Ende des Undo-Arrays
*/
virtual void ClearRedo() = 0;
/** Manipulates the position of the undo stack which reset the modified flag
*/
virtual void setUndoNoModifiedPosition( SwUndoNoModifiedPosition ) = 0;
/** Gets the position of the undo stack which reset the modified flag
*/
virtual SwUndoNoModifiedPosition getUndoNoModifiedPosition() const = 0;
protected:
virtual ~IDocumentUndoRedo() {};
};
#endif
<|endoftext|>
|
<commit_before>#include <iostream>
#include <fstream>
#include <vector>
#include <cassert>
#include "structures.h"
#define abs(x) ((x)<0 ? -(x) : (x))
int op(int x) {
int ret ;
ret = x&1 ;
x >>= 1 ;
for(int i = 0 ; i < 31 ; i++) {
ret ^= x&1 ;
x >>= 1 ;
}
return ret ;
}
void check(void) {
assert(op(0b1110101101)) ;
assert(op(0b11100101100100)) ;
assert(!op(0b11101101101)) ;
assert(!op(0b111001011010100)) ;
}
int main(int argc, char *argv[]) {
if(argc != 2) {
std::cerr << "Syntax:" << argv[0] << " <size of the S box>" << std::endl ;
return 1 ;
}
std::vector<int> substitution = {7, 3, 6, 1, 13, 9, 10, 11, 2, 12, 0, 4, 5, 15, 8, 14} ;
std::vector<std::pair<int,int>> goodKeys ;
int S = atoi(argv[1]) ;
int nbElt = 1<<S ;
std::cout << "\\[\n\\bordermatrix{\n& " ;
for(int b = 0 ; b < nbElt-1 ; b++) {
std::cout << b << " & " ;
}
std::cout << nbElt-1 << "\\cr\n" ;
for(int a = 0 ; a < nbElt ; a++) {
std::cout << a << " & " ;
for(int b = 0 ; b < nbElt ; b++) {
int nbKey = 0 ;
for(int c = 0 ; c < nbElt ; c++) {
Block blockA(a) ;
Block blockB(b) ;
Block key(c) ;
blockA.product(key) ;
key.substitution() ;
blockB.product(key) ;
if(blockA.bitsXor() == blockB.bitsXor()) {
nbKey ++ ;
}
}
std::cout << nbKey ;
double proba = ((double)nbKey)/16 ;
if(abs(proba - 0.5) > 0.3) {
// std::cout << nbKey ;
goodKeys.push_back(std::pair<int,int>(a, b)) ;
}
if(b < nbElt-1)
std::cout << " & " ;
}
std::cout << "\\cr\n" ;
}
std::cout << "}\n\\]\n";
std::cout << "Couples (a, b) with the highest probability:\n\\[" ;
if(goodKeys.size() > 0)
std::cout << "(" << goodKeys[0].first << ", " << goodKeys[0].second << ")" ;
for(unsigned i = 1 ; i < goodKeys.size() ; i++) {
std::cout << ", (" << goodKeys[i].first << ", " << goodKeys[i].second << ")" ;
}
std::cout << "\\]\n" ;
return 0 ;
}
<commit_msg>Remove useless stuff.<commit_after>#include <iostream>
#include <fstream>
#include <vector>
#include <cassert>
#include "structures.h"
int main(int argc, char *argv[]) {
if(argc != 2) {
std::cerr << "Syntax:" << argv[0] << " <size of the S box>" << std::endl ;
return 1 ;
}
std::vector<std::pair<int,int>> goodKeys ;
int S = atoi(argv[1]) ;
int nbElt = 1<<S ;
std::cout << "\\[\n\\bordermatrix{\n& " ;
for(int b = 0 ; b < nbElt-1 ; b++) {
std::cout << b << " & " ;
}
std::cout << nbElt-1 << "\\cr\n" ;
for(int a = 0 ; a < nbElt ; a++) {
std::cout << a << " & " ;
for(int b = 0 ; b < nbElt ; b++) {
int nbKey = 0 ;
for(int c = 0 ; c < nbElt ; c++) {
Block blockA(a) ;
Block blockB(b) ;
Block key(c) ;
blockA.product(key) ;
key.substitution() ;
blockB.product(key) ;
if(blockA.bitsXor() == blockB.bitsXor()) {
nbKey ++ ;
}
}
std::cout << nbKey ;
double proba = ((double)nbKey)/16 ;
if(abs(proba - 0.5) > 0.3) {
// std::cout << nbKey ;
goodKeys.push_back(std::pair<int,int>(a, b)) ;
}
if(b < nbElt-1)
std::cout << " & " ;
}
std::cout << "\\cr\n" ;
}
std::cout << "}\n\\]\n";
std::cout << "Couples (a, b) with the highest probability:\n\\[" ;
if(goodKeys.size() > 0)
std::cout << "(" << goodKeys[0].first << ", " << goodKeys[0].second << ")" ;
for(unsigned i = 1 ; i < goodKeys.size() ; i++) {
std::cout << ", (" << goodKeys[i].first << ", " << goodKeys[i].second << ")" ;
}
std::cout << "\\]\n" ;
return 0 ;
}
<|endoftext|>
|
<commit_before>#include <vector>
#include <fstream>
#include <string>
#include <sys/stat.h>
#include <Windows.h>
#include <tinydir/tinydir.h>
char appplication_folder[1024];
void set_application_folder( char const* application_path )
{
int length = strrchr( application_path, '\\' ) - application_path + 1;
memcpy( appplication_folder, application_path, length );
appplication_folder[length] = 0;
}
char const* get_application_folder()
{
return appplication_folder;
}
bool run( char* command_line )
{
return system( command_line ) == 0;
}
struct compiler
{
compiler( char const* compiler_path )
: path( compiler_path )
{
int ext_begin = strrchr(compiler_path, '\\') - compiler_path + 1;
int ext_end = strrchr(compiler_path, '.') - compiler_path - ext_begin;
extension = path.substr(ext_begin, ext_end);
}
void compile( char const* asset_path, char const* output_folder )
{
char command_line[1024];
sprintf( command_line, "%s \"%s\" \"%s\"", path.c_str(), asset_path, output_folder );
run( command_line );
}
std::string extension;
std::string path;
};
typedef std::vector< std::string > file_list;
typedef std::vector< compiler* > compiler_list;
void list_files( char const* folder, char const* extension, file_list& files )
{
char search_key[1024];
sprintf( search_key, "%s\\*", folder, extension );
WIN32_FIND_DATA find_data;
HANDLE find_handle = FindFirstFile( search_key, &find_data );
if( find_handle != INVALID_HANDLE_VALUE )
{
do
{
if( strstr( find_data.cFileName, extension ) && strlen( strstr( find_data.cFileName, extension ) ) == strlen( extension ) )
{
char file_path[1024];
sprintf( file_path, "%s\\%s", folder, find_data.cFileName );
files.push_back( file_path );
}
else if( find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
{
if( find_data.cFileName[0] != '.' )
{
char subfolder[2048];
sprintf( subfolder, "%s\\%s", folder, find_data.cFileName );
list_files( subfolder, extension, files );
}
}
}while( FindNextFile( find_handle, &find_data ) );
}
}
void list_folders( char const* path, file_list& folders )
{
char search_key[1024];
sprintf( search_key, "%s\\*", path );
WIN32_FIND_DATA find_data;
HANDLE find_handle = FindFirstFile( search_key, &find_data );
if( find_handle != INVALID_HANDLE_VALUE )
{
do
{
if( find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
{
if( find_data.cFileName[0] != '.' )
{
char subfolder[2048];
sprintf( subfolder, "%s\\%s", path, find_data.cFileName );
folders.push_back( subfolder );
}
}
}while( FindNextFile( find_handle, &find_data ) );
}
}
compiler_list get_compilers( char const* folder )
{
file_list paths;
list_files( folder, "exe", paths );
compiler_list compilers;
for( file_list::iterator iter = paths.begin(); iter != paths.end(); ++iter )
{
char const* path = (*iter).c_str();
compilers.push_back( new compiler( path ) );
}
return compilers;
}
void compile_folder( compiler* c, char const* asset_folder, char const* mod_folder )
{
file_list files;
list_files( asset_folder, c->extension.c_str(), files );
for( file_list::iterator file_iter = files.begin(); file_iter != files.end(); ++file_iter )
{
c->compile( file_iter->c_str(), mod_folder );
}
}
void get_asset_folders( compiler& c, file_list& asset_folders )
{
std::string asset_list_path = c.path + std::string( ".txt" );
std::ifstream in = std::ifstream( asset_list_path.c_str() );
char path[1024];
while( !in.eof() )
{
in.getline( path, sizeof( path ) );
asset_folders.push_back( path );
}
}
int main( int argument_count, char** arguments )
{
char module_name[1024];
GetModuleFileName( 0, module_name, 1024 );
set_application_folder( module_name );
file_list mod_folders;
char mods_folder[1024];
sprintf( mods_folder, "%s..\\..\\mods", get_application_folder() );
list_folders( mods_folder, mod_folders );
sprintf( mods_folder, "%s..\\..\\dont_starve\\mods", get_application_folder() );
list_folders( mods_folder, mod_folders );
char compilers_folder[1024] ;
sprintf( compilers_folder, "%scompilers", get_application_folder() );
compiler_list compilers = get_compilers( compilers_folder );
for( compiler_list::iterator iter = compilers.begin(); iter != compilers.end(); ++iter )
{
compiler* c = *iter;
file_list asset_folders;
get_asset_folders( *c, asset_folders );
for( file_list::iterator mod_folder_iter = mod_folders.begin(); mod_folder_iter != mod_folders.end(); ++mod_folder_iter )
{
for( file_list::iterator asset_folder_iter = asset_folders.begin(); asset_folder_iter != asset_folders.end(); ++asset_folder_iter )
{
char asset_folder[1024];
sprintf( asset_folder, "%s/%s", mod_folder_iter->c_str(), asset_folder_iter->c_str() );
compile_folder( c, asset_folder, mod_folder_iter->c_str() );
}
}
}
return 0;
}<commit_msg>Just use arg[0] to get application folder. Removes another windows.h dependency.<commit_after>#include <vector>
#include <fstream>
#include <string>
#include <sys/stat.h>
#include <Windows.h>
#include <tinydir/tinydir.h>
char appplication_folder[1024];
void set_application_folder( char const* application_path )
{
int length = strrchr( application_path, '\\' ) - application_path + 1;
memcpy( appplication_folder, application_path, length );
appplication_folder[length] = 0;
}
char const* get_application_folder()
{
return appplication_folder;
}
bool run( char* command_line )
{
return system( command_line ) == 0;
}
struct compiler
{
compiler( char const* compiler_path )
: path( compiler_path )
{
int ext_begin = strrchr(compiler_path, '\\') - compiler_path + 1;
int ext_end = strrchr(compiler_path, '.') - compiler_path - ext_begin;
extension = path.substr(ext_begin, ext_end);
}
void compile( char const* asset_path, char const* output_folder )
{
char command_line[1024];
sprintf( command_line, "%s \"%s\" \"%s\"", path.c_str(), asset_path, output_folder );
run( command_line );
}
std::string extension;
std::string path;
};
typedef std::vector< std::string > file_list;
typedef std::vector< compiler* > compiler_list;
void list_files( char const* folder, char const* extension, file_list& files )
{
char search_key[1024];
sprintf( search_key, "%s\\*", folder, extension );
WIN32_FIND_DATA find_data;
HANDLE find_handle = FindFirstFile( search_key, &find_data );
if( find_handle != INVALID_HANDLE_VALUE )
{
do
{
if( strstr( find_data.cFileName, extension ) && strlen( strstr( find_data.cFileName, extension ) ) == strlen( extension ) )
{
char file_path[1024];
sprintf( file_path, "%s\\%s", folder, find_data.cFileName );
files.push_back( file_path );
}
else if( find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
{
if( find_data.cFileName[0] != '.' )
{
char subfolder[2048];
sprintf( subfolder, "%s\\%s", folder, find_data.cFileName );
list_files( subfolder, extension, files );
}
}
}while( FindNextFile( find_handle, &find_data ) );
}
}
void list_folders( char const* path, file_list& folders )
{
char search_key[1024];
sprintf( search_key, "%s\\*", path );
WIN32_FIND_DATA find_data;
HANDLE find_handle = FindFirstFile( search_key, &find_data );
if( find_handle != INVALID_HANDLE_VALUE )
{
do
{
if( find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
{
if( find_data.cFileName[0] != '.' )
{
char subfolder[2048];
sprintf( subfolder, "%s\\%s", path, find_data.cFileName );
folders.push_back( subfolder );
}
}
}while( FindNextFile( find_handle, &find_data ) );
}
}
compiler_list get_compilers( char const* folder )
{
file_list paths;
list_files( folder, "exe", paths );
compiler_list compilers;
for( file_list::iterator iter = paths.begin(); iter != paths.end(); ++iter )
{
char const* path = (*iter).c_str();
compilers.push_back( new compiler( path ) );
}
return compilers;
}
void compile_folder( compiler* c, char const* asset_folder, char const* mod_folder )
{
file_list files;
list_files( asset_folder, c->extension.c_str(), files );
for( file_list::iterator file_iter = files.begin(); file_iter != files.end(); ++file_iter )
{
c->compile( file_iter->c_str(), mod_folder );
}
}
void get_asset_folders( compiler& c, file_list& asset_folders )
{
std::string asset_list_path = c.path + std::string( ".txt" );
std::ifstream in = std::ifstream( asset_list_path.c_str() );
char path[1024];
while( !in.eof() )
{
in.getline( path, sizeof( path ) );
asset_folders.push_back( path );
}
}
int main( int argument_count, char** arguments )
{
set_application_folder( arguments[0] );
file_list mod_folders;
char mods_folder[1024];
sprintf( mods_folder, "%s..\\..\\mods", get_application_folder() );
list_folders( mods_folder, mod_folders );
sprintf( mods_folder, "%s..\\..\\dont_starve\\mods", get_application_folder() );
list_folders( mods_folder, mod_folders );
char compilers_folder[1024] ;
sprintf( compilers_folder, "%scompilers", get_application_folder() );
compiler_list compilers = get_compilers( compilers_folder );
for( compiler_list::iterator iter = compilers.begin(); iter != compilers.end(); ++iter )
{
compiler* c = *iter;
file_list asset_folders;
get_asset_folders( *c, asset_folders );
for( file_list::iterator mod_folder_iter = mod_folders.begin(); mod_folder_iter != mod_folders.end(); ++mod_folder_iter )
{
for( file_list::iterator asset_folder_iter = asset_folders.begin(); asset_folder_iter != asset_folders.end(); ++asset_folder_iter )
{
char asset_folder[1024];
sprintf( asset_folder, "%s/%s", mod_folder_iter->c_str(), asset_folder_iter->c_str() );
compile_folder( c, asset_folder, mod_folder_iter->c_str() );
}
}
}
return 0;
}<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2006 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: Gabe Black
*/
#include "arch/sparc/isa_traits.hh"
#include "arch/sparc/registers.hh"
#include "arch/sparc/nativetrace.hh"
#include "cpu/thread_context.hh"
#include "params/SparcNativeTrace.hh"
namespace Trace {
static char *intRegNames[SparcISA::NumIntArchRegs] = {
//Global registers
"g0", "g1", "g2", "g3", "g4", "g5", "g6", "g7",
//Output registers
"o0", "o1", "o2", "o3", "o4", "o5", "o6", "o7",
//Local registers
"l0", "l1", "l2", "l3", "l4", "l5", "l6", "l7",
//Input registers
"i0", "i1", "i2", "i3", "i4", "i5", "i6", "i7",
};
void
Trace::SparcNativeTrace::check(NativeTraceRecord *record)
{
ThreadContext *tc = record->getThread();
uint64_t regVal, realRegVal;
// Integer registers
// I doubt a real SPARC will describe more integer registers than this.
assert(SparcISA::NumIntArchRegs == 32);
char **regName = intRegNames;
for (int i = 0; i < SparcISA::NumIntArchRegs; i++) {
regVal = tc->readIntReg(i);
read(&realRegVal, sizeof(realRegVal));
realRegVal = SparcISA::gtoh(realRegVal);
checkReg(*(regName++), regVal, realRegVal);
}
// PC
read(&realRegVal, sizeof(realRegVal));
realRegVal = SparcISA::gtoh(realRegVal);
regVal = tc->readNextPC();
checkReg("pc", regVal, realRegVal);
// NPC
read(&realRegVal, sizeof(realRegVal));
realRegVal = SparcISA::gtoh(realRegVal);
regVal = tc->readNextNPC();
checkReg("npc", regVal, realRegVal);
// CCR
read(&realRegVal, sizeof(realRegVal));
realRegVal = SparcISA::gtoh(realRegVal);
regVal = tc->readIntReg(SparcISA::NumIntArchRegs + 2);
checkReg("ccr", regVal, realRegVal);
}
} /* namespace Trace */
////////////////////////////////////////////////////////////////////////
//
// ExeTracer Simulation Object
//
Trace::SparcNativeTrace *
SparcNativeTraceParams::create()
{
return new Trace::SparcNativeTrace(this);
};
<commit_msg>SPARC: Fix a minor compile bug in native trace on gcc > 4.1.<commit_after>/*
* Copyright (c) 2006 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: Gabe Black
*/
#include "arch/sparc/isa_traits.hh"
#include "arch/sparc/registers.hh"
#include "arch/sparc/nativetrace.hh"
#include "cpu/thread_context.hh"
#include "params/SparcNativeTrace.hh"
namespace Trace {
static const char *intRegNames[SparcISA::NumIntArchRegs] = {
//Global registers
"g0", "g1", "g2", "g3", "g4", "g5", "g6", "g7",
//Output registers
"o0", "o1", "o2", "o3", "o4", "o5", "o6", "o7",
//Local registers
"l0", "l1", "l2", "l3", "l4", "l5", "l6", "l7",
//Input registers
"i0", "i1", "i2", "i3", "i4", "i5", "i6", "i7",
};
void
Trace::SparcNativeTrace::check(NativeTraceRecord *record)
{
ThreadContext *tc = record->getThread();
uint64_t regVal, realRegVal;
// Integer registers
// I doubt a real SPARC will describe more integer registers than this.
assert(SparcISA::NumIntArchRegs == 32);
const char **regName = intRegNames;
for (int i = 0; i < SparcISA::NumIntArchRegs; i++) {
regVal = tc->readIntReg(i);
read(&realRegVal, sizeof(realRegVal));
realRegVal = SparcISA::gtoh(realRegVal);
checkReg(*(regName++), regVal, realRegVal);
}
// PC
read(&realRegVal, sizeof(realRegVal));
realRegVal = SparcISA::gtoh(realRegVal);
regVal = tc->readNextPC();
checkReg("pc", regVal, realRegVal);
// NPC
read(&realRegVal, sizeof(realRegVal));
realRegVal = SparcISA::gtoh(realRegVal);
regVal = tc->readNextNPC();
checkReg("npc", regVal, realRegVal);
// CCR
read(&realRegVal, sizeof(realRegVal));
realRegVal = SparcISA::gtoh(realRegVal);
regVal = tc->readIntReg(SparcISA::NumIntArchRegs + 2);
checkReg("ccr", regVal, realRegVal);
}
} /* namespace Trace */
////////////////////////////////////////////////////////////////////////
//
// ExeTracer Simulation Object
//
Trace::SparcNativeTrace *
SparcNativeTraceParams::create()
{
return new Trace::SparcNativeTrace(this);
};
<|endoftext|>
|
<commit_before>/* Copyright (c) 2009-2015 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdio.h>
#include <string.h>
#include <getopt.h>
#include <assert.h>
#include <iostream>
#include <fstream>
#include "ClusterMetrics.h"
#include "Context.h"
#include "Cycles.h"
#include "Dispatch.h"
#include "ShortMacros.h"
#include "Crc32C.h"
#include "ObjectFinder.h"
#include "OptionParser.h"
#include "RamCloud.h"
#include "Tub.h"
#include "IndexLookup.h"
#include "TableEnumerator.h"
using namespace RAMCloud;
/**
* A utility for splitting table images generated by the TableDownloader
* into chunks of equal size (measured in RAMCloud objects). Once split, those
* parts can be uploaded in parallel by the TableUploader.
*/
int
main(int argc, char *argv[])
try
{
string imageFilePath;
long objectsPerFile;
string outputDir;
string splitSuffixFormat;
// Set line buffering for stdout so that printf's and log messages
// interleave properly.
setvbuf(stdout, NULL, _IOLBF, 1024);
// Need external context to set log levels with OptionParser
Context context(false);
OptionsDescription clientOptions("TableImageSplitter");
clientOptions.add_options()
("imageFile",
ProgramOptions::value<string>(&imageFilePath),
"Path to the image file to split.")
("objectsPerFile",
ProgramOptions::value<long>(&objectsPerFile),
"How many objects to pack into a partition.")
("outputDir",
ProgramOptions::value<string>(&outputDir),
"Directory to write split files.")
("splitSuffixFormat",
ProgramOptions::value<string>(&splitSuffixFormat)->
default_value(".part%04d"),
"Format string of the suffix to use for partitions. Must contain "
"exactly one %d. [default: \".part%04d\"].");
OptionParser optionParser(clientOptions, argc, argv);
printf("TableImageSplitter: {imageFile: %s, objectsPerFile: %u, "
"outputDir: %s, splitSuffixFormat: %s}\n", imageFilePath.c_str(),
objectsPerFile, outputDir.c_str(), splitSuffixFormat.c_str());
// Open image file for splitting.
std::ifstream inFile;
inFile.open(imageFilePath.c_str(), std::ios::binary);
size_t lastSlashIndex = imageFilePath.find_last_of("/");
string imageFileName;
if (lastSlashIndex != string::npos)
imageFileName = imageFilePath.substr(lastSlashIndex + 1);
else
imageFileName = imageFilePath;
long partitionCount = 0; // How many partitions we've created so far.
long objCount = 0; // How many objects are in the current partition.
long totalObjCount = 0; // How many objects have we copied in total.
long byteCount = 0; // How many total bytes have we copied so far.
// Open initial output file for first partition.
char *outFileName;
asprintf(&outFileName,
(outputDir + "/" + imageFileName + splitSuffixFormat).c_str(),
partitionCount);
std::ofstream outFile;
outFile.open(outFileName, std::ios::binary);
printf("Creating %s... ", outFileName);
free(outFileName);
// Read the imagefile until there are no more objects left in the file.
char lenBuffer[sizeof(uint32_t)];
while(inFile.read(lenBuffer, sizeof(lenBuffer))) {
uint32_t keyLength = *((uint32_t*) lenBuffer);
char keyBuffer[keyLength];
inFile.read(keyBuffer, keyLength);
inFile.read(lenBuffer, sizeof(lenBuffer));
uint32_t dataLength = *((uint32_t*) lenBuffer);
char dataBuffer[dataLength];
inFile.read(dataBuffer, dataLength);
// Copy object to output file.
outFile.write((char*) &keyLength, sizeof(uint32_t));
outFile.write((char*) keyBuffer, keyLength);
outFile.write((char*) &dataLength, sizeof(uint32_t));
outFile.write((char*) dataBuffer, dataLength);
objCount++;
totalObjCount++;
byteCount += keyLength + dataLength;
// If we've filled up the partition, close it and start a new one.
if (objCount == objectsPerFile) {
outFile.close();
partitionCount++;
printf("Done\n");
asprintf(&outFileName,
(outputDir + "/" + imageFileName + splitSuffixFormat).c_str(),
partitionCount);
outFile.open(outFileName, std::ios::binary);
printf("Creating %s... ", outFileName);
free(outFileName);
objCount = 0;
}
}
outFile.close();
partitionCount++;
printf("Done\n");
inFile.close();
printf("Split table image into %u partitions. Total objects: %u. Total "
"bytes: %u\n", partitionCount, totalObjCount, byteCount);
return 0;
} catch (Exception& e) {
fprintf(stderr, "Exception: %s\n", e.str().c_str());
return 1;
}
<commit_msg>Added bytePerFile opt to TableImageSplitter.<commit_after>/* Copyright (c) 2009-2015 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdio.h>
#include <string.h>
#include <getopt.h>
#include <assert.h>
#include <iostream>
#include <fstream>
#include "ClusterMetrics.h"
#include "Context.h"
#include "Cycles.h"
#include "Dispatch.h"
#include "ShortMacros.h"
#include "Crc32C.h"
#include "ObjectFinder.h"
#include "OptionParser.h"
#include "RamCloud.h"
#include "Tub.h"
#include "IndexLookup.h"
#include "TableEnumerator.h"
using namespace RAMCloud;
/**
* A utility for splitting table images generated by the TableDownloader
* into chunks of equal size (measured in RAMCloud objects). Once split, those
* parts can be uploaded in parallel by the TableUploader.
*/
int
main(int argc, char *argv[])
try
{
string imageFilePath;
long objectsPerFile;
long bytesPerFile;
string outputDir;
string splitSuffixFormat;
// Set line buffering for stdout so that printf's and log messages
// interleave properly.
setvbuf(stdout, NULL, _IOLBF, 1024);
// Need external context to set log levels with OptionParser
Context context(false);
OptionsDescription clientOptions("TableImageSplitter");
clientOptions.add_options()
("imageFile",
ProgramOptions::value<string>(&imageFilePath),
"Path to the image file to split.")
("objectsPerFile",
ProgramOptions::value<long>(&objectsPerFile)->default_value(0),
"How many objects to pack into a partition.")
("bytesPerFile",
ProgramOptions::value<long>(&bytesPerFile)->default_value(0),
"How many bytes to pack into a partition.")
("outputDir",
ProgramOptions::value<string>(&outputDir),
"Directory to write split files.")
("splitSuffixFormat",
ProgramOptions::value<string>(&splitSuffixFormat)->
default_value(".part%04d"),
"Format string of the suffix to use for partitions. Must contain "
"exactly one %d. [default: \".part%04d\"].");
OptionParser optionParser(clientOptions, argc, argv);
printf("TableImageSplitter: {imageFile: %s, objectsPerFile: %lu, "
"bytesPerFile: %lu, outputDir: %s, splitSuffixFormat: %s}\n",
imageFilePath.c_str(), objectsPerFile, bytesPerFile, outputDir.c_str(),
splitSuffixFormat.c_str());
// Open image file for splitting.
std::ifstream inFile;
inFile.open(imageFilePath.c_str(), std::ios::binary);
size_t lastSlashIndex = imageFilePath.find_last_of("/");
string imageFileName;
if (lastSlashIndex != string::npos)
imageFileName = imageFilePath.substr(lastSlashIndex + 1);
else
imageFileName = imageFilePath;
long partitionCount = 0; // How many partitions we've created so far.
long objCount = 0; // How many objects are in the current partition.
long totalObjCount = 0; // How many objects have we copied in total.
long byteCount = 0; // How many bytes are in the current partition.
long totalObjByteCount = 0; // How many total bytes have we copied so far.
// Open initial output file for first partition.
char *outFileName;
asprintf(&outFileName,
(outputDir + "/" + imageFileName + splitSuffixFormat).c_str(),
partitionCount);
std::ofstream outFile;
outFile.open(outFileName, std::ios::binary);
printf("Creating %s... ", outFileName);
free(outFileName);
// Read the imagefile until there are no more objects left in the file.
char lenBuffer[sizeof(uint32_t)];
while(inFile.read(lenBuffer, sizeof(lenBuffer))) {
uint32_t keyLength = *((uint32_t*) lenBuffer);
char keyBuffer[keyLength];
inFile.read(keyBuffer, keyLength);
inFile.read(lenBuffer, sizeof(lenBuffer));
uint32_t dataLength = *((uint32_t*) lenBuffer);
char dataBuffer[dataLength];
inFile.read(dataBuffer, dataLength);
// Copy object to output file.
outFile.write((char*) &keyLength, sizeof(uint32_t));
outFile.write((char*) keyBuffer, keyLength);
outFile.write((char*) &dataLength, sizeof(uint32_t));
outFile.write((char*) dataBuffer, dataLength);
objCount++;
totalObjCount++;
byteCount += sizeof(uint32_t) + keyLength + sizeof(uint32_t) + dataLength;
totalObjByteCount += keyLength + dataLength;
// If we've filled up the partition, close it and start a new one.
if (objectsPerFile > 0) {
if (objCount == objectsPerFile) {
outFile.close();
partitionCount++;
printf("Done\n");
asprintf(&outFileName,
(outputDir + "/" + imageFileName + splitSuffixFormat).c_str(),
partitionCount);
outFile.open(outFileName, std::ios::binary);
printf("Creating %s... ", outFileName);
free(outFileName);
objCount = 0;
byteCount = 0;
}
} else {
if (byteCount > bytesPerFile) {
outFile.close();
partitionCount++;
printf("Done\n");
asprintf(&outFileName,
(outputDir + "/" + imageFileName + splitSuffixFormat).c_str(),
partitionCount);
outFile.open(outFileName, std::ios::binary);
printf("Creating %s... ", outFileName);
free(outFileName);
objCount = 0;
byteCount = 0;
}
}
}
outFile.close();
partitionCount++;
printf("Done\n");
inFile.close();
printf("Split table image into %lu partitions. Total objects: %lu. Total "
"bytes: %lu\n", partitionCount, totalObjCount, totalObjByteCount);
return 0;
} catch (Exception& e) {
fprintf(stderr, "Exception: %s\n", e.str().c_str());
return 1;
}
<|endoftext|>
|
<commit_before>#include "SharedMessagePool.hpp"
#include "Statistics.hpp"
#include "ConditionVariable.hpp"
#include <stack>
DEFINE_int64(shared_pool_size, 1L << 20, "Size (in bytes) of global SharedMessagePool (on each Core)");
DEFINE_int64(shared_pool_max, -1, "Maximum number of shared pools allowed to be allocated (per core).");
GRAPPA_DEFINE_STAT(SimpleStatistic<uint64_t>, shared_message_pools_allocated, 0);
namespace Grappa {
SharedMessagePool * shared_pool = nullptr;
std::stack<SharedMessagePool*> unused_pools;
ConditionVariable blocked_senders;
void init_shared_pool() {
void * p = impl::locale_shared_memory.allocate_aligned(sizeof(SharedMessagePool), 8);
shared_pool = new (p) SharedMessagePool(FLAGS_shared_pool_size);
shared_message_pools_allocated++;
VLOG(3) << "initialized shared_pool @ " << shared_pool << ", buf:" << (void*)shared_pool->buffer;
}
void* SharedMessagePool::allocate(size_t size) {
VLOG(5) << "allocating on shared pool " << this;
CHECK_EQ(this, shared_pool) << "not allocating from global shared_pool!";
if (this->remaining() < size) {
CHECK(size <= this->buffer_size) << "Pool (" << this->buffer_size << ") is not large enough to allocate " << size << " bytes.";
VLOG(3) << "MessagePool full (" << this << ", to_send:"<< this->to_send << "), finding a new one; completions_received:" << completions_received << ", allocated_count:" << allocated_count;
// first try and find one from the unused_pools pool
if (unused_pools.size() > 0) { pop_pool:
shared_pool = unused_pools.top();
VLOG(4) << "found pool @ " << shared_pool << " allocated:" << shared_pool->allocated << "/" << shared_pool->buffer_size << ", count=" << allocated_count << " @ " << this;
unused_pools.pop();
} else if (!global_scheduler.in_no_switch_region() && FLAGS_shared_pool_max > 0 &&
shared_message_pools_allocated >= FLAGS_shared_pool_max-1) {
Grappa::wait(&blocked_senders);
if (this == shared_pool) {
CHECK_GT(unused_pools.size(), 0);
goto pop_pool;
} // else should be able to just fall through and go on our merry way
// CHECK(unused_pools.size() > 0 || shared_pool->remaining() > size);
} else {
// allocate a new one, have the old one delete itself when all previous have been sent
void * p = impl::locale_shared_memory.allocate_aligned(sizeof(SharedMessagePool), 8);
shared_pool = new (p) SharedMessagePool(this->buffer_size);
shared_message_pools_allocated++;
VLOG(4) << "created new shared_pool @ " << shared_pool << ", buf:" << shared_pool->buffer;
}
this->start_emptying(); // start working on freeing up the previous one
return shared_pool->allocate(size); // actually satisfy the allocation request
} else {
allocated_count++;
this->to_send++;
return PoolAllocator<impl::MessageBase>::allocate(size);
// return impl::MessagePoolBase::allocate(size);
}
}
void SharedMessagePool::start_emptying() {
emptying = true;
// CHECK_GT(to_send, 0);
if (to_send == 0 && emptying) { on_empty(); }
}
void SharedMessagePool::message_sent(impl::MessageBase* m) {
CHECK( reinterpret_cast<char*>(m) >= this->buffer && reinterpret_cast<char*>(m)+m->size() <= this->buffer+this->buffer_size )
<< "message is outside this pool!! message(" << m << ", extra:" << m->pool << "), "
<< "pool(" << this << ", buf:" << (void*)this->buffer << ", size:" << this->buffer_size << ")";
to_send--;
completions_received++;
if (to_send == 0 && emptying) {
VLOG(3) << "empty! so put back on unused stack message(" << m << ", is_sent_:" << m->is_sent_ << ")";
on_empty();
}
}
void SharedMessagePool::on_empty() {
VLOG(3) << "empty and emptying, to_send:"<< to_send << ", allocated:" << allocated << "/" << buffer_size << " @ " << this << ", buf:" << (void*)buffer << " completions_received:" << completions_received << ", allocated_count:" << allocated_count;
// verify everything sent
this->iterate([](impl::MessageBase* m) {
if (!m->is_sent_ || !m->is_delivered_ || !m->is_enqueued_) {
VLOG(1) << "!! message(" << m << ", is_sent_:" << m->is_sent_ << ", is_delivered_:" << m->is_delivered_ << ", m->is_enqueued_:" << m->is_enqueued_ << ", extra:" << m->pool << ")";
}
});
this->reset();
memset(buffer, (0x11*locale_mycore()) | 0xf0, buffer_size); // poison
unused_pools.push(this);
broadcast(&blocked_senders);
}
} // namespace Grappa
<commit_msg>Add note about how shared_pool_max works.<commit_after>#include "SharedMessagePool.hpp"
#include "Statistics.hpp"
#include "ConditionVariable.hpp"
#include <stack>
DEFINE_int64(shared_pool_size, 1L << 20, "Size (in bytes) of global SharedMessagePool (on each Core)");
/// Note: max is enforced only for blockable callers, and is enforced early to avoid callers
/// that cannot block (callers from message handlers) to have a greater chance of proceeding.
DEFINE_int64(shared_pool_max, -1, "Maximum number of shared pools allowed to be allocated (per core).");
GRAPPA_DEFINE_STAT(SimpleStatistic<uint64_t>, shared_message_pools_allocated, 0);
namespace Grappa {
SharedMessagePool * shared_pool = nullptr;
std::stack<SharedMessagePool*> unused_pools;
ConditionVariable blocked_senders;
void init_shared_pool() {
void * p = impl::locale_shared_memory.allocate_aligned(sizeof(SharedMessagePool), 8);
shared_pool = new (p) SharedMessagePool(FLAGS_shared_pool_size);
shared_message_pools_allocated++;
VLOG(3) << "initialized shared_pool @ " << shared_pool << ", buf:" << (void*)shared_pool->buffer;
}
void* SharedMessagePool::allocate(size_t size) {
VLOG(5) << "allocating on shared pool " << this;
CHECK_EQ(this, shared_pool) << "not allocating from global shared_pool!";
if (this->remaining() < size) {
CHECK(size <= this->buffer_size) << "Pool (" << this->buffer_size << ") is not large enough to allocate " << size << " bytes.";
VLOG(3) << "MessagePool full (" << this << ", to_send:"<< this->to_send << "), finding a new one; completions_received:" << completions_received << ", allocated_count:" << allocated_count;
// first try and find one from the unused_pools pool
if (unused_pools.size() > 0) { pop_pool:
shared_pool = unused_pools.top();
VLOG(4) << "found pool @ " << shared_pool << " allocated:" << shared_pool->allocated << "/" << shared_pool->buffer_size << ", count=" << allocated_count << " @ " << this;
unused_pools.pop();
} else if (!global_scheduler.in_no_switch_region() && FLAGS_shared_pool_max > 0 &&
shared_message_pools_allocated >= FLAGS_shared_pool_max-1) {
Grappa::wait(&blocked_senders);
if (this == shared_pool) {
CHECK_GT(unused_pools.size(), 0);
goto pop_pool;
} // else should be able to just fall through and go on our merry way
// CHECK(unused_pools.size() > 0 || shared_pool->remaining() > size);
} else {
// allocate a new one, have the old one delete itself when all previous have been sent
void * p = impl::locale_shared_memory.allocate_aligned(sizeof(SharedMessagePool), 8);
shared_pool = new (p) SharedMessagePool(this->buffer_size);
shared_message_pools_allocated++;
VLOG(4) << "created new shared_pool @ " << shared_pool << ", buf:" << shared_pool->buffer;
}
this->start_emptying(); // start working on freeing up the previous one
return shared_pool->allocate(size); // actually satisfy the allocation request
} else {
allocated_count++;
this->to_send++;
return PoolAllocator<impl::MessageBase>::allocate(size);
// return impl::MessagePoolBase::allocate(size);
}
}
void SharedMessagePool::start_emptying() {
emptying = true;
// CHECK_GT(to_send, 0);
if (to_send == 0 && emptying) { on_empty(); }
}
void SharedMessagePool::message_sent(impl::MessageBase* m) {
CHECK( reinterpret_cast<char*>(m) >= this->buffer && reinterpret_cast<char*>(m)+m->size() <= this->buffer+this->buffer_size )
<< "message is outside this pool!! message(" << m << ", extra:" << m->pool << "), "
<< "pool(" << this << ", buf:" << (void*)this->buffer << ", size:" << this->buffer_size << ")";
to_send--;
completions_received++;
if (to_send == 0 && emptying) {
VLOG(3) << "empty! so put back on unused stack message(" << m << ", is_sent_:" << m->is_sent_ << ")";
on_empty();
}
}
void SharedMessagePool::on_empty() {
VLOG(3) << "empty and emptying, to_send:"<< to_send << ", allocated:" << allocated << "/" << buffer_size << " @ " << this << ", buf:" << (void*)buffer << " completions_received:" << completions_received << ", allocated_count:" << allocated_count;
// verify everything sent
this->iterate([](impl::MessageBase* m) {
if (!m->is_sent_ || !m->is_delivered_ || !m->is_enqueued_) {
VLOG(1) << "!! message(" << m << ", is_sent_:" << m->is_sent_ << ", is_delivered_:" << m->is_delivered_ << ", m->is_enqueued_:" << m->is_enqueued_ << ", extra:" << m->pool << ")";
}
});
this->reset();
memset(buffer, (0x11*locale_mycore()) | 0xf0, buffer_size); // poison
unused_pools.push(this);
broadcast(&blocked_senders);
}
} // namespace Grappa
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-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 <math.h>
#include "pow.h"
#include "chain.h"
#include "chainparams.h"
#include "primitives/block.h"
#include "uint256.h"
#include "util.h"
unsigned int static KimotoGravityWell(const CBlockIndex* pindexLast, const CBlockHeader *pblock, uint64_t TargetBlocksSpacingSeconds, uint64_t PastBlocksMin, uint64_t PastBlocksMax) {
/* current difficulty formula, megacoin - kimoto gravity well */
const CBlockIndex *BlockLastSolved = pindexLast;
const CBlockIndex *BlockReading = pindexLast;
const CBlockHeader *BlockCreating = pblock;
BlockCreating = BlockCreating;
uint64_t PastBlocksMass = 0;
int64_t PastRateActualSeconds = 0;
int64_t PastRateTargetSeconds = 0;
int64_t LatestBlockTime = BlockLastSolved->GetBlockTime();
double PastRateAdjustmentRatio = double(1);
uint256 PastDifficultyAverage;
uint256 PastDifficultyAveragePrev;
double EventHorizonDeviation;
double EventHorizonDeviationFast;
double EventHorizonDeviationSlow;
const uint256 &bnProofOfWorkLimit = Params().ProofOfWorkLimit();
if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || (uint64_t)BlockLastSolved->nHeight < PastBlocksMin) { return bnProofOfWorkLimit.GetCompact(); }
for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {
if (PastBlocksMax > 0 && i > PastBlocksMax) { break; }
PastBlocksMass++;
if (i == 1) { PastDifficultyAverage.SetCompact(BlockReading->nBits); }
else { PastDifficultyAverage = ((uint256().SetCompact(BlockReading->nBits) - PastDifficultyAveragePrev) / i) + PastDifficultyAveragePrev; }
PastDifficultyAveragePrev = PastDifficultyAverage;
if (LatestBlockTime < BlockReading->GetBlockTime()) { LatestBlockTime = BlockReading->GetBlockTime(); }
PastRateActualSeconds = LatestBlockTime - BlockReading->GetBlockTime();
PastRateTargetSeconds = TargetBlocksSpacingSeconds * PastBlocksMass;
PastRateAdjustmentRatio = double(1);
if (PastRateActualSeconds < 1) { PastRateActualSeconds = 1; }
if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {
PastRateAdjustmentRatio = double(PastRateTargetSeconds) / double(PastRateActualSeconds);
}
EventHorizonDeviation = 1 + (0.7084 * pow((double(PastBlocksMass)/double(9)), -1.228));
EventHorizonDeviationFast = EventHorizonDeviation;
EventHorizonDeviationSlow = 1 / EventHorizonDeviation;
if (PastBlocksMass >= PastBlocksMin) {
if ((PastRateAdjustmentRatio <= EventHorizonDeviationSlow) || (PastRateAdjustmentRatio >= EventHorizonDeviationFast)) { assert(BlockReading); break; }
}
if (BlockReading->pprev == NULL) { assert(BlockReading); break; }
BlockReading = BlockReading->pprev;
}
uint256 bnNew(PastDifficultyAverage);
if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {
bnNew *= PastRateActualSeconds;
bnNew /= PastRateTargetSeconds;
}
if (bnNew > bnProofOfWorkLimit) { bnNew = bnProofOfWorkLimit; }
/// debug print
LogPrintf("Difficulty Retarget - BOB's Wormh0le (KGW)\n");
LogPrintf("PastRateAdjustmentRatio = %g\n", PastRateAdjustmentRatio);
LogPrintf("Before: %08x %s\n", BlockLastSolved->nBits, uint256().SetCompact(BlockLastSolved->nBits).ToString().c_str());
LogPrintf("After: %08x %s\n", bnNew.GetCompact(), bnNew.ToString().c_str());
return bnNew.GetCompact();
}
unsigned int static GetNextWorkRequired_V2(const CBlockIndex* pindexLast, const CBlockHeader *pblock)
{
static const int64_t BlocksTargetSpacing = 10 * 60; // 10 minutes
unsigned int TimeDaySeconds = 60 * 60 * 24;
int64_t PastSecondsMin = TimeDaySeconds * 0.0625;
int64_t PastSecondsMax = TimeDaySeconds * 1.75;
uint64_t PastBlocksMin = PastSecondsMin / BlocksTargetSpacing;
uint64_t PastBlocksMax = PastSecondsMax / BlocksTargetSpacing;
return KimotoGravityWell(pindexLast, pblock, BlocksTargetSpacing, PastBlocksMin, PastBlocksMax);
}
unsigned int GetNextWorkRequired_V1(const CBlockIndex* pindexLast, const CBlockHeader *pblock)
{
unsigned int nProofOfWorkLimit = Params().ProofOfWorkLimit().GetCompact();
// Genesis block
if (pindexLast == NULL)
return nProofOfWorkLimit;
// Only change once per interval
if ((pindexLast->nHeight+1) % Params().Interval() != 0)
{
if (Params().AllowMinDifficultyBlocks())
{
// Special difficulty rule for testnet:
// If the new block's timestamp is more than 2* 10 minutes
// then allow mining of a min-difficulty block.
if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + Params().TargetSpacing()*2)
return nProofOfWorkLimit;
else
{
// Return the last non-special-min-difficulty-rules-block
const CBlockIndex* pindex = pindexLast;
while (pindex->pprev && pindex->nHeight % Params().Interval() != 0 && pindex->nBits == nProofOfWorkLimit)
pindex = pindex->pprev;
return pindex->nBits;
}
}
return pindexLast->nBits;
}
// Go back by what we want to be 14 days worth of blocks
const CBlockIndex* pindexFirst = pindexLast;
for (int i = 0; pindexFirst && i < Params().Interval()-1; i++)
pindexFirst = pindexFirst->pprev;
assert(pindexFirst);
// Limit adjustment step
int64_t nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
LogPrintf(" nActualTimespan = %d before bounds\n", nActualTimespan);
if (nActualTimespan < Params().TargetTimespan()/4)
nActualTimespan = Params().TargetTimespan()/4;
if (nActualTimespan > Params().TargetTimespan()*4)
nActualTimespan = Params().TargetTimespan()*4;
// Retarget
uint256 bnNew;
uint256 bnOld;
bnNew.SetCompact(pindexLast->nBits);
bnOld = bnNew;
bnNew *= nActualTimespan;
bnNew /= Params().TargetTimespan();
if (bnNew > Params().ProofOfWorkLimit())
bnNew = Params().ProofOfWorkLimit();
/// debug print
LogPrintf("GetNextWorkRequired RETARGET\n");
LogPrintf("Params().TargetTimespan() = %d nActualTimespan = %d\n", Params().TargetTimespan(), nActualTimespan);
LogPrintf("Before: %08x %s\n", pindexLast->nBits, bnOld.ToString());
LogPrintf("After: %08x %s\n", bnNew.GetCompact(), bnNew.ToString());
return bnNew.GetCompact();
}
unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock)
{
int DiffMode = 1;
if (Params().AllowMinDifficultyBlocks()) {
// if (pindexLast->nHeight+1 >= 50) { DiffMode = 2; }
}
else {
if (pindexLast->nHeight+1 >= 13579) { DiffMode = 2; } // KGW @ Block 13579
}
if (DiffMode == 1) { return GetNextWorkRequired_V1(pindexLast, pblock); }
else if (DiffMode == 2) { return GetNextWorkRequired_V2(pindexLast, pblock); }
return GetNextWorkRequired_V2(pindexLast, pblock);
}
bool CheckProofOfWork(uint256 hash, unsigned int nBits)
{
bool fNegative;
bool fOverflow;
uint256 bnTarget;
if(hash==HASHGENESISBLOCKPOW) //ignore genesis block
{
return true;
}
if (Params().SkipProofOfWorkCheck())
return true;
bnTarget.SetCompact(nBits, &fNegative, &fOverflow);
// Check range
if (fNegative || bnTarget == 0 || fOverflow || bnTarget > Params().ProofOfWorkLimit())
return error("CheckProofOfWork() : nBits below minimum work");
// Check proof of work matches claimed amount
if (hash > bnTarget)
return error("CheckProofOfWork() : hash doesn't match nBits");
return true;
}
uint256 GetBlockProof(const CBlockIndex& block)
{
uint256 bnTarget;
bool fNegative;
bool fOverflow;
bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow);
if (fNegative || fOverflow || bnTarget == 0)
return 0;
// We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256
// as it's too large for a uint256. However, as 2**256 is at least as large
// as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,
// or ~bnTarget / (nTarget+1) + 1.
return (~bnTarget / (bnTarget + 1)) + 1;
}
<commit_msg>I don't know wtf it is, but BOB's wormhole is yielding different results... for some unknown reason<commit_after>// Copyright (c) 2009-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 <math.h>
#include "pow.h"
#include "chain.h"
#include "chainparams.h"
#include "primitives/block.h"
#include "uint256.h"
#include "util.h"
unsigned int static KimotoGravityWell(const CBlockIndex* pindexLast, const CBlockHeader *pblock, uint64_t TargetBlocksSpacingSeconds, uint64_t PastBlocksMin, uint64_t PastBlocksMax) {
/* current difficulty formula, megacoin - kimoto gravity well */
const CBlockIndex *BlockLastSolved = pindexLast;
const CBlockIndex *BlockReading = pindexLast;
const CBlockHeader *BlockCreating = pblock;
BlockCreating = BlockCreating;
uint64_t PastBlocksMass = 0;
int64_t PastRateActualSeconds = 0;
int64_t PastRateTargetSeconds = 0;
int64_t LatestBlockTime = BlockLastSolved->GetBlockTime();
double PastRateAdjustmentRatio = double(1);
uint256 PastDifficultyAverage;
uint256 PastDifficultyAveragePrev;
double EventHorizonDeviation;
double EventHorizonDeviationFast;
double EventHorizonDeviationSlow;
const uint256 bnProofOfWorkLimit = Params().ProofOfWorkLimit();
if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || (uint64_t)BlockLastSolved->nHeight < PastBlocksMin) { return bnProofOfWorkLimit.GetCompact(); }
for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {
if (PastBlocksMax > 0 && i > PastBlocksMax) { break; }
PastBlocksMass++;
if (i == 1) { PastDifficultyAverage.SetCompact(BlockReading->nBits); }
else { PastDifficultyAverage = ((uint256().SetCompact(BlockReading->nBits) - PastDifficultyAveragePrev) / i) + PastDifficultyAveragePrev; }
PastDifficultyAveragePrev = PastDifficultyAverage;
if (LatestBlockTime < BlockReading->GetBlockTime()) { LatestBlockTime = BlockReading->GetBlockTime(); }
PastRateActualSeconds = LatestBlockTime - BlockReading->GetBlockTime();
PastRateTargetSeconds = TargetBlocksSpacingSeconds * PastBlocksMass;
PastRateAdjustmentRatio = double(1);
if (PastRateActualSeconds < 1) { PastRateActualSeconds = 1; }
if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {
PastRateAdjustmentRatio = double(PastRateTargetSeconds) / double(PastRateActualSeconds);
}
EventHorizonDeviation = 1 + (0.7084 * pow((double(PastBlocksMass)/double(9)), -1.228));
EventHorizonDeviationFast = EventHorizonDeviation;
EventHorizonDeviationSlow = 1 / EventHorizonDeviation;
if (PastBlocksMass >= PastBlocksMin) {
if ((PastRateAdjustmentRatio <= EventHorizonDeviationSlow) || (PastRateAdjustmentRatio >= EventHorizonDeviationFast)) { assert(BlockReading); break; }
}
if (BlockReading->pprev == NULL) { assert(BlockReading); break; }
BlockReading = BlockReading->pprev;
}
uint256 bnNew;
bnNew=PastDifficultyAverage;
if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {
bnNew *= PastRateActualSeconds;
bnNew /= PastRateTargetSeconds;
}
if (bnNew > bnProofOfWorkLimit) { bnNew = bnProofOfWorkLimit; }
/// debug print
LogPrintf("Difficulty Retarget - BOB's Wormh0le (KGW)\n");
LogPrintf("PastRateAdjustmentRatio = %g\n", PastRateAdjustmentRatio);
LogPrintf("Before: %08x %s\n", BlockLastSolved->nBits, uint256().SetCompact(BlockLastSolved->nBits).ToString().c_str());
LogPrintf("After: %08x %s\n", bnNew.GetCompact(), bnNew.ToString().c_str());
return bnNew.GetCompact();
}
unsigned int static GetNextWorkRequired_V2(const CBlockIndex* pindexLast, const CBlockHeader *pblock)
{
static const int64_t BlocksTargetSpacing = 10 * 60; // 10 minutes
unsigned int TimeDaySeconds = 60 * 60 * 24;
int64_t PastSecondsMin = TimeDaySeconds * 0.0625;
int64_t PastSecondsMax = TimeDaySeconds * 1.75;
uint64_t PastBlocksMin = PastSecondsMin / BlocksTargetSpacing;
uint64_t PastBlocksMax = PastSecondsMax / BlocksTargetSpacing;
return KimotoGravityWell(pindexLast, pblock, BlocksTargetSpacing, PastBlocksMin, PastBlocksMax);
}
unsigned int GetNextWorkRequired_V1(const CBlockIndex* pindexLast, const CBlockHeader *pblock)
{
unsigned int nProofOfWorkLimit = Params().ProofOfWorkLimit().GetCompact();
// Genesis block
if (pindexLast == NULL)
return nProofOfWorkLimit;
// Only change once per interval
if ((pindexLast->nHeight+1) % Params().Interval() != 0)
{
if (Params().AllowMinDifficultyBlocks())
{
// Special difficulty rule for testnet:
// If the new block's timestamp is more than 2* 10 minutes
// then allow mining of a min-difficulty block.
if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + Params().TargetSpacing()*2)
return nProofOfWorkLimit;
else
{
// Return the last non-special-min-difficulty-rules-block
const CBlockIndex* pindex = pindexLast;
while (pindex->pprev && pindex->nHeight % Params().Interval() != 0 && pindex->nBits == nProofOfWorkLimit)
pindex = pindex->pprev;
return pindex->nBits;
}
}
return pindexLast->nBits;
}
// Go back by what we want to be 14 days worth of blocks
const CBlockIndex* pindexFirst = pindexLast;
for (int i = 0; pindexFirst && i < Params().Interval()-1; i++)
pindexFirst = pindexFirst->pprev;
assert(pindexFirst);
// Limit adjustment step
int64_t nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
LogPrintf(" nActualTimespan = %d before bounds\n", nActualTimespan);
if (nActualTimespan < Params().TargetTimespan()/4)
nActualTimespan = Params().TargetTimespan()/4;
if (nActualTimespan > Params().TargetTimespan()*4)
nActualTimespan = Params().TargetTimespan()*4;
// Retarget
uint256 bnNew;
uint256 bnOld;
bnNew.SetCompact(pindexLast->nBits);
bnOld = bnNew;
bnNew *= nActualTimespan;
bnNew /= Params().TargetTimespan();
if (bnNew > Params().ProofOfWorkLimit())
bnNew = Params().ProofOfWorkLimit();
/// debug print
LogPrintf("GetNextWorkRequired RETARGET\n");
LogPrintf("Params().TargetTimespan() = %d nActualTimespan = %d\n", Params().TargetTimespan(), nActualTimespan);
LogPrintf("Before: %08x %s\n", pindexLast->nBits, bnOld.ToString());
LogPrintf("After: %08x %s\n", bnNew.GetCompact(), bnNew.ToString());
return bnNew.GetCompact();
}
unsigned int GetNextWorkRequired_V3(const CBlockIndex* pindexLast, const CBlockHeader *pblock)
{
static const int64_t nTargetTimespan_V3 = 10*60 ; // dobbscoin: every 10 minutes
static const int64_t nTargetSpacing_V3 = 10*60; // dobbscoin: 10 minutes
static const int64_t nInterval_V3 = nTargetTimespan_V3 / nTargetSpacing_V3;
unsigned int nProofOfWorkLimit = Params().ProofOfWorkLimit().GetCompact();
int64_t retargetTimespan = nTargetTimespan_V3; //Params().TargetTimespan();
int64_t retargetInterval = nInterval_V3; //Params().Interval();
//retargetInterval = Params().TargetTimespan() / Params().TargetSpacing();
//retargetTimespan = Params().TargetTimespan();
// Genesis block
if (pindexLast == NULL)
return nProofOfWorkLimit;
// Only change once per interval
if ((pindexLast->nHeight+1) % retargetInterval != 0)
{
if (Params().AllowMinDifficultyBlocks())
{
// Special difficulty rule for testnet:
// If the new block's timestamp is more than 2* nTargetSpacing minutes
// then allow mining of a min-difficulty block.
if (pblock->nTime > pindexLast->nTime + nTargetSpacing_V3 * 30) //Params().TargetSpacing()*30)
return nProofOfWorkLimit;
else
{
// Return the last non-special-min-difficulty-rules-block
const CBlockIndex* pindex = pindexLast;
while (pindex->pprev && pindex->nHeight % retargetInterval != 0 && pindex->nBits == nProofOfWorkLimit)
pindex = pindex->pprev;
return pindex->nBits;
}
}
return pindexLast->nBits;
}
// Fractalcoin: This fixes an issue where a 51% attack can change difficulty at will.
// Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz
int blockstogoback = retargetInterval-1;
if ((pindexLast->nHeight+1) != retargetInterval)
blockstogoback = retargetInterval;
// Go back by what we want to be 14 days worth of blocks
const CBlockIndex* pindexFirst = pindexLast;
for (int i = 0; pindexFirst && i < blockstogoback; i++)
pindexFirst = pindexFirst->pprev;
assert(pindexFirst);
// Limit adjustment step
int64_t nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
LogPrintf(" nActualTimespan = %d before bounds\n", nActualTimespan);
//DigiShield implementation - thanks to RealSolid & WDC for this code
// amplitude filter - thanks to daft27 for this code
nActualTimespan = retargetTimespan + (nActualTimespan - retargetTimespan)/8;
if (nActualTimespan < (retargetTimespan - (retargetTimespan/4)) ) nActualTimespan = (retargetTimespan - (retargetTimespan/4));
if (nActualTimespan > (retargetTimespan + (retargetTimespan/2)) ) nActualTimespan = (retargetTimespan + (retargetTimespan/2));
// Retarget
uint256 bnNew;
uint256 bnOld;
bnNew.SetCompact(pindexLast->nBits);
bnOld = bnNew;
//scale up for millisecond granularity
bnNew *= nActualTimespan;
//slingshield effectively works by making the target block time longer temporarily
bnNew /= (retargetTimespan);
if (bnNew > Params().ProofOfWorkLimit())
bnNew = Params().ProofOfWorkLimit();
/// debug print
LogPrintf("GetNextWorkRequired DIGISHIELD RETARGET\n");
LogPrintf("Params().TargetTimespan() = %d nActualTimespan = %d\n", Params().TargetTimespan(), nActualTimespan);
LogPrintf("Before: %08x %s\n", pindexLast->nBits, bnOld.ToString());
LogPrintf("After: %08x %s\n", bnNew.GetCompact(), bnNew.ToString());
return bnNew.GetCompact();
}
unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock)
{
int DiffMode = 1;
if (Params().AllowMinDifficultyBlocks()) {
if (pindexLast->nHeight+1 >= 50) { DiffMode = 2; }
if (pindexLast->nHeight+1 >= 100) { DiffMode = 3; }
}
else
{
if (pindexLast->nHeight+1 >= 13579) { DiffMode = 2; } // KGW @ Block 13579
if(pindexLast->nHeight+1 >= 31597) { DiffMode = 3; } //switch to dobbshield @ block 31597
}
if (DiffMode == 1) { return GetNextWorkRequired_V1(pindexLast, pblock); }
else if (DiffMode == 2) { return GetNextWorkRequired_V2(pindexLast, pblock); }
else if (DiffMode == 3) { return GetNextWorkRequired_V3(pindexLast, pblock); }
return GetNextWorkRequired_V3(pindexLast, pblock); //never reached..
}
bool CheckProofOfWork(uint256 hash, unsigned int nBits)
{
bool fNegative;
bool fOverflow;
uint256 bnTarget;
if(hash==HASHGENESISBLOCKPOW) //ignore genesis block
{
return true;
}
if (Params().SkipProofOfWorkCheck())
return true;
bnTarget.SetCompact(nBits, &fNegative, &fOverflow);
// Check range
if (fNegative || bnTarget == 0 || fOverflow || bnTarget > Params().ProofOfWorkLimit())
return error("CheckProofOfWork() : nBits below minimum work");
// Check proof of work matches claimed amount
if (hash > bnTarget)
return error("CheckProofOfWork() : hash doesn't match nBits");
return true;
}
uint256 GetBlockProof(const CBlockIndex& block)
{
uint256 bnTarget;
bool fNegative;
bool fOverflow;
bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow);
if (fNegative || fOverflow || bnTarget == 0)
return 0;
// We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256
// as it's too large for a uint256. However, as 2**256 is at least as large
// as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,
// or ~bnTarget / (nTarget+1) + 1.
return (~bnTarget / (bnTarget + 1)) + 1;
}
<|endoftext|>
|
<commit_before>#pragma once
#include <string>
#include <functional>
#include <cmath>
#include <random>
#include <iostream>
#include <vector>
#include <utility>
#include "tbb/parallel_sort.h"
#include "tbb/mutex.h"
#include "tbb/pipeline.h"
#include "util.hpp"
#include "point.hpp"
#define VALUE(x) std::cout << #x "=" << x << std::endl
namespace psh
{
template<uint d, class T>
class map
{
static_assert(d > 0, "d must be larger than 0.");
public:
struct data_t
{
point<d> location;
T contents;
};
struct bucket : public std::vector<data_t>
{
uint phi_index;
bucket(uint phi_index) : phi_index(phi_index) { }
friend bool operator<(const bucket& lhs, const bucket& rhs) {
return lhs.size() > rhs.size();
}
};
uint M0;
uint M1;
uint n;
uint m_bar;
uint m;
uint r_bar;
uint r;
std::vector<point<d>> phi;
std::vector<bool> H_b;
std::vector<T> H;
std::default_random_engine generator;
map(const std::vector<data_t>& data)
: n(data.size()), m_bar(std::ceil(std::pow(n, 1.0f / d))), m(std::pow(m_bar, d)),
r_bar(std::ceil(std::pow(n / d, 1.0f / d)) - 1), generator(time(0))
{
M0 = prime();
while ((M1 = prime()) == M0);
VALUE(m);
VALUE(m_bar);
bool create_succeeded = false;
std::uniform_int_distribution<uint> m_dist(0, m - 1);
do
{
r_bar += d;
r = std::pow(r_bar, d);
VALUE(r);
VALUE(r_bar);
create_succeeded = create(data, m_dist);
} while (!create_succeeded);
}
uint prime()
{
static const std::vector<uint> primes{ 53, 97, 193, 389, 769, 1543, 3079, 6151, 12289,
24593, 49157, 98317, 196613, 393241, 786433, 1572869, 3145739, 6291469 };
static std::uniform_int_distribution<uint> prime_dist(0, primes.size() - 1);
return primes[prime_dist(generator)];
}
bool bad_m_r()
{
auto m_mod_r = m_bar % r_bar;
return m_mod_r == 1 || m_mod_r == r - 1;
}
void insert(const bucket& b, decltype(H)& H_hat, decltype(H_b)& H_b_hat,
const decltype(phi)& phi_hat)
{
for (auto& element : b)
{
auto hashed = h(element.location, phi_hat);
auto i = point_to_index<d>(hashed, m_bar, m);
H_hat[i] = element.contents;
H_b_hat[i] = true;
}
}
bool jiggle_offsets(decltype(H)& H_hat, decltype(H_b)& H_b_hat,
decltype(phi)& phi_hat, const bucket& b,
std::uniform_int_distribution<uint>& m_dist)
{
uint start_offset = m_dist(generator);
bool found = false;
point<d> found_offset;
tbb::mutex mutex;
uint chunk_index = 0;
const uint num_cores = 8;
const uint group_size = r / num_cores + 1;
tbb::parallel_pipeline(num_cores,
tbb::make_filter<void, uint>(tbb::filter::serial,
[=, &chunk_index, &found, &group_size](tbb::flow_control& fc) {
if (found || chunk_index >= r)
{
fc.stop();
}
chunk_index += group_size;
return chunk_index;
}) &
tbb::make_filter<uint, void>(tbb::filter::parallel,
[=, &mutex, &found, &found_offset, &b, &phi_hat, &H_hat, &H_b_hat](uint i0)
{
for (uint i = i0; i < i0 + group_size && !found; i++)
{
auto phi_offset = index_to_point<d>((start_offset + i) % m, m_bar, m);
bool collision = false;
for (auto& element : b)
{
auto h0 = M0 * element.location;
auto h1 = M1 * element.location;
auto index = point_to_index<d>(h1, r_bar, r);
auto offset = index == b.phi_index ? phi_offset : phi_hat[index];
auto hash = h0 + offset;
collision = H_b_hat[point_to_index<d>(hash, m_bar, m)];
if (collision)
break;
}
if (!collision)
{
tbb::mutex::scoped_lock lock(mutex);
if (!found)
{
found = true;
found_offset = phi_offset;
}
}
}
})
);
if (found)
{
phi_hat[b.phi_index] = found_offset;
insert(b, H_hat, H_b_hat, phi_hat);
return true;
}
return false;
}
std::vector<bucket> create_buckets(const std::vector<data_t>& data)
{
std::vector<bucket> buckets;
buckets.reserve(r);
{
uint i = 0;
std::generate_n(std::back_inserter(buckets), r, [&] {
return bucket(i++);
});
}
for (auto& element : data)
{
auto h1 = M1 * element.location;
buckets[point_to_index<d>(h1, r_bar, r)].push_back(element);
}
std::cout << "buckets created" << std::endl;
tbb::parallel_sort(buckets.begin(), buckets.end());
std::cout << "buckets sorted" << std::endl;
return buckets;
}
bool create(const std::vector<data_t>& data, std::uniform_int_distribution<uint>& m_dist)
{
decltype(phi) phi_hat;
phi_hat.reserve(r);
decltype(H) H_hat;
H_hat.reserve(m);
decltype(H_b) H_b_hat(m, false);
std::cout << "creating " << r << " buckets" << std::endl;
if (bad_m_r())
return false;
auto buckets = create_buckets(data);
std::cout << "jiggling offsets" << std::endl;
for (uint i = 0; i < buckets.size(); i++)
{
if (buckets[i].size() == 0)
break;
if (i % (buckets.size() / 10) == 0)
std::cout << (100 * i) / buckets.size() << "% done" << std::endl;
if (!jiggle_offsets(H_hat, H_b_hat, phi_hat, buckets[i], m_dist))
{
return false;
}
}
std::cout << "done!" << std::endl;
phi = std::move(phi_hat);
H = std::move(H_hat);
H_b = std::move(H_b_hat);
return true;
}
point<d> h(const point<d>& p, const decltype(phi)& phi_hat) const
{
auto h0 = M0 * p;
auto h1 = M1 * p;
auto offset = phi_hat[point_to_index<d>(h1, r_bar, r)];
return h0 + offset;
}
point<d> h(const point<d>& p) const
{
return h(p, phi);
}
T get(const point<d>& p) const
{
auto i = point_to_index<d>(h(p), m_bar, m);
if (H_b[i])
return H[i];
else
throw std::out_of_range("Element not found in map");
}
uint memory_size() const
{
return sizeof(*this)
+ sizeof(typename decltype(phi)::value_type) * phi.capacity()
+ sizeof(typename decltype(H)::value_type) * H.capacity();
}
};
}<commit_msg>added another 'vector<bool>' to keep track of phi insertions<commit_after>#pragma once
#include <string>
#include <functional>
#include <cmath>
#include <random>
#include <iostream>
#include <vector>
#include <utility>
#include "tbb/parallel_sort.h"
#include "tbb/mutex.h"
#include "tbb/pipeline.h"
#include "util.hpp"
#include "point.hpp"
#define VALUE(x) std::cout << #x "=" << x << std::endl
namespace psh
{
template<uint d, class T>
class map
{
static_assert(d > 0, "d must be larger than 0.");
public:
struct data_t
{
point<d> location;
T contents;
};
struct bucket : public std::vector<data_t>
{
uint phi_index;
bucket(uint phi_index) : phi_index(phi_index) { }
friend bool operator<(const bucket& lhs, const bucket& rhs) {
return lhs.size() > rhs.size();
}
};
uint M0;
uint M1;
uint n;
uint m_bar;
uint m;
uint r_bar;
uint r;
std::vector<bool> phi_b;
std::vector<point<d>> phi;
std::vector<bool> H_b;
std::vector<T> H;
std::default_random_engine generator;
map(const std::vector<data_t>& data)
: n(data.size()), m_bar(std::ceil(std::pow(n, 1.0f / d))), m(std::pow(m_bar, d)),
r_bar(std::ceil(std::pow(n / d, 1.0f / d)) - 1), generator(time(0))
{
M0 = prime();
while ((M1 = prime()) == M0);
VALUE(m);
VALUE(m_bar);
bool create_succeeded = false;
std::uniform_int_distribution<uint> m_dist(0, m - 1);
do
{
r_bar += d;
r = std::pow(r_bar, d);
VALUE(r);
VALUE(r_bar);
create_succeeded = create(data, m_dist);
} while (!create_succeeded);
}
uint prime()
{
static const std::vector<uint> primes{ 53, 97, 193, 389, 769, 1543, 3079, 6151, 12289,
24593, 49157, 98317, 196613, 393241, 786433, 1572869, 3145739, 6291469 };
static std::uniform_int_distribution<uint> prime_dist(0, primes.size() - 1);
return primes[prime_dist(generator)];
}
bool bad_m_r()
{
auto m_mod_r = m_bar % r_bar;
return m_mod_r == 1 || m_mod_r == r - 1;
}
void insert(const bucket& b, decltype(H)& H_hat, decltype(H_b)& H_b_hat,
const decltype(phi)& phi_hat, const decltype(phi_b)& phi_b_hat)
{
for (auto& element : b)
{
auto hashed = h(element.location, phi_hat, phi_b_hat);
auto i = point_to_index<d>(hashed, m_bar, m);
H_hat[i] = element.contents;
H_b_hat[i] = true;
}
}
bool jiggle_offsets(decltype(H)& H_hat, decltype(H_b)& H_b_hat,
decltype(phi)& phi_hat, decltype(phi_b)& phi_b_hat, const bucket& b,
std::uniform_int_distribution<uint>& m_dist)
{
uint start_offset = m_dist(generator);
bool found = false;
point<d> found_offset;
tbb::mutex mutex;
uint chunk_index = 0;
const uint num_cores = 8;
const uint group_size = r / num_cores + 1;
tbb::parallel_pipeline(num_cores,
tbb::make_filter<void, uint>(tbb::filter::serial,
[=, &chunk_index, &found, &group_size](tbb::flow_control& fc) {
if (found || chunk_index >= r)
{
fc.stop();
}
chunk_index += group_size;
return chunk_index;
}) &
tbb::make_filter<uint, void>(tbb::filter::parallel,
[=, &mutex, &found, &found_offset, &b, &phi_hat, &phi_b_hat, &H_hat, &H_b_hat](uint i0)
{
for (uint i = i0; i < i0 + group_size && !found; i++)
{
auto phi_offset = index_to_point<d>((start_offset + i) % m, m_bar, m);
bool collision = false;
for (auto& element : b)
{
auto h0 = M0 * element.location;
auto h1 = M1 * element.location;
auto index = point_to_index<d>(h1, r_bar, r);
auto offset = index == b.phi_index ? phi_offset : phi_hat[index];
auto hash = h0 + offset;
collision = H_b_hat[point_to_index<d>(hash, m_bar, m)];
if (collision)
break;
}
if (!collision)
{
tbb::mutex::scoped_lock lock(mutex);
if (!found)
{
found = true;
found_offset = phi_offset;
}
}
}
})
);
if (found)
{
phi_b_hat[b.phi_index] = true;
phi_hat[b.phi_index] = found_offset;
insert(b, H_hat, H_b_hat, phi_hat, phi_b_hat);
return true;
}
return false;
}
std::vector<bucket> create_buckets(const std::vector<data_t>& data)
{
std::vector<bucket> buckets;
buckets.reserve(r);
{
uint i = 0;
std::generate_n(std::back_inserter(buckets), r, [&] {
return bucket(i++);
});
}
for (auto& element : data)
{
auto h1 = M1 * element.location;
buckets[point_to_index<d>(h1, r_bar, r)].push_back(element);
}
std::cout << "buckets created" << std::endl;
tbb::parallel_sort(buckets.begin(), buckets.end());
std::cout << "buckets sorted" << std::endl;
return buckets;
}
bool create(const std::vector<data_t>& data, std::uniform_int_distribution<uint>& m_dist)
{
decltype(phi) phi_hat;
phi_hat.reserve(r);
decltype(phi_b) phi_b_hat(r, false);
decltype(H) H_hat;
H_hat.reserve(m);
decltype(H_b) H_b_hat(m, false);
std::cout << "creating " << r << " buckets" << std::endl;
if (bad_m_r())
return false;
auto buckets = create_buckets(data);
std::cout << "jiggling offsets" << std::endl;
for (uint i = 0; i < buckets.size(); i++)
{
if (buckets[i].size() == 0)
break;
if (i % (buckets.size() / 10) == 0)
std::cout << (100 * i) / buckets.size() << "% done" << std::endl;
if (!jiggle_offsets(H_hat, H_b_hat, phi_hat, phi_b_hat, buckets[i], m_dist))
{
return false;
}
}
std::cout << "done!" << std::endl;
phi = std::move(phi_hat);
phi_b = std::move(phi_b_hat);
H = std::move(H_hat);
H_b = std::move(H_b_hat);
return true;
}
point<d> h(const point<d>& p, const decltype(phi)& phi_hat,
const decltype(phi_b)& phi_b_hat) const
{
auto h0 = M0 * p;
auto h1 = M1 * p;
auto i = point_to_index<d>(h1, r_bar, r);
if (!phi_b_hat[i])
throw std::out_of_range("Element not found in map");
auto offset = phi_hat[i];
return h0 + offset;
}
point<d> h(const point<d>& p) const
{
return h(p, phi, phi_b);
}
T get(const point<d>& p) const
{
auto i = point_to_index<d>(h(p), m_bar, m);
if (H_b[i])
return H[i];
else
throw std::out_of_range("Element not found in map");
}
uint memory_size() const
{
return sizeof(*this)
+ sizeof(typename decltype(phi)::value_type) * phi.capacity()
+ sizeof(typename decltype(phi_b)::value_type) * phi_b.capacity()
+ sizeof(typename decltype(H)::value_type) * H.capacity()
+ sizeof(typename decltype(H_b)::value_type) * H_b.capacity();
}
};
}<|endoftext|>
|
<commit_before>#include <bitcoin/blockchain/blockchain.hpp>
#include <bitcoin/utility/assert.hpp>
namespace libbitcoin {
using std::placeholders::_1;
using std::placeholders::_2;
typedef blockchain_fetch_handler_block handler_block;
class fetch_block_t
: public std::enable_shared_from_this<fetch_block_t>
{
public:
fetch_block_t(blockchain_ptr chain)
: chain_(chain), stopped_(false) {}
template <typename BlockIndex>
void start(const BlockIndex& index, handler_block handle)
{
handle_ = handle;
auto this_ptr = shared_from_this();
chain_->fetch_block_header(index,
[this, this_ptr](const std::error_code& ec,
const message::block& block_header)
{
if (stop_on_error(ec))
return;
block_ = block_header;
fetch_hashes();
});
}
private:
bool stop_on_error(const std::error_code& ec)
{
if (stopped_)
return true;
else if (ec)
{
stopped_ = true;
handle_(ec, message::block());
return true;
}
return false;
}
void fetch_hashes()
{
chain_->fetch_block_transaction_hashes(
hash_block_header(block_),
std::bind(&fetch_block_t::fetch_transactions,
shared_from_this(), _1, _2));
}
void fetch_transactions(const std::error_code& ec,
const message::inventory_list& tx_hashes)
{
if (stop_on_error(ec))
return;
block_.transactions.resize(tx_hashes.size());
count_ = 0;
for (size_t tx_index = 0;
tx_index < tx_hashes.size(); ++tx_index)
{
fetch_tx(tx_hashes, tx_index);
}
}
void fetch_tx(const message::inventory_list& tx_hashes, size_t tx_index)
{
auto this_ptr = shared_from_this();
const message::inventory_vector& inv = tx_hashes[tx_index];
BITCOIN_ASSERT(inv.type ==
message::inventory_type::transaction);
size_t tx_hashes_size = tx_hashes.size();
chain_->fetch_transaction(inv.hash,
[this, this_ptr, tx_index, tx_hashes_size](
const std::error_code& ec,
const message::transaction& tx)
{
if (stop_on_error(ec))
return;
BITCOIN_ASSERT(tx_index < block_.transactions.size());
block_.transactions[tx_index] = tx;
++count_;
BITCOIN_ASSERT(block_.transactions.size() == tx_hashes_size);
if (count_ == tx_hashes_size)
handle_(std::error_code(), block_);
});
}
blockchain_ptr chain_;
handler_block handle_;
message::block block_;
size_t count_;
bool stopped_;
};
void fetch_block(blockchain_ptr chain, size_t depth,
handler_block handle_fetch)
{
auto fetcher = std::make_shared<fetch_block_t>(chain);
fetcher->start(depth, handle_fetch);
}
void fetch_block(blockchain_ptr chain, const hash_digest& block_hash,
handler_block handle_fetch)
{
auto fetcher = std::make_shared<fetch_block_t>(chain);
fetcher->start(block_hash, handle_fetch);
}
// fetch_block_locator
typedef blockchain_fetch_handler_block_locator handler_locator;
class fetch_locator
: public std::enable_shared_from_this<fetch_locator>
{
public:
fetch_locator(blockchain_ptr chain)
: chain_(chain) {}
void start(handler_locator handle)
{
handle_ = handle;
auto this_ptr = shared_from_this();
chain_->fetch_last_depth(
std::bind(&fetch_locator::populate,
this_ptr, _1, _2));
}
private:
// An intermediate type used to keep metadata about the locator
// so we can sort the locator before returning.
typedef std::pair<size_t, hash_digest> meta_entry;
typedef std::vector<meta_entry> meta_locator;
bool stop_on_error(const std::error_code& ec)
{
if (stopped_)
return true;
else if (ec)
{
stopped_ = true;
handle_(ec, message::block_locator());
return true;
}
return false;
}
void populate(const std::error_code& ec, size_t last_depth)
{
if (stop_on_error(ec))
return;
index_list indexes = block_locator_indexes(last_depth);
auto this_ptr = shared_from_this();
for (size_t depth: indexes)
chain_->fetch_block_header(depth,
std::bind(&fetch_locator::append,
this_ptr, _1, _2, depth, indexes.size()));
}
void append(const std::error_code& ec,
const message::block& block_header, size_t depth, size_t entries)
{
if (stop_on_error(ec))
return;
meta_.push_back(std::make_pair(depth, hash_block_header(block_header)));
if (meta_.size() == entries)
final();
}
void final()
{
std::sort(meta_.begin(), meta_.end(),
[](const meta_entry& entry_a, const meta_entry& entry_b)
{
return entry_a.first < entry_b.first;
});
message::block_locator final_locator;
for (const meta_entry& entry: meta_)
final_locator.push_back(entry.second);
handle_(std::error_code(), final_locator);
}
blockchain_ptr chain_;
handler_locator handle_;
bool stopped_;
meta_locator meta_;
};
void fetch_block_locator(blockchain_ptr chain, handler_locator handle_fetch)
{
auto fetcher = std::make_shared<fetch_locator>(chain);
fetcher->start(handle_fetch);
}
} // namespace libbitcoin
<commit_msg>Bugfix: fetch_block_locator returning entries reversed.<commit_after>#include <bitcoin/blockchain/blockchain.hpp>
#include <bitcoin/utility/assert.hpp>
namespace libbitcoin {
using std::placeholders::_1;
using std::placeholders::_2;
typedef blockchain_fetch_handler_block handler_block;
class fetch_block_t
: public std::enable_shared_from_this<fetch_block_t>
{
public:
fetch_block_t(blockchain_ptr chain)
: chain_(chain), stopped_(false) {}
template <typename BlockIndex>
void start(const BlockIndex& index, handler_block handle)
{
handle_ = handle;
auto this_ptr = shared_from_this();
chain_->fetch_block_header(index,
[this, this_ptr](const std::error_code& ec,
const message::block& block_header)
{
if (stop_on_error(ec))
return;
block_ = block_header;
fetch_hashes();
});
}
private:
bool stop_on_error(const std::error_code& ec)
{
if (stopped_)
return true;
else if (ec)
{
stopped_ = true;
handle_(ec, message::block());
return true;
}
return false;
}
void fetch_hashes()
{
chain_->fetch_block_transaction_hashes(
hash_block_header(block_),
std::bind(&fetch_block_t::fetch_transactions,
shared_from_this(), _1, _2));
}
void fetch_transactions(const std::error_code& ec,
const message::inventory_list& tx_hashes)
{
if (stop_on_error(ec))
return;
block_.transactions.resize(tx_hashes.size());
count_ = 0;
for (size_t tx_index = 0;
tx_index < tx_hashes.size(); ++tx_index)
{
fetch_tx(tx_hashes, tx_index);
}
}
void fetch_tx(const message::inventory_list& tx_hashes, size_t tx_index)
{
auto this_ptr = shared_from_this();
const message::inventory_vector& inv = tx_hashes[tx_index];
BITCOIN_ASSERT(inv.type ==
message::inventory_type::transaction);
size_t tx_hashes_size = tx_hashes.size();
chain_->fetch_transaction(inv.hash,
[this, this_ptr, tx_index, tx_hashes_size](
const std::error_code& ec,
const message::transaction& tx)
{
if (stop_on_error(ec))
return;
BITCOIN_ASSERT(tx_index < block_.transactions.size());
block_.transactions[tx_index] = tx;
++count_;
BITCOIN_ASSERT(block_.transactions.size() == tx_hashes_size);
if (count_ == tx_hashes_size)
handle_(std::error_code(), block_);
});
}
blockchain_ptr chain_;
handler_block handle_;
message::block block_;
size_t count_;
bool stopped_;
};
void fetch_block(blockchain_ptr chain, size_t depth,
handler_block handle_fetch)
{
auto fetcher = std::make_shared<fetch_block_t>(chain);
fetcher->start(depth, handle_fetch);
}
void fetch_block(blockchain_ptr chain, const hash_digest& block_hash,
handler_block handle_fetch)
{
auto fetcher = std::make_shared<fetch_block_t>(chain);
fetcher->start(block_hash, handle_fetch);
}
// fetch_block_locator
typedef blockchain_fetch_handler_block_locator handler_locator;
class fetch_locator
: public std::enable_shared_from_this<fetch_locator>
{
public:
fetch_locator(blockchain_ptr chain)
: chain_(chain) {}
void start(handler_locator handle)
{
handle_ = handle;
auto this_ptr = shared_from_this();
chain_->fetch_last_depth(
std::bind(&fetch_locator::populate,
this_ptr, _1, _2));
}
private:
// An intermediate type used to keep metadata about the locator
// so we can sort the locator before returning.
typedef std::pair<size_t, hash_digest> meta_entry;
typedef std::vector<meta_entry> meta_locator;
bool stop_on_error(const std::error_code& ec)
{
if (stopped_)
return true;
else if (ec)
{
stopped_ = true;
handle_(ec, message::block_locator());
return true;
}
return false;
}
void populate(const std::error_code& ec, size_t last_depth)
{
if (stop_on_error(ec))
return;
index_list indexes = block_locator_indexes(last_depth);
auto this_ptr = shared_from_this();
for (size_t depth: indexes)
chain_->fetch_block_header(depth,
std::bind(&fetch_locator::append,
this_ptr, _1, _2, depth, indexes.size()));
}
void append(const std::error_code& ec,
const message::block& block_header, size_t depth, size_t entries)
{
if (stop_on_error(ec))
return;
meta_.push_back(std::make_pair(depth, hash_block_header(block_header)));
if (meta_.size() == entries)
final();
}
void final()
{
std::sort(meta_.begin(), meta_.end(),
[](const meta_entry& entry_a, const meta_entry& entry_b)
{
return entry_a.first > entry_b.first;
});
message::block_locator final_locator;
for (const meta_entry& entry: meta_)
final_locator.push_back(entry.second);
handle_(std::error_code(), final_locator);
}
blockchain_ptr chain_;
handler_locator handle_;
bool stopped_;
meta_locator meta_;
};
void fetch_block_locator(blockchain_ptr chain, handler_locator handle_fetch)
{
auto fetcher = std::make_shared<fetch_locator>(chain);
fetcher->start(handle_fetch);
}
} // namespace libbitcoin
<|endoftext|>
|
<commit_before>
// Visomics includes
#include "voDelimitedTextImportWidget.h"
#include "ui_voDelimitedTextImportWidget.h"
#include "voDelimitedTextPreviewModel.h"
class voDelimitedTextImportWidgetPrivate : public Ui_voDelimitedTextImportWidget
{
public:
voDelimitedTextImportWidgetPrivate();
void initWidgetFromModel();
QButtonGroup DelimiterButtonGroup;
voDelimitedTextPreviewModel * DelimitedTextPreviewModel;
};
// --------------------------------------------------------------------------
// voDelimitedTextImportWidgetPrivate methods
// --------------------------------------------------------------------------
voDelimitedTextImportWidgetPrivate::voDelimitedTextImportWidgetPrivate()
{
this->DelimitedTextPreviewModel = 0;
}
// --------------------------------------------------------------------------
void voDelimitedTextImportWidgetPrivate::initWidgetFromModel()
{
this->OtherLineEdit->setText(QString(":"));
switch (this->DelimitedTextPreviewModel->fieldDelimiterCharacters().at(0).toLatin1())
{
case ',':
this->CommaRadioButton->setChecked(true);
break;
case ';':
this->SemicolonRadioButton->setChecked(true);
break;
case '\t':
this->TabRadioButton->setChecked(true);
break;
case ' ':
this->SpaceRadioButton->setChecked(true);
break;
default:
this->OtherRadioButton->setChecked(true);
this->OtherLineEdit->setText(this->DelimitedTextPreviewModel->fieldDelimiterCharacters());
break;
}
this->StringDelimiterCheckBox->setChecked(this->DelimitedTextPreviewModel->useStringDelimiter());
this->StringDelimiterLineEdit->setText(QString(QChar(this->DelimitedTextPreviewModel->stringDelimiter())));
this->TransposeCheckBox->setChecked(this->DelimitedTextPreviewModel->transpose());
this->NumberHeaderColumnsSpinBox->setValue(this->DelimitedTextPreviewModel->numberOfRowMetaDataTypes());
if(this->DelimitedTextPreviewModel->numberOfRowMetaDataTypes() > 0)
{
this->HeaderColumnOfInterestSpinBox->setRange(0, this->DelimitedTextPreviewModel->numberOfRowMetaDataTypes()-1);
this->HeaderColumnOfInterestSpinBox->setValue(this->DelimitedTextPreviewModel->rowMetaDataTypeOfInterest());
this->HeaderColumnOfInterestSpinBox->setEnabled(true);
}
else
{
this->HeaderColumnOfInterestSpinBox->setMinimum(-1);
this->HeaderColumnOfInterestSpinBox->setValue(-1);
this->HeaderColumnOfInterestSpinBox->setEnabled(false);
}
this->NumberHeaderRowsSpinBox->setValue(this->DelimitedTextPreviewModel->numberOfColumnMetaDataTypes());
if(this->DelimitedTextPreviewModel->numberOfColumnMetaDataTypes() > 0)
{
this->HeaderRowOfInterestSpinBox->setRange(0, this->DelimitedTextPreviewModel->numberOfColumnMetaDataTypes()-1);
this->HeaderRowOfInterestSpinBox->setValue(this->DelimitedTextPreviewModel->columnMetaDataTypeOfInterest());
this->HeaderRowOfInterestSpinBox->setEnabled(true);
}
else
{
this->HeaderRowOfInterestSpinBox->setMinimum(-1);
this->HeaderRowOfInterestSpinBox->setValue(-1);
this->HeaderRowOfInterestSpinBox->setEnabled(false);
}
}
// --------------------------------------------------------------------------
// voDelimitedTextImportWidget methods
// --------------------------------------------------------------------------
voDelimitedTextImportWidget::voDelimitedTextImportWidget(QWidget* newParent) :
Superclass(newParent), d_ptr(new voDelimitedTextImportWidgetPrivate())
{
Q_D(voDelimitedTextImportWidget);
d->setupUi(this);
d->DelimiterButtonGroup.addButton(d->CommaRadioButton, ',');
d->DelimiterButtonGroup.addButton(d->SemicolonRadioButton, ';');
d->DelimiterButtonGroup.addButton(d->TabRadioButton, '\t');
d->DelimiterButtonGroup.addButton(d->SpaceRadioButton, ' ');
d->DelimiterButtonGroup.addButton(d->OtherRadioButton, 'x');
// Delimiter connections
connect(&d->DelimiterButtonGroup, SIGNAL(buttonClicked(int)),
this, SLOT(onDelimiterChanged(int)));
// StringBeginEndCharacter connection
connect(d->StringDelimiterCheckBox, SIGNAL(toggled(bool)),
this, SLOT(onStringDelimiterEnabled(bool)));
}
// --------------------------------------------------------------------------
voDelimitedTextImportWidget::~voDelimitedTextImportWidget()
{
}
// --------------------------------------------------------------------------
void voDelimitedTextImportWidget::insertWidget(QWidget * widget, InsertWidgetLocation location)
{
Q_D(voDelimitedTextImportWidget);
if (!widget)
{
return;
}
int index = -1;
if (location == Self::DelimiterGroupBox)
{
index = d->MainVerticalLayout->indexOf(d->DelimiterGroupBox);
}
else if (location == Self::RowsAndColumnsGroupBox)
{
index = d->MainVerticalLayout->indexOf(d->RowsColumnsGroupBox);
}
Q_ASSERT(index != -1);
d->MainVerticalLayout->insertWidget(index, widget);
}
// --------------------------------------------------------------------------
voDelimitedTextPreviewModel* voDelimitedTextImportWidget::delimitedTextPreviewModel()
{
Q_D(voDelimitedTextImportWidget);
return d->DelimitedTextPreviewModel;
}
// --------------------------------------------------------------------------
void voDelimitedTextImportWidget::setDelimitedTextPreviewModel(voDelimitedTextPreviewModel* model)
{
Q_D(voDelimitedTextImportWidget);
if (d->DelimitedTextPreviewModel == model)
{
return;
}
// Disconnect model
if (d->DelimitedTextPreviewModel)
{
// Widget -> Model connections
disconnect(d->TransposeCheckBox, SIGNAL(toggled(bool)),
d->DelimitedTextPreviewModel, SLOT(setTranspose(bool)));
disconnect(d->NumberHeaderColumnsSpinBox, SIGNAL(valueChanged(int)),
d->DelimitedTextPreviewModel, SLOT(setNumberOfRowMetaDataTypes(int)));
disconnect(d->HeaderColumnOfInterestSpinBox, SIGNAL(valueChanged(int)),
d->DelimitedTextPreviewModel, SLOT(setRowMetaDataTypeOfInterest(int)));
disconnect(d->NumberHeaderRowsSpinBox, SIGNAL(valueChanged(int)),
d->DelimitedTextPreviewModel, SLOT(setNumberOfColumnMetaDataTypes(int)));
disconnect(d->HeaderRowOfInterestSpinBox, SIGNAL(valueChanged(int)),
d->DelimitedTextPreviewModel, SLOT(setColumnMetaDataTypeOfInterest(int)));
// Model -> Widget connections
disconnect(d->DelimitedTextPreviewModel, SIGNAL(numberOfColumnMetaDataTypesChanged(int)),
this, SLOT(onNumberOfColumnMetaDataTypesChanged(int)));
disconnect(d->DelimitedTextPreviewModel, SIGNAL(columnMetaDataTypeOfInterestChanged(int)),
this, SLOT(onColumnMetaDataTypeOfInterestChanged(int)));
disconnect(d->DelimitedTextPreviewModel, SIGNAL(numberOfRowMetaDataTypesChanged(int)),
this, SLOT(onNumberOfRowMetaDataTypesChanged(int)));
disconnect(d->DelimitedTextPreviewModel, SIGNAL(rowMetaDataTypeOfInterestChanged(int)),
this, SLOT(onRowMetaDataTypeOfInterestChanged(int)));
}
d->DelimitedTextPreviewModel = model;
if (d->DelimitedTextPreviewModel)
{
d->initWidgetFromModel();
// Widget -> Model connections
connect(d->TransposeCheckBox, SIGNAL(toggled(bool)),
d->DelimitedTextPreviewModel, SLOT(setTranspose(bool)));
connect(d->NumberHeaderColumnsSpinBox, SIGNAL(valueChanged(int)),
d->DelimitedTextPreviewModel, SLOT(setNumberOfRowMetaDataTypes(int)));
connect(d->HeaderColumnOfInterestSpinBox, SIGNAL(valueChanged(int)),
d->DelimitedTextPreviewModel, SLOT(setRowMetaDataTypeOfInterest(int)));
connect(d->NumberHeaderRowsSpinBox, SIGNAL(valueChanged(int)),
d->DelimitedTextPreviewModel, SLOT(setNumberOfColumnMetaDataTypes(int)));
connect(d->HeaderRowOfInterestSpinBox, SIGNAL(valueChanged(int)),
d->DelimitedTextPreviewModel, SLOT(setColumnMetaDataTypeOfInterest(int)));
// Model -> Widget connections
connect(d->DelimitedTextPreviewModel, SIGNAL(numberOfColumnMetaDataTypesChanged(int)),
this, SLOT(onNumberOfColumnMetaDataTypesChanged(int)));
connect(d->DelimitedTextPreviewModel, SIGNAL(columnMetaDataTypeOfInterestChanged(int)),
this, SLOT(onColumnMetaDataTypeOfInterestChanged(int)));
connect(d->DelimitedTextPreviewModel, SIGNAL(numberOfRowMetaDataTypesChanged(int)),
this, SLOT(onNumberOfRowMetaDataTypesChanged(int)));
connect(d->DelimitedTextPreviewModel, SIGNAL(rowMetaDataTypeOfInterestChanged(int)),
this, SLOT(onRowMetaDataTypeOfInterestChanged(int)));
}
}
// --------------------------------------------------------------------------
void voDelimitedTextImportWidget::onNumberOfColumnMetaDataTypesChanged(int value)
{
Q_D(voDelimitedTextImportWidget);
d->NumberHeaderRowsSpinBox->setValue(value);
if(value > 0)
{
d->HeaderRowOfInterestSpinBox->setRange(0, value-1);
}
else
{
d->HeaderRowOfInterestSpinBox->setMinimum(-1);
}
d->HeaderRowOfInterestSpinBox->setEnabled(value > 0);
}
// --------------------------------------------------------------------------
void voDelimitedTextImportWidget::onColumnMetaDataTypeOfInterestChanged(int value)
{
Q_D(voDelimitedTextImportWidget);
d->HeaderRowOfInterestSpinBox->setValue(value);
}
// --------------------------------------------------------------------------
void voDelimitedTextImportWidget::onNumberOfRowMetaDataTypesChanged(int value)
{
Q_D(voDelimitedTextImportWidget);
d->NumberHeaderColumnsSpinBox->setValue(value);
if(value > 0)
{
d->HeaderColumnOfInterestSpinBox->setRange(0, value-1);
}
else
{
d->HeaderColumnOfInterestSpinBox->setMinimum(-1);
}
d->HeaderColumnOfInterestSpinBox->setEnabled(value > 0);
}
// --------------------------------------------------------------------------
void voDelimitedTextImportWidget::onRowMetaDataTypeOfInterestChanged(int value)
{
Q_D(voDelimitedTextImportWidget);
d->HeaderColumnOfInterestSpinBox->setValue(value);
}
// --------------------------------------------------------------------------
void voDelimitedTextImportWidget::onDelimiterChanged(int delimiter)
{
Q_D(voDelimitedTextImportWidget);
if (delimiter == 'x')
{ // Special case triggered by OtherRadioButton
QString text = d->OtherLineEdit->text();
connect(d->OtherLineEdit, SIGNAL(textChanged(const QString&)),
this, SLOT(onOtherDelimiterLineEditChanged(const QString&)));
if (text.isEmpty())
{
return;
}
delimiter = text.at(0).toLatin1();
}
else
{
disconnect(d->OtherLineEdit, SIGNAL(textChanged(const QString&)),
this, SLOT(onOtherDelimiterLineEditChanged(const QString&)));
}
d->DelimitedTextPreviewModel->setFieldDelimiter(delimiter);
}
// --------------------------------------------------------------------------
void voDelimitedTextImportWidget::onOtherDelimiterLineEditChanged(const QString& text)
{
Q_D(voDelimitedTextImportWidget);
if (text.isEmpty())
{
return;
}
char delimiter = d->OtherLineEdit->text().at(0).toLatin1();
d->DelimitedTextPreviewModel->setFieldDelimiter(delimiter);
}
// --------------------------------------------------------------------------
void voDelimitedTextImportWidget::onStringDelimiterEnabled(bool value)
{
Q_D(voDelimitedTextImportWidget);
char character = 0;
if (value)
{
QString text = d->StringDelimiterLineEdit->text();
connect(d->StringDelimiterLineEdit, SIGNAL(textChanged(const QString&)),
this, SLOT(onStringDelimiterLineEditChanged(const QString&)));
if (text.isEmpty())
{
return;
}
character = text.at(0).toLatin1();
}
else
{
disconnect(d->StringDelimiterLineEdit, SIGNAL(textChanged(const QString&)),
this, SLOT(onStringDelimiterLineEditChanged(const QString&)));
}
d->DelimitedTextPreviewModel->setStringDelimiter(character);
}
// --------------------------------------------------------------------------
void voDelimitedTextImportWidget::onStringDelimiterLineEditChanged(const QString& text)
{
Q_D(voDelimitedTextImportWidget);
if (text.isEmpty())
{
return;
}
char character = d->StringDelimiterLineEdit->text().at(0).toLatin1();
d->DelimitedTextPreviewModel->setStringDelimiter(character);
}
<commit_msg>Fix voDelimitedTextImportWidget::insertWidget function<commit_after>
// Visomics includes
#include "voDelimitedTextImportWidget.h"
#include "ui_voDelimitedTextImportWidget.h"
#include "voDelimitedTextPreviewModel.h"
class voDelimitedTextImportWidgetPrivate : public Ui_voDelimitedTextImportWidget
{
public:
voDelimitedTextImportWidgetPrivate();
void initWidgetFromModel();
QButtonGroup DelimiterButtonGroup;
voDelimitedTextPreviewModel * DelimitedTextPreviewModel;
};
// --------------------------------------------------------------------------
// voDelimitedTextImportWidgetPrivate methods
// --------------------------------------------------------------------------
voDelimitedTextImportWidgetPrivate::voDelimitedTextImportWidgetPrivate()
{
this->DelimitedTextPreviewModel = 0;
}
// --------------------------------------------------------------------------
void voDelimitedTextImportWidgetPrivate::initWidgetFromModel()
{
this->OtherLineEdit->setText(QString(":"));
switch (this->DelimitedTextPreviewModel->fieldDelimiterCharacters().at(0).toLatin1())
{
case ',':
this->CommaRadioButton->setChecked(true);
break;
case ';':
this->SemicolonRadioButton->setChecked(true);
break;
case '\t':
this->TabRadioButton->setChecked(true);
break;
case ' ':
this->SpaceRadioButton->setChecked(true);
break;
default:
this->OtherRadioButton->setChecked(true);
this->OtherLineEdit->setText(this->DelimitedTextPreviewModel->fieldDelimiterCharacters());
break;
}
this->StringDelimiterCheckBox->setChecked(this->DelimitedTextPreviewModel->useStringDelimiter());
this->StringDelimiterLineEdit->setText(QString(QChar(this->DelimitedTextPreviewModel->stringDelimiter())));
this->TransposeCheckBox->setChecked(this->DelimitedTextPreviewModel->transpose());
this->NumberHeaderColumnsSpinBox->setValue(this->DelimitedTextPreviewModel->numberOfRowMetaDataTypes());
if(this->DelimitedTextPreviewModel->numberOfRowMetaDataTypes() > 0)
{
this->HeaderColumnOfInterestSpinBox->setRange(0, this->DelimitedTextPreviewModel->numberOfRowMetaDataTypes()-1);
this->HeaderColumnOfInterestSpinBox->setValue(this->DelimitedTextPreviewModel->rowMetaDataTypeOfInterest());
this->HeaderColumnOfInterestSpinBox->setEnabled(true);
}
else
{
this->HeaderColumnOfInterestSpinBox->setMinimum(-1);
this->HeaderColumnOfInterestSpinBox->setValue(-1);
this->HeaderColumnOfInterestSpinBox->setEnabled(false);
}
this->NumberHeaderRowsSpinBox->setValue(this->DelimitedTextPreviewModel->numberOfColumnMetaDataTypes());
if(this->DelimitedTextPreviewModel->numberOfColumnMetaDataTypes() > 0)
{
this->HeaderRowOfInterestSpinBox->setRange(0, this->DelimitedTextPreviewModel->numberOfColumnMetaDataTypes()-1);
this->HeaderRowOfInterestSpinBox->setValue(this->DelimitedTextPreviewModel->columnMetaDataTypeOfInterest());
this->HeaderRowOfInterestSpinBox->setEnabled(true);
}
else
{
this->HeaderRowOfInterestSpinBox->setMinimum(-1);
this->HeaderRowOfInterestSpinBox->setValue(-1);
this->HeaderRowOfInterestSpinBox->setEnabled(false);
}
}
// --------------------------------------------------------------------------
// voDelimitedTextImportWidget methods
// --------------------------------------------------------------------------
voDelimitedTextImportWidget::voDelimitedTextImportWidget(QWidget* newParent) :
Superclass(newParent), d_ptr(new voDelimitedTextImportWidgetPrivate())
{
Q_D(voDelimitedTextImportWidget);
d->setupUi(this);
d->DelimiterButtonGroup.addButton(d->CommaRadioButton, ',');
d->DelimiterButtonGroup.addButton(d->SemicolonRadioButton, ';');
d->DelimiterButtonGroup.addButton(d->TabRadioButton, '\t');
d->DelimiterButtonGroup.addButton(d->SpaceRadioButton, ' ');
d->DelimiterButtonGroup.addButton(d->OtherRadioButton, 'x');
// Delimiter connections
connect(&d->DelimiterButtonGroup, SIGNAL(buttonClicked(int)),
this, SLOT(onDelimiterChanged(int)));
// StringBeginEndCharacter connection
connect(d->StringDelimiterCheckBox, SIGNAL(toggled(bool)),
this, SLOT(onStringDelimiterEnabled(bool)));
}
// --------------------------------------------------------------------------
voDelimitedTextImportWidget::~voDelimitedTextImportWidget()
{
}
// --------------------------------------------------------------------------
void voDelimitedTextImportWidget::insertWidget(QWidget * widget, InsertWidgetLocation location)
{
Q_D(voDelimitedTextImportWidget);
if (!widget)
{
return;
}
int index = -1;
if (location == Self::DelimiterGroupBox)
{
index = d->MainVerticalLayout->indexOf(d->DelimiterGroupBox);
}
else if (location == Self::RowsAndColumnsGroupBox)
{
index = d->MainVerticalLayout->indexOf(d->RowsColumnsGroupBox);
}
Q_ASSERT(index != -1);
d->MainVerticalLayout->insertWidget(index + 1, widget);
}
// --------------------------------------------------------------------------
voDelimitedTextPreviewModel* voDelimitedTextImportWidget::delimitedTextPreviewModel()
{
Q_D(voDelimitedTextImportWidget);
return d->DelimitedTextPreviewModel;
}
// --------------------------------------------------------------------------
void voDelimitedTextImportWidget::setDelimitedTextPreviewModel(voDelimitedTextPreviewModel* model)
{
Q_D(voDelimitedTextImportWidget);
if (d->DelimitedTextPreviewModel == model)
{
return;
}
// Disconnect model
if (d->DelimitedTextPreviewModel)
{
// Widget -> Model connections
disconnect(d->TransposeCheckBox, SIGNAL(toggled(bool)),
d->DelimitedTextPreviewModel, SLOT(setTranspose(bool)));
disconnect(d->NumberHeaderColumnsSpinBox, SIGNAL(valueChanged(int)),
d->DelimitedTextPreviewModel, SLOT(setNumberOfRowMetaDataTypes(int)));
disconnect(d->HeaderColumnOfInterestSpinBox, SIGNAL(valueChanged(int)),
d->DelimitedTextPreviewModel, SLOT(setRowMetaDataTypeOfInterest(int)));
disconnect(d->NumberHeaderRowsSpinBox, SIGNAL(valueChanged(int)),
d->DelimitedTextPreviewModel, SLOT(setNumberOfColumnMetaDataTypes(int)));
disconnect(d->HeaderRowOfInterestSpinBox, SIGNAL(valueChanged(int)),
d->DelimitedTextPreviewModel, SLOT(setColumnMetaDataTypeOfInterest(int)));
// Model -> Widget connections
disconnect(d->DelimitedTextPreviewModel, SIGNAL(numberOfColumnMetaDataTypesChanged(int)),
this, SLOT(onNumberOfColumnMetaDataTypesChanged(int)));
disconnect(d->DelimitedTextPreviewModel, SIGNAL(columnMetaDataTypeOfInterestChanged(int)),
this, SLOT(onColumnMetaDataTypeOfInterestChanged(int)));
disconnect(d->DelimitedTextPreviewModel, SIGNAL(numberOfRowMetaDataTypesChanged(int)),
this, SLOT(onNumberOfRowMetaDataTypesChanged(int)));
disconnect(d->DelimitedTextPreviewModel, SIGNAL(rowMetaDataTypeOfInterestChanged(int)),
this, SLOT(onRowMetaDataTypeOfInterestChanged(int)));
}
d->DelimitedTextPreviewModel = model;
if (d->DelimitedTextPreviewModel)
{
d->initWidgetFromModel();
// Widget -> Model connections
connect(d->TransposeCheckBox, SIGNAL(toggled(bool)),
d->DelimitedTextPreviewModel, SLOT(setTranspose(bool)));
connect(d->NumberHeaderColumnsSpinBox, SIGNAL(valueChanged(int)),
d->DelimitedTextPreviewModel, SLOT(setNumberOfRowMetaDataTypes(int)));
connect(d->HeaderColumnOfInterestSpinBox, SIGNAL(valueChanged(int)),
d->DelimitedTextPreviewModel, SLOT(setRowMetaDataTypeOfInterest(int)));
connect(d->NumberHeaderRowsSpinBox, SIGNAL(valueChanged(int)),
d->DelimitedTextPreviewModel, SLOT(setNumberOfColumnMetaDataTypes(int)));
connect(d->HeaderRowOfInterestSpinBox, SIGNAL(valueChanged(int)),
d->DelimitedTextPreviewModel, SLOT(setColumnMetaDataTypeOfInterest(int)));
// Model -> Widget connections
connect(d->DelimitedTextPreviewModel, SIGNAL(numberOfColumnMetaDataTypesChanged(int)),
this, SLOT(onNumberOfColumnMetaDataTypesChanged(int)));
connect(d->DelimitedTextPreviewModel, SIGNAL(columnMetaDataTypeOfInterestChanged(int)),
this, SLOT(onColumnMetaDataTypeOfInterestChanged(int)));
connect(d->DelimitedTextPreviewModel, SIGNAL(numberOfRowMetaDataTypesChanged(int)),
this, SLOT(onNumberOfRowMetaDataTypesChanged(int)));
connect(d->DelimitedTextPreviewModel, SIGNAL(rowMetaDataTypeOfInterestChanged(int)),
this, SLOT(onRowMetaDataTypeOfInterestChanged(int)));
}
}
// --------------------------------------------------------------------------
void voDelimitedTextImportWidget::onNumberOfColumnMetaDataTypesChanged(int value)
{
Q_D(voDelimitedTextImportWidget);
d->NumberHeaderRowsSpinBox->setValue(value);
if(value > 0)
{
d->HeaderRowOfInterestSpinBox->setRange(0, value-1);
}
else
{
d->HeaderRowOfInterestSpinBox->setMinimum(-1);
}
d->HeaderRowOfInterestSpinBox->setEnabled(value > 0);
}
// --------------------------------------------------------------------------
void voDelimitedTextImportWidget::onColumnMetaDataTypeOfInterestChanged(int value)
{
Q_D(voDelimitedTextImportWidget);
d->HeaderRowOfInterestSpinBox->setValue(value);
}
// --------------------------------------------------------------------------
void voDelimitedTextImportWidget::onNumberOfRowMetaDataTypesChanged(int value)
{
Q_D(voDelimitedTextImportWidget);
d->NumberHeaderColumnsSpinBox->setValue(value);
if(value > 0)
{
d->HeaderColumnOfInterestSpinBox->setRange(0, value-1);
}
else
{
d->HeaderColumnOfInterestSpinBox->setMinimum(-1);
}
d->HeaderColumnOfInterestSpinBox->setEnabled(value > 0);
}
// --------------------------------------------------------------------------
void voDelimitedTextImportWidget::onRowMetaDataTypeOfInterestChanged(int value)
{
Q_D(voDelimitedTextImportWidget);
d->HeaderColumnOfInterestSpinBox->setValue(value);
}
// --------------------------------------------------------------------------
void voDelimitedTextImportWidget::onDelimiterChanged(int delimiter)
{
Q_D(voDelimitedTextImportWidget);
if (delimiter == 'x')
{ // Special case triggered by OtherRadioButton
QString text = d->OtherLineEdit->text();
connect(d->OtherLineEdit, SIGNAL(textChanged(const QString&)),
this, SLOT(onOtherDelimiterLineEditChanged(const QString&)));
if (text.isEmpty())
{
return;
}
delimiter = text.at(0).toLatin1();
}
else
{
disconnect(d->OtherLineEdit, SIGNAL(textChanged(const QString&)),
this, SLOT(onOtherDelimiterLineEditChanged(const QString&)));
}
d->DelimitedTextPreviewModel->setFieldDelimiter(delimiter);
}
// --------------------------------------------------------------------------
void voDelimitedTextImportWidget::onOtherDelimiterLineEditChanged(const QString& text)
{
Q_D(voDelimitedTextImportWidget);
if (text.isEmpty())
{
return;
}
char delimiter = d->OtherLineEdit->text().at(0).toLatin1();
d->DelimitedTextPreviewModel->setFieldDelimiter(delimiter);
}
// --------------------------------------------------------------------------
void voDelimitedTextImportWidget::onStringDelimiterEnabled(bool value)
{
Q_D(voDelimitedTextImportWidget);
char character = 0;
if (value)
{
QString text = d->StringDelimiterLineEdit->text();
connect(d->StringDelimiterLineEdit, SIGNAL(textChanged(const QString&)),
this, SLOT(onStringDelimiterLineEditChanged(const QString&)));
if (text.isEmpty())
{
return;
}
character = text.at(0).toLatin1();
}
else
{
disconnect(d->StringDelimiterLineEdit, SIGNAL(textChanged(const QString&)),
this, SLOT(onStringDelimiterLineEditChanged(const QString&)));
}
d->DelimitedTextPreviewModel->setStringDelimiter(character);
}
// --------------------------------------------------------------------------
void voDelimitedTextImportWidget::onStringDelimiterLineEditChanged(const QString& text)
{
Q_D(voDelimitedTextImportWidget);
if (text.isEmpty())
{
return;
}
char character = d->StringDelimiterLineEdit->text().at(0).toLatin1();
d->DelimitedTextPreviewModel->setStringDelimiter(character);
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbGenericRSResampleImageFilter.h"
#include "otbBCOInterpolateImageFunction.h"
// Elevation handler
#include "otbWrapperElevationParametersHandler.h"
namespace otb
{
namespace Wrapper
{
class Superimpose : public Application
{
public:
/** Standard class typedefs. */
typedef Superimpose Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(Superimpose, Application);
typedef unsigned short int PixelType;
typedef otb::BCOInterpolateImageFunction<UInt16VectorImageType> InterpolatorType;
typedef otb::GenericRSResampleImageFilter<UInt16VectorImageType,
UInt16VectorImageType> ResamplerType;
private:
void DoInit()
{
SetName("Superimpose");
SetDescription("Using available image metadata, project one image onto another one");
// Documentation
SetDocName("Superimpose sensor");
SetDocLongDescription("This application performs the projection of an image into the geometry of another one.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso(" ");
AddDocTag(Tags::Geometry);
AddDocTag("Superimposition");
AddParameter(ParameterType_InputImage, "inr", "Reference input");
SetParameterDescription("inr","The input reference image.");
AddParameter(ParameterType_InputImage, "inm", "The image to reproject");
SetParameterDescription("inm","The image to reproject into the geometry of the reference input.");
// Elevation
ElevationParametersHandler::AddElevationParameters(this, "elev");
AddParameter(ParameterType_Float, "lms", "Spacing of the deformation field");
SetParameterDescription("lms","Generate a coarser deformation field with the given spacing");
SetDefaultParameterFloat("lms", 4.);
AddParameter(ParameterType_OutputImage, "out", "Output image");
SetParameterDescription("out","Output reprojected image.");
AddRAMParameter();
MandatoryOff("lms");
// Doc example parameter settings
SetDocExampleParameterValue("inr", "QB_Toulouse_Ortho_PAN.tif");
SetDocExampleParameterValue("inm", "QB_Toulouse_Ortho_XS.tif");
SetDocExampleParameterValue("out", "SuperimposedXS_to_PAN.tif");
}
void DoUpdateParameters()
{
// Nothing to do here : all parameters are independent
}
void DoExecute()
{
// Get the inputs
UInt16VectorImageType* refImage = GetParameterUInt16VectorImage("inr");
UInt16VectorImageType* movingImage = GetParameterUInt16VectorImage("inm");
// Resample filter
m_Resampler = ResamplerType::New();
m_Interpolator = InterpolatorType::New();
m_Resampler->SetInterpolator(m_Interpolator);
// Setup the DEM Handler
otb::Wrapper::ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(this,"elev");
// Set up output image informations
UInt16VectorImageType::SpacingType spacing = refImage->GetSpacing();
UInt16VectorImageType::IndexType start = refImage->GetLargestPossibleRegion().GetIndex();
UInt16VectorImageType::SizeType size = refImage->GetLargestPossibleRegion().GetSize();
UInt16VectorImageType::PointType origin = refImage->GetOrigin();
if(IsParameterEnabled("lms"))
{
float defScalarSpacing = GetParameterFloat("lms");
std::cout<<"Generating coarse deformation field (spacing="<<defScalarSpacing<<")"<<std::endl;
UInt16VectorImageType::SpacingType defSpacing;
defSpacing[0] = defScalarSpacing;
defSpacing[1] = defScalarSpacing;
m_Resampler->SetDeformationFieldSpacing(defSpacing);
}
UInt16VectorImageType::PixelType defaultValue;
itk::PixelBuilder<UInt16VectorImageType::PixelType>::Zero(defaultValue,
movingImage->GetNumberOfComponentsPerPixel());
m_Resampler->SetInput(movingImage);
m_Resampler->SetOutputOrigin(origin);
m_Resampler->SetOutputSpacing(spacing);
m_Resampler->SetOutputSize(size);
m_Resampler->SetOutputStartIndex(start);
m_Resampler->SetOutputKeywordList(refImage->GetImageKeywordlist());
m_Resampler->SetOutputProjectionRef(refImage->GetProjectionRef());
m_Resampler->SetEdgePaddingValue(defaultValue);
// Set the output image
SetParameterOutputImage("out", m_Resampler->GetOutput());
}
ResamplerType::Pointer m_Resampler;
InterpolatorType::Pointer m_Interpolator;
};
} // end namespace Wrapper
} // end namespace otb
OTB_APPLICATION_EXPORT(otb::Wrapper::Superimpose)
<commit_msg>BUG: Mantis 619: fix Superimpose with ortho images<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbGenericRSResampleImageFilter.h"
#include "otbBCOInterpolateImageFunction.h"
// Elevation handler
#include "otbWrapperElevationParametersHandler.h"
namespace otb
{
namespace Wrapper
{
class Superimpose : public Application
{
public:
/** Standard class typedefs. */
typedef Superimpose Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(Superimpose, Application);
typedef unsigned short int PixelType;
typedef otb::BCOInterpolateImageFunction<FloatVectorImageType> InterpolatorType;
typedef otb::GenericRSResampleImageFilter<FloatVectorImageType,
FloatVectorImageType> ResamplerType;
private:
void DoInit()
{
SetName("Superimpose");
SetDescription("Using available image metadata, project one image onto another one");
// Documentation
SetDocName("Superimpose sensor");
SetDocLongDescription("This application performs the projection of an image into the geometry of another one.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso(" ");
AddDocTag(Tags::Geometry);
AddDocTag("Superimposition");
AddParameter(ParameterType_InputImage, "inr", "Reference input");
SetParameterDescription("inr","The input reference image.");
AddParameter(ParameterType_InputImage, "inm", "The image to reproject");
SetParameterDescription("inm","The image to reproject into the geometry of the reference input.");
// Elevation
ElevationParametersHandler::AddElevationParameters(this, "elev");
AddParameter(ParameterType_Float, "lms", "Spacing of the deformation field");
SetParameterDescription("lms","Generate a coarser deformation field with the given spacing");
SetDefaultParameterFloat("lms", 4.);
AddParameter(ParameterType_OutputImage, "out", "Output image");
SetParameterDescription("out","Output reprojected image.");
AddRAMParameter();
MandatoryOff("lms");
// Doc example parameter settings
SetDocExampleParameterValue("inr", "QB_Toulouse_Ortho_PAN.tif");
SetDocExampleParameterValue("inm", "QB_Toulouse_Ortho_XS.tif");
SetDocExampleParameterValue("out", "SuperimposedXS_to_PAN.tif");
}
void DoUpdateParameters()
{
// Nothing to do here : all parameters are independent
}
void DoExecute()
{
// Get the inputs
FloatVectorImageType* refImage = GetParameterImage("inr");
FloatVectorImageType* movingImage = GetParameterImage("inm");
// Resample filter
m_Resampler = ResamplerType::New();
m_Interpolator = InterpolatorType::New();
m_Interpolator->SetRadius(2);
m_Resampler->SetInterpolator(m_Interpolator);
// Setup the DEM Handler
otb::Wrapper::ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(this,"elev");
// Set up output image informations
FloatVectorImageType::SpacingType spacing = refImage->GetSpacing();
FloatVectorImageType::IndexType start = refImage->GetLargestPossibleRegion().GetIndex();
FloatVectorImageType::SizeType size = refImage->GetLargestPossibleRegion().GetSize();
FloatVectorImageType::PointType origin = refImage->GetOrigin();
if(IsParameterEnabled("lms"))
{
float defScalarSpacing = vcl_abs(GetParameterFloat("lms"));
std::cout<<"Generating coarse deformation field (spacing="<<defScalarSpacing<<")"<<std::endl;
FloatVectorImageType::SpacingType defSpacing;
defSpacing[0] = defScalarSpacing;
defSpacing[1] = defScalarSpacing;
if (spacing[0]<0.0) defSpacing[0] *= -1.0;
if (spacing[1]<0.0) defSpacing[1] *= -1.0;
m_Resampler->SetDeformationFieldSpacing(defSpacing);
}
FloatVectorImageType::PixelType defaultValue;
itk::PixelBuilder<FloatVectorImageType::PixelType>::Zero(defaultValue,
movingImage->GetNumberOfComponentsPerPixel());
m_Resampler->SetInput(movingImage);
m_Resampler->SetInputKeywordList(movingImage->GetImageKeywordlist());
m_Resampler->SetInputProjectionRef(movingImage->GetProjectionRef());
m_Resampler->SetOutputOrigin(origin);
m_Resampler->SetOutputSpacing(spacing);
m_Resampler->SetOutputSize(size);
m_Resampler->SetOutputStartIndex(start);
m_Resampler->SetOutputKeywordList(refImage->GetImageKeywordlist());
m_Resampler->SetOutputProjectionRef(refImage->GetProjectionRef());
m_Resampler->SetEdgePaddingValue(defaultValue);
// Set the output image
SetParameterOutputImage("out", m_Resampler->GetOutput());
}
ResamplerType::Pointer m_Resampler;
InterpolatorType::Pointer m_Interpolator;
};
} // end namespace Wrapper
} // end namespace otb
OTB_APPLICATION_EXPORT(otb::Wrapper::Superimpose)
<|endoftext|>
|
<commit_before>#include <string>
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <assert.h>
#include <unistd.h>
#include "config.h"
#include "file_utils.hpp"
#include "NeighborJoining.hpp"
#include <ctime>
#include <time.h>
#include "log_utils.hpp"
#include "fnj_gengetopt.h"
#include "DataInputStream.hpp"
#include "DataOutputStream.hpp"
#include "TreeTextOutputStream.hpp"
#include "XmlOutputStream.hpp"
#include "Extrainfos.hpp"
#include "fileFormatSchema.hpp"
#include "PhylipDmInputStream.hpp"
#include "BinaryInputStream.hpp"
#ifdef WITH_LIBXML
#include "XmlInputStream.hpp"
#endif // WITH_LIBXML
using namespace std;
//
// Builds trees using the supplied distance methods.
// Each created tree is added to the tree2count map.
//
template<class T> void buildTrees(T &dm, tree2int_map &tree2count, std::vector<NJ_method> &methods, str2int_hashmap &name2id) {
SequenceTree tree;
for(size_t i=0; i<methods.size(); i++){
computeNJTree(dm,tree,methods[i]);
tree.makeCanonical(name2id);
tree2int_map::iterator iter = tree2count.find(tree);
if(iter!=tree2count.end())
iter->second++;
else
tree2count[tree] = 1;
}
}
int main (int argc, char **argv) {
if(isatty(STDIN_FILENO) && argc==1) {
cout<<"No input data or parameters. Use -h,--help for more information"<<endl;
exit(EXIT_FAILURE);
}
gengetopt_args_info args_info;
TRY_EXCEPTION();
if (cmdline_parser (argc, argv, &args_info) != 0)
exit(EXIT_FAILURE);
#ifndef WITH_LIBXML
if ( args_info.input_format_arg == input_format_arg_xml ) {
cerr << "The software was built with WITH_LIBXML=OFF. Please rebuild it if you want XML functionality." << endl;
exit(EXIT_FAILURE);
}
#endif // WITH_LIBXML
if ( args_info.print_relaxng_input_given && args_info.print_relaxng_output_given ) {
cerr << "error: --print-relaxng-input and --print-relaxng-output can not be used at the same time" << endl;
exit(EXIT_FAILURE);
}
if ( args_info.print_relaxng_input_given ) {
cout << fastphylo_distance_matrix_xml_relaxngstr << std::endl;
exit(EXIT_SUCCESS);
};
if ( args_info.print_relaxng_output_given ) {
cout << fastphylo_tree_count_xml_relaxngstr << std::endl;
exit(EXIT_SUCCESS);
};
//----------------------------------------------
// DISTANCE METHODS
std::vector<NJ_method> methods;
if( args_info.number_of_runs_given && args_info.input_format_arg == input_format_arg_xml ) {
cerr << "error: --number-of-runs can not be used together with input format xml." << endl;
exit(EXIT_FAILURE);
}
switch ( args_info.method_arg ) {
case method_arg_NJ:
methods.push_back(NJ);
break;
case method_arg_FNJ:
methods.push_back(FNJ);
break;
case method_arg_BIONJ:
methods.push_back(BIONJ);
break;
default:
cerr << "error: method chosen not available" << endl;
exit(EXIT_FAILURE);
}
bool printCounts = args_info.print_counts_flag;
try {
char * inputfilename = NULL;
char * outputfilename = NULL;
DataInputStream *istream;
DataOutputStream *ostream;
switch( args_info.inputs_num ) {
case 0:
break; /* inputfilename will be null and indicate stdin as input */
case 1:
inputfilename = args_info.inputs[0];
break;
default: cerr << "Error: you can at most specify one input filename" << endl;
exit(EXIT_FAILURE);
}
if( args_info.outfile_given )
outputfilename = args_info.outfile_arg;
switch ( args_info.input_format_arg ) {
case input_format_arg_phylip:
istream = new PhylipDmInputStream(inputfilename);
break;
case input_format_arg_binary: istream = new BinaryInputStream(inputfilename);
break;
#ifdef WITH_LIBXML
case input_format_arg_xml: istream = new XmlInputStream(inputfilename);
break;
#endif // WITH_LIBXML
default:
exit(EXIT_FAILURE);
}
switch (args_info.output_format_arg) {
case output_format_arg_newick:
ostream = new TreeTextOutputStream(outputfilename);
break;
case output_format_arg_xml:
ostream = new XmlOutputStream(outputfilename);
break;
default:
exit(EXIT_FAILURE);
}
//printf("%d\n", args_info.input_format_arg);
// THE DATA WE WILL PROCESS
vector<Sequence> seqs;
vector<std::string> names;
vector<DNA_b128_String> b128seqs;
Extrainfos extrainfos;
bool latestReadSuccessful = true;
vector<string> speciesnames;
readstatus status;
int run = 0;
status = END_OF_RUN;
while (status == END_OF_RUN && (args_info.input_format_arg == input_format_arg_xml || run<args_info.number_of_runs_arg)) {
string runId("");
run++;
tree2int_map tree2count((size_t)(args_info.bootstraps_arg * 1.3));
str2int_hashmap name2id;
if (args_info.input_format_arg==input_format_arg_binary) {
StrFloMatrix dm;
for (int runNo=1; (status = istream->readDM(dm, names, runId, extrainfos))==DM_READ; runNo++) {
if (args_info.analyze_run_number_given) {
if (runNo<args_info.analyze_run_number_arg)
continue;
if (runNo>args_info.analyze_run_number_arg) {
status=END_OF_RUN;
break;
}
}
for(size_t namei=0; namei<dm.getSize(); namei++)
name2id[dm.getIdentifier(namei)] = namei;
buildTrees(dm, tree2count, methods,name2id);
}
}
else {
StrDblMatrix dm;
for (int runNo=1; (status = istream->readDM(dm, names, runId, extrainfos))==DM_READ; runNo++) {
if (args_info.analyze_run_number_given) {
if (runNo<args_info.analyze_run_number_arg)
continue;
if (runNo>args_info.analyze_run_number_arg) {
status=END_OF_RUN;
break;
}
}
for(size_t namei=0; namei<dm.getSize(); namei++)
name2id[dm.getIdentifier(namei)] = namei;
buildTrees(dm, tree2count, methods,name2id);
}
}
if (status==END_OF_RUN)
ostream->print(tree2count,printCounts, runId, names, extrainfos);
if (args_info.analyze_run_number_given)
break;
}//end run loop
delete ostream;
delete istream;
}
catch(...){
throw;
}
CATCH_EXCEPTION();
cmdline_parser_free(&args_info);
return 0;
}
<commit_msg>Spiteful indent fix<commit_after>#include <string>
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <assert.h>
#include <unistd.h>
#include "config.h"
#include "file_utils.hpp"
#include "NeighborJoining.hpp"
#include <ctime>
#include <time.h>
#include "log_utils.hpp"
#include "fnj_gengetopt.h"
#include "DataInputStream.hpp"
#include "DataOutputStream.hpp"
#include "TreeTextOutputStream.hpp"
#include "XmlOutputStream.hpp"
#include "Extrainfos.hpp"
#include "fileFormatSchema.hpp"
#include "PhylipDmInputStream.hpp"
#include "BinaryInputStream.hpp"
#ifdef WITH_LIBXML
#include "XmlInputStream.hpp"
#endif // WITH_LIBXML
using namespace std;
//
// Builds trees using the supplied distance methods.
// Each created tree is added to the tree2count map.
//
template<class T> void buildTrees(T &dm, tree2int_map &tree2count, std::vector<NJ_method> &methods, str2int_hashmap &name2id) {
SequenceTree tree;
for(size_t i=0; i<methods.size(); i++){
computeNJTree(dm,tree,methods[i]);
tree.makeCanonical(name2id);
tree2int_map::iterator iter = tree2count.find(tree);
if(iter!=tree2count.end())
iter->second++;
else
tree2count[tree] = 1;
}
}
int main (int argc, char **argv) {
if(isatty(STDIN_FILENO) && argc==1) {
cout<<"No input data or parameters. Use -h,--help for more information"<<endl;
exit(EXIT_FAILURE);
}
gengetopt_args_info args_info;
TRY_EXCEPTION();
if (cmdline_parser (argc, argv, &args_info) != 0)
exit(EXIT_FAILURE);
#ifndef WITH_LIBXML
if ( args_info.input_format_arg == input_format_arg_xml ) {
cerr << "The software was built with WITH_LIBXML=OFF. Please rebuild it if you want XML functionality." << endl;
exit(EXIT_FAILURE);
}
#endif // WITH_LIBXML
if ( args_info.print_relaxng_input_given && args_info.print_relaxng_output_given ) {
cerr << "error: --print-relaxng-input and --print-relaxng-output can not be used at the same time" << endl;
exit(EXIT_FAILURE);
}
if ( args_info.print_relaxng_input_given ) {
cout << fastphylo_distance_matrix_xml_relaxngstr << std::endl;
exit(EXIT_SUCCESS);
};
if ( args_info.print_relaxng_output_given ) {
cout << fastphylo_tree_count_xml_relaxngstr << std::endl;
exit(EXIT_SUCCESS);
};
//----------------------------------------------
// DISTANCE METHODS
std::vector<NJ_method> methods;
if( args_info.number_of_runs_given && args_info.input_format_arg == input_format_arg_xml ) {
cerr << "error: --number-of-runs can not be used together with input format xml." << endl;
exit(EXIT_FAILURE);
}
switch ( args_info.method_arg ) {
case method_arg_NJ:
methods.push_back(NJ);
break;
case method_arg_FNJ:
methods.push_back(FNJ);
break;
case method_arg_BIONJ:
methods.push_back(BIONJ);
break;
default:
cerr << "error: method chosen not available" << endl;
exit(EXIT_FAILURE);
}
bool printCounts = args_info.print_counts_flag;
try {
char * inputfilename = NULL;
char * outputfilename = NULL;
DataInputStream *istream;
DataOutputStream *ostream;
switch( args_info.inputs_num ) {
case 0:
break; /* inputfilename will be null and indicate stdin as input */
case 1:
inputfilename = args_info.inputs[0];
break;
default: cerr << "Error: you can at most specify one input filename" << endl;
exit(EXIT_FAILURE);
}
if( args_info.outfile_given )
outputfilename = args_info.outfile_arg;
switch ( args_info.input_format_arg ) {
case input_format_arg_phylip:
istream = new PhylipDmInputStream(inputfilename);
break;
case input_format_arg_binary: istream = new BinaryInputStream(inputfilename);
break;
#ifdef WITH_LIBXML
case input_format_arg_xml: istream = new XmlInputStream(inputfilename);
break;
#endif // WITH_LIBXML
default:
exit(EXIT_FAILURE);
}
switch (args_info.output_format_arg) {
case output_format_arg_newick:
ostream = new TreeTextOutputStream(outputfilename);
break;
case output_format_arg_xml:
ostream = new XmlOutputStream(outputfilename);
break;
default:
exit(EXIT_FAILURE);
}
//printf("%d\n", args_info.input_format_arg);
// THE DATA WE WILL PROCESS
vector<Sequence> seqs;
vector<std::string> names;
vector<DNA_b128_String> b128seqs;
Extrainfos extrainfos;
bool latestReadSuccessful = true;
vector<string> speciesnames;
readstatus status;
int run = 0;
status = END_OF_RUN;
while (status == END_OF_RUN && (args_info.input_format_arg == input_format_arg_xml || run<args_info.number_of_runs_arg)) {
string runId("");
run++;
tree2int_map tree2count((size_t)(args_info.bootstraps_arg * 1.3));
str2int_hashmap name2id;
if (args_info.input_format_arg==input_format_arg_binary) {
StrFloMatrix dm;
for (int runNo=1; (status = istream->readDM(dm, names, runId, extrainfos))==DM_READ; runNo++) {
if (args_info.analyze_run_number_given) {
if (runNo<args_info.analyze_run_number_arg)
continue;
if (runNo>args_info.analyze_run_number_arg) {
status=END_OF_RUN;
break;
}
}
for(size_t namei=0; namei<dm.getSize(); namei++)
name2id[dm.getIdentifier(namei)] = namei;
buildTrees(dm, tree2count, methods,name2id);
}
}
else {
StrDblMatrix dm;
for (int runNo=1; (status = istream->readDM(dm, names, runId, extrainfos))==DM_READ; runNo++) {
if (args_info.analyze_run_number_given) {
if (runNo<args_info.analyze_run_number_arg)
continue;
if (runNo>args_info.analyze_run_number_arg) {
status=END_OF_RUN;
break;
}
}
for(size_t namei=0; namei<dm.getSize(); namei++) {
name2id[dm.getIdentifier(namei)] = namei;
}
buildTrees(dm, tree2count, methods,name2id);
}
}
if (status==END_OF_RUN)
ostream->print(tree2count,printCounts, runId, names, extrainfos);
if (args_info.analyze_run_number_given)
break;
}//end run loop
delete ostream;
delete istream;
}
catch(...){
throw;
}
CATCH_EXCEPTION();
cmdline_parser_free(&args_info);
return 0;
}
<|endoftext|>
|
<commit_before>/*
* ExcaliburFrameDecoder.cpp
*
* Created on: Jan 16th, 2017
* Author: Tim Nicholls, STFC Application Engineering Group
*/
#include "ExcaliburFrameDecoder.h"
#include "gettime.h"
#include <iostream>
#include <iomanip>
#include <sstream>
#include <arpa/inet.h>
using namespace FrameReceiver;
ExcaliburFrameDecoder::ExcaliburFrameDecoder(LoggerPtr& logger,
bool enable_packet_logging, unsigned int frame_timeout_ms) :
FrameDecoder(logger, enable_packet_logging),
current_frame_seen_(-1),
current_frame_buffer_id_(-1),
current_frame_buffer_(0),
current_frame_header_(0),
dropping_frame_data_(false),
frame_timeout_ms_(frame_timeout_ms),
frames_timedout_(0)
{
current_packet_header_.reset(new uint8_t[sizeof(Excalibur::PacketHeader)]);
dropped_frame_buffer_.reset(new uint8_t[Excalibur::total_frame_size]);
if (enable_packet_logging_) {
LOG4CXX_INFO(packet_logger_, "PktHdr: SourceAddress");
LOG4CXX_INFO(packet_logger_, "PktHdr: | SourcePort");
LOG4CXX_INFO(packet_logger_, "PktHdr: | | DestinationPort");
LOG4CXX_INFO(packet_logger_, "PktHdr: | | | SubframeCounter [4 Bytes]");
LOG4CXX_INFO(packet_logger_, "PktHdr: | | | | PacketCounter&Flags [4 Bytes]");
LOG4CXX_INFO(packet_logger_, "PktHdr: | | | | |");
LOG4CXX_INFO(packet_logger_, "PktHdr: |-------------- |---- |---- |---------- |----------");
}
}
ExcaliburFrameDecoder::~ExcaliburFrameDecoder()
{
}
const size_t ExcaliburFrameDecoder::get_frame_buffer_size(void) const
{
return Excalibur::total_frame_size;
}
const size_t ExcaliburFrameDecoder::get_frame_header_size(void) const
{
return sizeof(Excalibur::FrameHeader);
}
const size_t ExcaliburFrameDecoder::get_packet_header_size(void) const
{
return sizeof(Excalibur::PacketHeader);
}
void* ExcaliburFrameDecoder::get_packet_header_buffer(void)
{
return current_packet_header_.get();
}
void ExcaliburFrameDecoder::process_packet_header(size_t bytes_received, int port, struct sockaddr_in* from_addr)
{
// Dump raw header if packet logging enabled
if (enable_packet_logging_)
{
std::stringstream ss;
uint8_t* hdr_ptr = reinterpret_cast<uint8_t*>(current_packet_header_.get());
ss << "PktHdr: " << std::setw(15) << std::left << inet_ntoa(from_addr->sin_addr) << std::right << " "
<< std::setw(5) << ntohs(from_addr->sin_port) << " "
<< std::setw(5) << port << std::hex;
for (unsigned int hdr_byte = 0; hdr_byte < sizeof(Excalibur::PacketHeader); hdr_byte++)
{
if (hdr_byte % 8 == 0) {
ss << " ";
}
ss << std::setw(2) << std::setfill('0') << (unsigned int)*hdr_ptr << " ";
hdr_ptr++;
}
ss << std::dec;
LOG4CXX_INFO(packet_logger_, ss.str());
}
uint32_t subframe_counter = get_subframe_counter();
uint32_t packet_number = get_packet_number();
bool start_of_frame_marker = get_start_of_frame_marker();
bool end_of_frame_marker = get_end_of_frame_marker();
uint32_t subframe_idx = subframe_counter % 2;
uint32_t frame = subframe_counter / 2;
LOG4CXX_DEBUG_LEVEL(3, logger_, "Got packet header:"
<< " packet: " << packet_number << " subframe ctr: "<< subframe_counter << " idx:" << subframe_idx
<< " SOF: " << (int)start_of_frame_marker << " EOF: " << (int)end_of_frame_marker
);
if (frame != current_frame_seen_)
{
current_frame_seen_ = frame;
if (frame_buffer_map_.count(current_frame_seen_) == 0)
{
if (empty_buffer_queue_.empty())
{
current_frame_buffer_ = dropped_frame_buffer_.get();
if (!dropping_frame_data_)
{
LOG4CXX_ERROR(logger_, "First packet from frame " << current_frame_seen_ << " detected but no free buffers available. Dropping packet data for this frame");
dropping_frame_data_ = true;
}
}
else
{
current_frame_buffer_id_ = empty_buffer_queue_.front();
empty_buffer_queue_.pop();
frame_buffer_map_[current_frame_seen_] = current_frame_buffer_id_;
current_frame_buffer_ = buffer_manager_->get_buffer_address(current_frame_buffer_id_);
if (!dropping_frame_data_)
{
LOG4CXX_DEBUG_LEVEL(2, logger_, "First packet from frame " << current_frame_seen_ << " detected, allocating frame buffer ID " << current_frame_buffer_id_);
}
else
{
dropping_frame_data_ = false;
LOG4CXX_DEBUG_LEVEL(2, logger_, "Free buffer now available for frame " << current_frame_seen_ << ", allocating frame buffer ID " << current_frame_buffer_id_);
}
}
// Initialise frame header
current_frame_header_ = reinterpret_cast<Excalibur::FrameHeader*>(current_frame_buffer_);
current_frame_header_->frame_number = current_frame_seen_;
current_frame_header_->frame_state = FrameDecoder::FrameReceiveStateIncomplete;
current_frame_header_->packets_received = 0;
current_frame_header_->sof_marker_count = 0;
current_frame_header_->eof_marker_count = 0;
memset(current_frame_header_->packet_state, 0, Excalibur::num_frame_packets);
gettime(reinterpret_cast<struct timespec*>(&(current_frame_header_->frame_start_time)));
}
else
{
current_frame_buffer_id_ = frame_buffer_map_[current_frame_seen_];
current_frame_buffer_ = buffer_manager_->get_buffer_address(current_frame_buffer_id_);
current_frame_header_ = reinterpret_cast<Excalibur::FrameHeader*>(current_frame_buffer_);
}
}
// If SOF or EOF markers seen in packet header, increment appropriate field in frame header
if (start_of_frame_marker) {
(current_frame_header_->sof_marker_count)++;
}
if (end_of_frame_marker) {
(current_frame_header_->eof_marker_count)++;
}
// Update packet_number state map in frame header
current_frame_header_->packet_state[subframe_idx][packet_number] = 1;
}
void* ExcaliburFrameDecoder::get_next_payload_buffer(void) const
{
uint8_t* next_receive_location =
reinterpret_cast<uint8_t*>(current_frame_buffer_) +
get_frame_header_size() +
(Excalibur::subframe_size * (get_subframe_counter() % 2)) +
(Excalibur::primary_packet_size * get_packet_number());
return reinterpret_cast<void*>(next_receive_location);
}
size_t ExcaliburFrameDecoder::get_next_payload_size(void) const
{
size_t next_receive_size = 0;
if (get_packet_number() < Excalibur::num_primary_packets)
{
next_receive_size = Excalibur::primary_packet_size;
}
else
{
next_receive_size = Excalibur::tail_packet_size;
}
return next_receive_size;
}
FrameDecoder::FrameReceiveState ExcaliburFrameDecoder::process_packet(size_t bytes_received)
{
FrameDecoder::FrameReceiveState frame_state = FrameDecoder::FrameReceiveStateIncomplete;
// If this packet is the last in subframe (i.e. has on EOF marker in the header), extract the frame
// number (which counts from 1) from the subframe trailer, update and/or validate in the frame buffer
// header appropriately.
if (get_end_of_frame_marker()) {
size_t payload_bytes_received = bytes_received - sizeof(Excalibur::PacketHeader);
Excalibur::SubframeTrailer* trailer = reinterpret_cast<Excalibur::SubframeTrailer*>(
(uint8_t*)get_next_payload_buffer() + payload_bytes_received - sizeof(Excalibur::SubframeTrailer));
uint32_t frame_number = static_cast<uint32_t>((trailer->frame_number & 0xFFFFFFFF) - 1);
LOG4CXX_DEBUG_LEVEL(3, logger_, "Subframe EOF trailer has frame number = " << frame_number);
uint32_t subframe_idx = get_subframe_counter() % 2;
if (subframe_idx == 0) {
current_frame_header_->frame_number = frame_number;
} else {
if (frame_number != current_frame_header_->frame_number) {
LOG4CXX_WARN(logger_, "Subframe EOF trailer frame number mismatch for frame " << current_frame_seen_
<< ": got " << frame_number << ", expected " << current_frame_header_->frame_number
);
}
}
}
current_frame_header_->packets_received++;
if (current_frame_header_->packets_received == Excalibur::num_frame_packets)
{
// Check that the appropriate number of SOF and EOF markers (one each per subframe) have
// been seen, otherwise log a warning
if ((current_frame_header_->sof_marker_count != Excalibur::num_subframes) ||
(current_frame_header_->eof_marker_count != Excalibur::num_subframes))
{
LOG4CXX_WARN(logger_, "Incorrect number of SOF (" << current_frame_header_->sof_marker_count
<< ") or EOF (" << current_frame_header_->eof_marker_count
<< "markers seen on completed frame " << current_frame_seen_
);
}
// Set frame state accordingly
frame_state = FrameDecoder::FrameReceiveStateComplete;
// Complete frame header
current_frame_header_->frame_state = frame_state;
if (!dropping_frame_data_)
{
// Erase frame from buffer map
frame_buffer_map_.erase(current_frame_seen_);
// Notify main thread that frame is ready
ready_callback_(current_frame_buffer_id_, current_frame_seen_);
// Reset current frame seen ID so that if next frame has same number (e.g. repeated
// sends of single frame 0), it is detected properly
current_frame_seen_ = -1;
}
}
return frame_state;
}
void ExcaliburFrameDecoder::monitor_buffers(void)
{
int frames_timedout = 0;
struct timespec current_time;
gettime(¤t_time);
// Loop over frame buffers currently in map and check their state
std::map<uint32_t, int>::iterator buffer_map_iter = frame_buffer_map_.begin();
while (buffer_map_iter != frame_buffer_map_.end())
{
uint32_t frame_num = buffer_map_iter->first;
int buffer_id = buffer_map_iter->second;
void* buffer_addr = buffer_manager_->get_buffer_address(buffer_id);
Excalibur::FrameHeader* frame_header = reinterpret_cast<Excalibur::FrameHeader*>(buffer_addr);
if (elapsed_ms(frame_header->frame_start_time, current_time) > frame_timeout_ms_)
{
LOG4CXX_DEBUG_LEVEL(1, logger_, "Frame " << frame_num << " in buffer " << buffer_id
<< " addr 0x" << std::hex << buffer_addr << std::dec
<< " timed out with " << frame_header->packets_received << " packets received");
frame_header->frame_state = FrameReceiveStateTimedout;
ready_callback_(buffer_id, frame_num);
frames_timedout++;
frame_buffer_map_.erase(buffer_map_iter++);
}
else
{
buffer_map_iter++;
}
}
if (frames_timedout)
{
LOG4CXX_WARN(logger_, "Released " << frames_timedout << " timed out incomplete frames");
}
frames_timedout_ += frames_timedout;
LOG4CXX_DEBUG_LEVEL(2, logger_, get_num_mapped_buffers() << " frame buffers in use, "
<< get_num_empty_buffers() << " empty buffers available, "
<< frames_timedout_ << " incomplete frames timed out");
}
uint32_t ExcaliburFrameDecoder::get_subframe_counter(void) const
{
return reinterpret_cast<Excalibur::PacketHeader*>(current_packet_header_.get())->subframe_counter;
}
uint32_t ExcaliburFrameDecoder::get_packet_number(void) const
{
return reinterpret_cast<Excalibur::PacketHeader*>(current_packet_header_.get())->packet_number_flags & Excalibur::packet_number_mask;
}
bool ExcaliburFrameDecoder::get_start_of_frame_marker(void) const
{
uint32_t packet_number_flags = reinterpret_cast<Excalibur::PacketHeader*>(current_packet_header_.get())->packet_number_flags;
return ((packet_number_flags & Excalibur::start_of_frame_mask) != 0);
}
bool ExcaliburFrameDecoder::get_end_of_frame_marker(void) const
{
uint32_t packet_number_flags = reinterpret_cast<Excalibur::PacketHeader*>(current_packet_header_.get())->packet_number_flags;
return ((packet_number_flags & Excalibur::end_of_frame_mask) != 0);
}
unsigned int ExcaliburFrameDecoder::elapsed_ms(struct timespec& start, struct timespec& end)
{
double start_ns = ((double)start.tv_sec * 1000000000) + start.tv_nsec;
double end_ns = ((double) end.tv_sec * 1000000000) + end.tv_nsec;
return (unsigned int)((end_ns - start_ns)/1000000);
}
<commit_msg>ExcaliburFrameDecoder now uses 'real' frame number in notifcations.<commit_after>/*
* ExcaliburFrameDecoder.cpp
*
* Created on: Jan 16th, 2017
* Author: Tim Nicholls, STFC Application Engineering Group
*/
#include "ExcaliburFrameDecoder.h"
#include "gettime.h"
#include <iostream>
#include <iomanip>
#include <sstream>
#include <arpa/inet.h>
using namespace FrameReceiver;
ExcaliburFrameDecoder::ExcaliburFrameDecoder(LoggerPtr& logger,
bool enable_packet_logging, unsigned int frame_timeout_ms) :
FrameDecoder(logger, enable_packet_logging),
current_frame_seen_(-1),
current_frame_buffer_id_(-1),
current_frame_buffer_(0),
current_frame_header_(0),
dropping_frame_data_(false),
frame_timeout_ms_(frame_timeout_ms),
frames_timedout_(0)
{
current_packet_header_.reset(new uint8_t[sizeof(Excalibur::PacketHeader)]);
dropped_frame_buffer_.reset(new uint8_t[Excalibur::total_frame_size]);
if (enable_packet_logging_) {
LOG4CXX_INFO(packet_logger_, "PktHdr: SourceAddress");
LOG4CXX_INFO(packet_logger_, "PktHdr: | SourcePort");
LOG4CXX_INFO(packet_logger_, "PktHdr: | | DestinationPort");
LOG4CXX_INFO(packet_logger_, "PktHdr: | | | SubframeCounter [4 Bytes]");
LOG4CXX_INFO(packet_logger_, "PktHdr: | | | | PacketCounter&Flags [4 Bytes]");
LOG4CXX_INFO(packet_logger_, "PktHdr: | | | | |");
LOG4CXX_INFO(packet_logger_, "PktHdr: |-------------- |---- |---- |---------- |----------");
}
}
ExcaliburFrameDecoder::~ExcaliburFrameDecoder()
{
}
const size_t ExcaliburFrameDecoder::get_frame_buffer_size(void) const
{
return Excalibur::total_frame_size;
}
const size_t ExcaliburFrameDecoder::get_frame_header_size(void) const
{
return sizeof(Excalibur::FrameHeader);
}
const size_t ExcaliburFrameDecoder::get_packet_header_size(void) const
{
return sizeof(Excalibur::PacketHeader);
}
void* ExcaliburFrameDecoder::get_packet_header_buffer(void)
{
return current_packet_header_.get();
}
void ExcaliburFrameDecoder::process_packet_header(size_t bytes_received, int port, struct sockaddr_in* from_addr)
{
// Dump raw header if packet logging enabled
if (enable_packet_logging_)
{
std::stringstream ss;
uint8_t* hdr_ptr = reinterpret_cast<uint8_t*>(current_packet_header_.get());
ss << "PktHdr: " << std::setw(15) << std::left << inet_ntoa(from_addr->sin_addr) << std::right << " "
<< std::setw(5) << ntohs(from_addr->sin_port) << " "
<< std::setw(5) << port << std::hex;
for (unsigned int hdr_byte = 0; hdr_byte < sizeof(Excalibur::PacketHeader); hdr_byte++)
{
if (hdr_byte % 8 == 0) {
ss << " ";
}
ss << std::setw(2) << std::setfill('0') << (unsigned int)*hdr_ptr << " ";
hdr_ptr++;
}
ss << std::dec;
LOG4CXX_INFO(packet_logger_, ss.str());
}
uint32_t subframe_counter = get_subframe_counter();
uint32_t packet_number = get_packet_number();
bool start_of_frame_marker = get_start_of_frame_marker();
bool end_of_frame_marker = get_end_of_frame_marker();
uint32_t subframe_idx = subframe_counter % 2;
uint32_t frame = subframe_counter / 2;
LOG4CXX_DEBUG_LEVEL(3, logger_, "Got packet header:"
<< " packet: " << packet_number << " subframe ctr: "<< subframe_counter << " idx:" << subframe_idx
<< " SOF: " << (int)start_of_frame_marker << " EOF: " << (int)end_of_frame_marker
);
if (frame != current_frame_seen_)
{
current_frame_seen_ = frame;
if (frame_buffer_map_.count(current_frame_seen_) == 0)
{
if (empty_buffer_queue_.empty())
{
current_frame_buffer_ = dropped_frame_buffer_.get();
if (!dropping_frame_data_)
{
LOG4CXX_ERROR(logger_, "First packet from frame " << current_frame_seen_ << " detected but no free buffers available. Dropping packet data for this frame");
dropping_frame_data_ = true;
}
}
else
{
current_frame_buffer_id_ = empty_buffer_queue_.front();
empty_buffer_queue_.pop();
frame_buffer_map_[current_frame_seen_] = current_frame_buffer_id_;
current_frame_buffer_ = buffer_manager_->get_buffer_address(current_frame_buffer_id_);
if (!dropping_frame_data_)
{
LOG4CXX_DEBUG_LEVEL(2, logger_, "First packet from frame " << current_frame_seen_ << " detected, allocating frame buffer ID " << current_frame_buffer_id_);
}
else
{
dropping_frame_data_ = false;
LOG4CXX_DEBUG_LEVEL(2, logger_, "Free buffer now available for frame " << current_frame_seen_ << ", allocating frame buffer ID " << current_frame_buffer_id_);
}
}
// Initialise frame header
current_frame_header_ = reinterpret_cast<Excalibur::FrameHeader*>(current_frame_buffer_);
current_frame_header_->frame_number = current_frame_seen_;
current_frame_header_->frame_state = FrameDecoder::FrameReceiveStateIncomplete;
current_frame_header_->packets_received = 0;
current_frame_header_->sof_marker_count = 0;
current_frame_header_->eof_marker_count = 0;
memset(current_frame_header_->packet_state, 0, Excalibur::num_frame_packets);
gettime(reinterpret_cast<struct timespec*>(&(current_frame_header_->frame_start_time)));
}
else
{
current_frame_buffer_id_ = frame_buffer_map_[current_frame_seen_];
current_frame_buffer_ = buffer_manager_->get_buffer_address(current_frame_buffer_id_);
current_frame_header_ = reinterpret_cast<Excalibur::FrameHeader*>(current_frame_buffer_);
}
}
// If SOF or EOF markers seen in packet header, increment appropriate field in frame header
if (start_of_frame_marker) {
(current_frame_header_->sof_marker_count)++;
}
if (end_of_frame_marker) {
(current_frame_header_->eof_marker_count)++;
}
// Update packet_number state map in frame header
current_frame_header_->packet_state[subframe_idx][packet_number] = 1;
}
void* ExcaliburFrameDecoder::get_next_payload_buffer(void) const
{
uint8_t* next_receive_location =
reinterpret_cast<uint8_t*>(current_frame_buffer_) +
get_frame_header_size() +
(Excalibur::subframe_size * (get_subframe_counter() % 2)) +
(Excalibur::primary_packet_size * get_packet_number());
return reinterpret_cast<void*>(next_receive_location);
}
size_t ExcaliburFrameDecoder::get_next_payload_size(void) const
{
size_t next_receive_size = 0;
if (get_packet_number() < Excalibur::num_primary_packets)
{
next_receive_size = Excalibur::primary_packet_size;
}
else
{
next_receive_size = Excalibur::tail_packet_size;
}
return next_receive_size;
}
FrameDecoder::FrameReceiveState ExcaliburFrameDecoder::process_packet(size_t bytes_received)
{
FrameDecoder::FrameReceiveState frame_state = FrameDecoder::FrameReceiveStateIncomplete;
// If this packet is the last in subframe (i.e. has on EOF marker in the header), extract the frame
// number (which counts from 1) from the subframe trailer, update and/or validate in the frame buffer
// header appropriately.
if (get_end_of_frame_marker()) {
size_t payload_bytes_received = bytes_received - sizeof(Excalibur::PacketHeader);
Excalibur::SubframeTrailer* trailer = reinterpret_cast<Excalibur::SubframeTrailer*>(
(uint8_t*)get_next_payload_buffer() + payload_bytes_received - sizeof(Excalibur::SubframeTrailer));
uint32_t frame_number = static_cast<uint32_t>((trailer->frame_number & 0xFFFFFFFF) - 1);
LOG4CXX_DEBUG_LEVEL(3, logger_, "Subframe EOF trailer has frame number = " << frame_number);
uint32_t subframe_idx = get_subframe_counter() % 2;
if (subframe_idx == 0) {
current_frame_header_->frame_number = frame_number;
} else {
if (frame_number != current_frame_header_->frame_number) {
LOG4CXX_WARN(logger_, "Subframe EOF trailer frame number mismatch for frame " << current_frame_seen_
<< ": got " << frame_number << ", expected " << current_frame_header_->frame_number
);
}
}
}
current_frame_header_->packets_received++;
if (current_frame_header_->packets_received == Excalibur::num_frame_packets)
{
// Check that the appropriate number of SOF and EOF markers (one each per subframe) have
// been seen, otherwise log a warning
if ((current_frame_header_->sof_marker_count != Excalibur::num_subframes) ||
(current_frame_header_->eof_marker_count != Excalibur::num_subframes))
{
LOG4CXX_WARN(logger_, "Incorrect number of SOF (" << current_frame_header_->sof_marker_count
<< ") or EOF (" << current_frame_header_->eof_marker_count
<< "markers seen on completed frame " << current_frame_seen_
);
}
// Set frame state accordingly
frame_state = FrameDecoder::FrameReceiveStateComplete;
// Complete frame header
current_frame_header_->frame_state = frame_state;
if (!dropping_frame_data_)
{
// Erase frame from buffer map
frame_buffer_map_.erase(current_frame_seen_);
// Notify main thread that frame is ready
ready_callback_(current_frame_buffer_id_, current_frame_header_->frame_number); //current_frame_seen_);
// Reset current frame seen ID so that if next frame has same number (e.g. repeated
// sends of single frame 0), it is detected properly
current_frame_seen_ = -1;
}
}
return frame_state;
}
void ExcaliburFrameDecoder::monitor_buffers(void)
{
int frames_timedout = 0;
struct timespec current_time;
gettime(¤t_time);
// Loop over frame buffers currently in map and check their state
std::map<uint32_t, int>::iterator buffer_map_iter = frame_buffer_map_.begin();
while (buffer_map_iter != frame_buffer_map_.end())
{
uint32_t frame_num = buffer_map_iter->first;
int buffer_id = buffer_map_iter->second;
void* buffer_addr = buffer_manager_->get_buffer_address(buffer_id);
Excalibur::FrameHeader* frame_header = reinterpret_cast<Excalibur::FrameHeader*>(buffer_addr);
if (elapsed_ms(frame_header->frame_start_time, current_time) > frame_timeout_ms_)
{
LOG4CXX_DEBUG_LEVEL(1, logger_, "Frame " << frame_num << " in buffer " << buffer_id
<< " addr 0x" << std::hex << buffer_addr << std::dec
<< " timed out with " << frame_header->packets_received << " packets received");
frame_header->frame_state = FrameReceiveStateTimedout;
ready_callback_(buffer_id, frame_num);
frames_timedout++;
frame_buffer_map_.erase(buffer_map_iter++);
}
else
{
buffer_map_iter++;
}
}
if (frames_timedout)
{
LOG4CXX_WARN(logger_, "Released " << frames_timedout << " timed out incomplete frames");
}
frames_timedout_ += frames_timedout;
LOG4CXX_DEBUG_LEVEL(2, logger_, get_num_mapped_buffers() << " frame buffers in use, "
<< get_num_empty_buffers() << " empty buffers available, "
<< frames_timedout_ << " incomplete frames timed out");
}
uint32_t ExcaliburFrameDecoder::get_subframe_counter(void) const
{
return reinterpret_cast<Excalibur::PacketHeader*>(current_packet_header_.get())->subframe_counter;
}
uint32_t ExcaliburFrameDecoder::get_packet_number(void) const
{
return reinterpret_cast<Excalibur::PacketHeader*>(current_packet_header_.get())->packet_number_flags & Excalibur::packet_number_mask;
}
bool ExcaliburFrameDecoder::get_start_of_frame_marker(void) const
{
uint32_t packet_number_flags = reinterpret_cast<Excalibur::PacketHeader*>(current_packet_header_.get())->packet_number_flags;
return ((packet_number_flags & Excalibur::start_of_frame_mask) != 0);
}
bool ExcaliburFrameDecoder::get_end_of_frame_marker(void) const
{
uint32_t packet_number_flags = reinterpret_cast<Excalibur::PacketHeader*>(current_packet_header_.get())->packet_number_flags;
return ((packet_number_flags & Excalibur::end_of_frame_mask) != 0);
}
unsigned int ExcaliburFrameDecoder::elapsed_ms(struct timespec& start, struct timespec& end)
{
double start_ns = ((double)start.tv_sec * 1000000000) + start.tv_nsec;
double end_ns = ((double) end.tv_sec * 1000000000) + end.tv_nsec;
return (unsigned int)((end_ns - start_ns)/1000000);
}
<|endoftext|>
|
<commit_before>// RUN: %clang_cc1 -triple x86_64-unknown-nacl -std=c++11 -verify %s
// expected-no-diagnostics
#include <stddef.h>
#include <stdarg.h>
static_assert(alignof(char) == 1, "alignof char is wrong");
static_assert(alignof(short) == 2, "sizeof short is wrong");
static_assert(alignof(short) == 2, "alignof short is wrong");
static_assert(alignof(int) == 4, "sizeof int is wrong");
static_assert(alignof(int) == 4, "alignof int is wrong");
static_assert(sizeof(long) == 4, "sizeof long is wrong");
static_assert(sizeof(long) == 4, "alignof long is wrong");
static_assert(sizeof(long long) == 8, "sizeof long long is wrong wrong");
static_assert(alignof(long long) == 8, "alignof long long is wrong wrong");
static_assert(sizeof(void*) == 4, "sizeof void * is wrong");
static_assert(alignof(void*) == 4, "alignof void * is wrong");
static_assert(sizeof(float) == 4, "sizeof float is wrong");
static_assert(alignof(float) == 4, "alignof float is wrong");
static_assert(sizeof(double) == 8, "sizeof double is wrong");
static_assert(alignof(double) == 8, "alignof double is wrong");
static_assert(sizeof(long double) == 8, "sizeof long double is wrong");
static_assert(alignof(long double) == 8, "alignof long double is wrong");
static_assert(sizeof(va_list) == 16, "sizeof va_list is wrong");
static_assert(alignof(va_list) == 4, "alignof va_list is wrong");
static_assert(sizeof(size_t) == 4, "sizeof size_t is wrong");
static_assert(alignof(size_t) == 4, "alignof size_t is wrong");
<commit_msg>Fix copy-paste errors in the test<commit_after>// RUN: %clang_cc1 -triple x86_64-unknown-nacl -std=c++11 -verify %s
// expected-no-diagnostics
#include <stddef.h>
#include <stdarg.h>
static_assert(alignof(char) == 1, "alignof char is wrong");
static_assert(sizeof(short) == 2, "sizeof short is wrong");
static_assert(alignof(short) == 2, "alignof short is wrong");
static_assert(sizeof(int) == 4, "sizeof int is wrong");
static_assert(alignof(int) == 4, "alignof int is wrong");
static_assert(sizeof(long) == 4, "sizeof long is wrong");
static_assert(alignof(long) == 4, "alignof long is wrong");
static_assert(sizeof(long long) == 8, "sizeof long long is wrong wrong");
static_assert(alignof(long long) == 8, "alignof long long is wrong wrong");
static_assert(sizeof(void*) == 4, "sizeof void * is wrong");
static_assert(alignof(void*) == 4, "alignof void * is wrong");
static_assert(sizeof(float) == 4, "sizeof float is wrong");
static_assert(alignof(float) == 4, "alignof float is wrong");
static_assert(sizeof(double) == 8, "sizeof double is wrong");
static_assert(alignof(double) == 8, "alignof double is wrong");
static_assert(sizeof(long double) == 8, "sizeof long double is wrong");
static_assert(alignof(long double) == 8, "alignof long double is wrong");
static_assert(sizeof(va_list) == 16, "sizeof va_list is wrong");
static_assert(alignof(va_list) == 4, "alignof va_list is wrong");
static_assert(sizeof(size_t) == 4, "sizeof size_t is wrong");
static_assert(alignof(size_t) == 4, "alignof size_t is wrong");
<|endoftext|>
|
<commit_before>/*
* gVirtuS -- A GPGPU transparent virtualization component.
*
* Copyright (C) 2009-2011 The University of Napoli Parthenope at Naples.
*
* This file is part of gVirtuS.
*
* gVirtuS 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.
*
* gVirtuS 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 General Public License
* along with gVirtuS; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Written by: Giuseppe Coviello <giuseppe.coviello@uniparthenope.it>,
* Department of Applied Science
*/
#include <cufft.h>
#include "Frontend.h"
#include <iostream>
using namespace std;
extern "C" cufftResult cufftPlan1d(cufftHandle *plan, int nx, cufftType type,
int batch) {
Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *in = f->GetInputBuffer();
in->Add(nx);
in->Add(type);
in->Add(batch);
f->Execute("cufftPlan1d");
//cout << hex << f->GetOutputBuffer() << endl;
//cout << hex << f->GetOutputBuffer()->Get<uint64_t>();
//*plan = (cufftHandle) f->GetOutputBuffer()->Get<uint64_t>();
*plan = f->GetOutputBuffer()->Get<cufftHandle>();
cout << "CCCC\n";
return (cufftResult) f->GetExitCode();
}
extern "C" cufftResult cufftPlan2d(cufftHandle *plan, int nx, int ny,
cufftType type) {
Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *in = f->GetInputBuffer();
in->Add(nx);
in->Add(ny);
in->Add(type);
f->Execute("cufftPlan2d");
*plan = f->GetOutputBuffer()->Get<cufftHandle>();
return (cufftResult) f->GetExitCode();
}
extern "C" cufftResult cufftPlan3d(cufftHandle *plan, int nx, int ny, int nz,
cufftType type) {
Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *in = f->GetInputBuffer();
in->Add(nx);
in->Add(ny);
in->Add(nz);
in->Add(type);
f->Execute("cufftPlan3d");
*plan = (cufftHandle) f->GetOutputBuffer()->Get<uint64_t>();
return (cufftResult) f->GetExitCode();
}
extern "C" cufftResult cufftPlanMany(cufftHandle *plan, int rank, int *n,
int *inembed, int istride, int idist, int *onembed, int ostride,
int odist, cufftType type, int batch) {
Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *in = f->GetInputBuffer();
in->Add(rank);
in->Add(*n);
in->Add(istride);
in->Add(idist);
in->Add(ostride);
in->Add(odist);
in->Add(type);
in->Add(batch);
f->Execute("cufftPlanMany");
*plan = (cufftHandle) f->GetOutputBuffer()->Get<uint64_t>();
*n = f->GetOutputBuffer()->Get<int>();
return (cufftResult) f->GetExitCode();
}
/*
* in Testing - Vincenzo Santopietro
*/
extern "C" cufftResult cufftCreate(cufftHandle *plan) {
Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *in = f->GetInputBuffer();
in->Add(plan);
f->Execute("cufftCreate");
return (cufftResult) f->GetExitCode();
}
extern "C" cufftResult cufftDestroy(cufftHandle plan) {
Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *in = f->GetInputBuffer();
in->Add(plan);
f->Execute("cufftDestroy");
return (cufftResult) f->GetExitCode();
}
extern "C" cufftResult cufftExecC2C(cufftHandle plan, cufftComplex *idata,
cufftComplex *odata, int direction) {
Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *in = f->GetInputBuffer();
in->Add(plan);
in->Add(idata);
in->Add(odata);
in->Add(direction);
f->Execute("cufftExecC2C");
return (cufftResult) f->GetExitCode();
}
extern "C" cufftResult cufftExecR2C(cufftHandle plan, cufftReal *idata,
cufftComplex *odata) {
Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *in = f->GetInputBuffer();
in->Add(plan);
in->Add(idata);
in->Add(odata);
f->Execute("cufftExecR2C");
return (cufftResult) f->GetExitCode();
}
extern "C" cufftResult cufftExecC2R(cufftHandle plan, cufftComplex *idata,
cufftReal *odata) {
Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *in = f->GetInputBuffer();
in->Add(plan);
in->Add((uint64_t) idata);
in->Add((uint64_t) odata);
f->Execute("cufftExecC2R");
return (cufftResult) f->GetExitCode();
}
extern "C" cufftResult cufftExecZ2Z(cufftHandle plan, cufftDoubleComplex *idata,
cufftDoubleComplex *odata, int direction) {
Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *in = f->GetInputBuffer();
in->Add(plan);
in->Add(idata);
in->Add(odata);
in->Add(direction);
f->Execute("cufftExecZ2z");
return (cufftResult) f->GetExitCode();
}
extern "C" cufftResult cufftExecD2Z(cufftHandle plan, cufftDoubleReal *idata,
cufftDoubleComplex *odata) {
Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *in = f->GetInputBuffer();
in->Add(plan);
in->Add(idata);
in->Add(odata);
f->Execute("cufftExecD2Z");
return (cufftResult) f->GetExitCode();
}
extern "C" cufftResult cufftExecZ2D(cufftHandle plan, cufftDoubleComplex *idata,
cufftDoubleReal *odata) {
Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *in = f->GetInputBuffer();
in->Add(plan);
in->Add(idata);
in->Add(odata);
f->Execute("cufftExecZ2D");
return (cufftResult) f->GetExitCode();
}
extern "C" cufftResult cufftSetStream(cufftHandle plan, cudaStream_t stream) {
Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *in = f->GetInputBuffer();
in->Add(plan);
in->Add((uint64_t) stream);
f->Execute("cufftSetStream");
return (cufftResult) f->GetExitCode();
}
extern "C" cufftResult cufftSetCompatibilityMode(cufftHandle plan,
cufftCompatibility mode){
Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *in = f->GetInputBuffer();
in->Add(plan);
in->Add(mode);
f->Execute("cufftSetCompatibilityMode");
return (cufftResult) f->GetExitCode();
}
extern "C" cufftResult cufftXtMakePlanMany(cufftHandle plan, int rank, long long int *n, long long int *inembed, long long int istride, long long int idist, cudaDataType inputtype, long long int *onembed, long long int ostride, long long int odist, cudaDataType outputtype, long long int batch, size_t *workSize, cudaDataType executiontype) {
Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *in = f->GetInputBuffer();
//plan = (cufftHandle) f->GetOutputBuffer()->Get<cufftHandle>();
//n = (long long int * )f->GetOutputBuffer()->Get<long long int>();
in->Add(plan);
in->Add(rank);
in->Add(*n);
in->Add(*inembed);
in->Add(istride);
in->Add(idist);
in->Add(inputtype);
in->Add(*onembed);
in->Add(ostride);
in->Add(odist);
in->Add(outputtype);
in->Add(batch);
in->Add(*workSize);
in->Add(executiontype);
f->Execute("cufftXtMakePlanMany");
return (cufftResult) f->GetExitCode();
}
<commit_msg>Fixed cufftCreate and CufftPlan1d<commit_after>/*
* gVirtuS -- A GPGPU transparent virtualization component.
*
* Copyright (C) 2009-2011 The University of Napoli Parthenope at Naples.
*
* This file is part of gVirtuS.
*
* gVirtuS 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.
*
* gVirtuS 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 General Public License
* along with gVirtuS; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Written by: Giuseppe Coviello <giuseppe.coviello@uniparthenope.it>,
* Department of Applied Science
*/
#include <cufft.h>
#include "Frontend.h"
#include "CufftFrontend.h"
using namespace std;
extern "C" cufftResult cufftPlan1d(cufftHandle *plan, int nx, cufftType type,
int batch) {
/*Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *in = f->GetInputBuffer();
in->Add(nx);
in->Add(type);
in->Add(batch);
f->Execute("cufftPlan1d");
//cout << hex << f->GetOutputBuffer() << endl;
//cout << hex << f->GetOutputBuffer()->Get<uint64_t>();
//*plan = (cufftHandle) f->GetOutputBuffer()->Get<uint64_t>();
*plan = f->GetOutputBuffer()->Get<cufftHandle>();
return (cufftResult) f->GetExitCode();*/
CufftFrontend::Prepare();
CufftFrontend::AddHostPointerForArguments(plan);
CufftFrontend::AddVariableForArguments(nx);
CufftFrontend::AddVariableForArguments(type);
CufftFrontend::AddVariableForArguments(batch);
CufftFrontend::Execute("cufftPlan1d");
if(CufftFrontend::Success())
*plan = *(CufftFrontend::GetOutputHostPointer<cufftHandle>());
cout << "plan : "<< *plan;
return (cufftResult) CufftFrontend::GetExitCode();
}
extern "C" cufftResult cufftPlan2d(cufftHandle *plan, int nx, int ny,
cufftType type) {
Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *in = f->GetInputBuffer();
in->Add(nx);
in->Add(ny);
in->Add(type);
f->Execute("cufftPlan2d");
*plan = f->GetOutputBuffer()->Get<cufftHandle>();
return (cufftResult) f->GetExitCode();
}
extern "C" cufftResult cufftPlan3d(cufftHandle *plan, int nx, int ny, int nz,
cufftType type) {
Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *in = f->GetInputBuffer();
in->Add(nx);
in->Add(ny);
in->Add(nz);
in->Add(type);
f->Execute("cufftPlan3d");
*plan = (cufftHandle) f->GetOutputBuffer()->Get<uint64_t>();
return (cufftResult) f->GetExitCode();
}
extern "C" cufftResult cufftPlanMany(cufftHandle *plan, int rank, int *n,
int *inembed, int istride, int idist, int *onembed, int ostride,
int odist, cufftType type, int batch) {
Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *in = f->GetInputBuffer();
in->Add(rank);
in->Add(*n);
in->Add(istride);
in->Add(idist);
in->Add(ostride);
in->Add(odist);
in->Add(type);
in->Add(batch);
f->Execute("cufftPlanMany");
*plan = (cufftHandle) f->GetOutputBuffer()->Get<uint64_t>();
*n = f->GetOutputBuffer()->Get<int>();
return (cufftResult) f->GetExitCode();
}
/*
* in Testing - Vincenzo Santopietro
*/
extern "C" cufftResult cufftCreate(cufftHandle *plan) {
//Frontend *f = Frontend::GetFrontend();
CufftFrontend::Prepare();
CufftFrontend::AddHostPointerForArguments(plan);
//f->GetFrontend();
CufftFrontend::Execute("cufftCreate");
if(CufftFrontend::Success())
*plan = *(CufftFrontend::GetOutputHostPointer<cufftHandle>());
printf("plan: %d",*plan);
return (cufftResult) CufftFrontend::GetExitCode();//(cufftResult) CufftFrontend::GetExitCode();
}
extern "C" cufftResult cufftDestroy(cufftHandle plan) {
Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *in = f->GetInputBuffer();
in->Add(plan);
f->Execute("cufftDestroy");
return (cufftResult) f->GetExitCode();
}
extern "C" cufftResult cufftExecC2C(cufftHandle plan, cufftComplex *idata,
cufftComplex *odata, int direction) {
Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *in = f->GetInputBuffer();
in->Add(plan);
in->Add(idata);
in->Add(odata);
in->Add(direction);
f->Execute("cufftExecC2C");
return (cufftResult) f->GetExitCode();
}
extern "C" cufftResult cufftExecR2C(cufftHandle plan, cufftReal *idata,
cufftComplex *odata) {
Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *in = f->GetInputBuffer();
in->Add(plan);
in->Add(idata);
in->Add(odata);
f->Execute("cufftExecR2C");
return (cufftResult) f->GetExitCode();
}
extern "C" cufftResult cufftExecC2R(cufftHandle plan, cufftComplex *idata,
cufftReal *odata) {
Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *in = f->GetInputBuffer();
in->Add(plan);
in->Add((uint64_t) idata);
in->Add((uint64_t) odata);
f->Execute("cufftExecC2R");
return (cufftResult) f->GetExitCode();
}
extern "C" cufftResult cufftExecZ2Z(cufftHandle plan, cufftDoubleComplex *idata,
cufftDoubleComplex *odata, int direction) {
Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *in = f->GetInputBuffer();
in->Add(plan);
in->Add(idata);
in->Add(odata);
in->Add(direction);
f->Execute("cufftExecZ2z");
return (cufftResult) f->GetExitCode();
}
extern "C" cufftResult cufftExecD2Z(cufftHandle plan, cufftDoubleReal *idata,
cufftDoubleComplex *odata) {
Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *in = f->GetInputBuffer();
in->Add(plan);
in->Add(idata);
in->Add(odata);
f->Execute("cufftExecD2Z");
return (cufftResult) f->GetExitCode();
}
extern "C" cufftResult cufftExecZ2D(cufftHandle plan, cufftDoubleComplex *idata,
cufftDoubleReal *odata) {
Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *in = f->GetInputBuffer();
in->Add(plan);
in->Add(idata);
in->Add(odata);
f->Execute("cufftExecZ2D");
return (cufftResult) f->GetExitCode();
}
extern "C" cufftResult cufftSetStream(cufftHandle plan, cudaStream_t stream) {
Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *in = f->GetInputBuffer();
in->Add(plan);
in->Add((uint64_t) stream);
f->Execute("cufftSetStream");
return (cufftResult) f->GetExitCode();
}
extern "C" cufftResult cufftSetCompatibilityMode(cufftHandle plan,
cufftCompatibility mode){
Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *in = f->GetInputBuffer();
in->Add(plan);
in->Add(mode);
f->Execute("cufftSetCompatibilityMode");
return (cufftResult) f->GetExitCode();
}
extern "C" cufftResult cufftXtMakePlanMany(cufftHandle plan, int rank, long long int *n, long long int *inembed, long long int istride, long long int idist, cudaDataType inputtype, long long int *onembed, long long int ostride, long long int odist, cudaDataType outputtype, long long int batch, size_t *workSize, cudaDataType executiontype) {
Frontend *f = Frontend::GetFrontend();
f->Prepare();
Buffer *input_buffer = f->GetInputBuffer();
plan = (cufftHandle) f->GetOutputBuffer()->Get<cufftHandle>();
n = (long long int * )f->GetOutputBuffer()->Get<long long int>();
input_buffer->Add(plan);
input_buffer->Add(rank);
input_buffer->Add(*n);
input_buffer->Add(*inembed);
input_buffer->Add(istride);
input_buffer->Add(idist);
input_buffer->Add(inputtype);
input_buffer->Add(*onembed);
input_buffer->Add(ostride);
input_buffer->Add(odist);
input_buffer->Add(outputtype);
input_buffer->Add(batch);
input_buffer->Add(*workSize);
input_buffer->Add(executiontype);
f->Execute("cufftXtMakePlanMany");
return (cufftResult) f->GetExitCode();
}
<|endoftext|>
|
<commit_before><commit_msg>fix OOXML validation error<commit_after><|endoftext|>
|
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
//
// 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.
//
// Interface header.
#include "generictilerenderer.h"
// appleseed.renderer headers.
#include "renderer/global/globallogger.h"
#include "renderer/global/globaltypes.h"
#include "renderer/kernel/aov/imagestack.h"
#include "renderer/kernel/aov/tilestack.h"
#include "renderer/kernel/rendering/ipixelrenderer.h"
#include "renderer/kernel/rendering/ishadingresultframebufferfactory.h"
#include "renderer/kernel/rendering/pixelcontext.h"
#include "renderer/kernel/rendering/shadingresultframebuffer.h"
#include "renderer/modeling/frame/frame.h"
// appleseed.foundation headers.
#include "foundation/image/canvasproperties.h"
#include "foundation/image/image.h"
#include "foundation/image/tile.h"
#include "foundation/math/aabb.h"
#include "foundation/math/filter.h"
#include "foundation/math/ordering.h"
#include "foundation/math/scalar.h"
#include "foundation/math/vector.h"
#include "foundation/platform/breakpoint.h"
#include "foundation/platform/types.h"
#include "foundation/utility/autoreleaseptr.h"
#include "foundation/utility/iostreamop.h"
#include "foundation/utility/job.h"
#include "foundation/utility/statistics.h"
#include "foundation/utility/string.h"
// Standard headers.
#include <cassert>
#include <cmath>
#include <cstddef>
#include <memory>
#include <string>
#include <vector>
using namespace foundation;
using namespace std;
namespace renderer
{
namespace
{
//
// Generic tile renderer.
//
#ifndef NDEBUG
// Define this symbol to break execution into the debugger
// when a specific pixel is about to be rendered.
// #define DEBUG_BREAK_AT_PIXEL Vector2i(0, 0)
#endif
class GenericTileRenderer
: public ITileRenderer
{
public:
GenericTileRenderer(
const Frame& frame,
IPixelRendererFactory* pixel_renderer_factory,
IShadingResultFrameBufferFactory* framebuffer_factory,
const ParamArray& params,
const bool primary)
: m_pixel_renderer(pixel_renderer_factory->create(primary))
, m_framebuffer_factory(framebuffer_factory)
{
compute_tile_margins(frame, primary);
compute_pixel_ordering(frame);
}
virtual void release() OVERRIDE
{
delete this;
}
virtual void render_tile(
const Frame& frame,
const size_t tile_x,
const size_t tile_y,
const size_t pass_hash,
AbortSwitch& abort_switch) OVERRIDE
{
// Retrieve frame properties.
const CanvasProperties& frame_properties = frame.image().properties();
assert(tile_x < frame_properties.m_tile_count_x);
assert(tile_y < frame_properties.m_tile_count_y);
// Retrieve tile properties.
Tile& tile = frame.image().tile(tile_x, tile_y);
TileStack aov_tiles = frame.aov_images().tiles(tile_x, tile_y);
const size_t tile_origin_x = frame_properties.m_tile_width * tile_x;
const size_t tile_origin_y = frame_properties.m_tile_height * tile_y;
// Compute the image space bounding box of the pixels to render.
AABB2u tile_bbox;
tile_bbox.min.x = tile_origin_x;
tile_bbox.min.y = tile_origin_y;
tile_bbox.max.x = tile_origin_x + tile.get_width() - 1;
tile_bbox.max.y = tile_origin_y + tile.get_height() - 1;
tile_bbox = AABB2u::intersect(tile_bbox, frame.get_crop_window());
if (!tile_bbox.is_valid())
return;
// Transform the bounding box to local (tile) space.
tile_bbox.min.x -= tile_origin_x;
tile_bbox.min.y -= tile_origin_y;
tile_bbox.max.x -= tile_origin_x;
tile_bbox.max.y -= tile_origin_y;
// Inform the pixel renderer that we are about to render a tile.
m_pixel_renderer->on_tile_begin(frame, tile, aov_tiles);
// Create the framebuffer into which we will accumulate the samples.
ShadingResultFrameBuffer* framebuffer =
m_framebuffer_factory->create(
frame,
tile_x,
tile_y,
tile_bbox);
assert(framebuffer);
// Seed the RNG with the tile index.
m_rng = SamplingContext::RNGType(
static_cast<uint32>(
tile_y * frame_properties.m_tile_count_x + tile_x));
// Loop over tile pixels.
const size_t tile_pixel_count = m_pixel_ordering.size();
for (size_t i = 0; i < tile_pixel_count; ++i)
{
// Cancel any work done on this tile if rendering is aborted.
if (abort_switch.is_aborted())
return;
// Retrieve the coordinates of the pixel in the padded tile.
const int tx = m_pixel_ordering[i].x;
const int ty = m_pixel_ordering[i].y;
// Skip pixels outside the intersection of the padded tile and the crop window.
if (tx > static_cast<int>(tile_bbox.max.x) + m_margin_width ||
ty > static_cast<int>(tile_bbox.max.y) + m_margin_height)
continue;
// Create a pixel context that identifies the pixel currently being rendered.
const PixelContext pixel_context(
static_cast<int>(tile_origin_x) + tx,
static_cast<int>(tile_origin_y) + ty);
#ifdef DEBUG_BREAK_AT_PIXEL
// Break in the debugger when this pixel is reached.
if (pixel_context.get_pixel_coordinates() == DEBUG_BREAK_AT_PIXEL)
BREAKPOINT();
#endif
// Render this pixel.
m_pixel_renderer->render_pixel(
frame,
tile,
aov_tiles,
AABB2i(tile_bbox),
pixel_context,
pass_hash,
tx, ty,
m_rng,
*framebuffer);
}
// Develop the framebuffer to the tile.
if (frame.is_premultiplied_alpha())
framebuffer->develop_to_tile_premult_alpha(tile, aov_tiles);
else framebuffer->develop_to_tile_straight_alpha(tile, aov_tiles);
// Release the framebuffer.
m_framebuffer_factory->destroy(framebuffer);
// Inform the pixel renderer that we are done rendering the tile.
m_pixel_renderer->on_tile_end(frame, tile, aov_tiles);
}
virtual StatisticsVector get_statistics() const OVERRIDE
{
return m_pixel_renderer->get_statistics();
}
protected:
auto_release_ptr<IPixelRenderer> m_pixel_renderer;
IShadingResultFrameBufferFactory* m_framebuffer_factory;
int m_margin_width;
int m_margin_height;
vector<Vector<int16, 2> > m_pixel_ordering;
SamplingContext::RNGType m_rng;
void compute_tile_margins(const Frame& frame, const bool primary)
{
m_margin_width = truncate<int>(ceil(frame.get_filter().get_xradius() - 0.5));
m_margin_height = truncate<int>(ceil(frame.get_filter().get_yradius() - 0.5));
const CanvasProperties& properties = frame.image().properties();
const size_t padded_tile_width = properties.m_tile_width + 2 * m_margin_width;
const size_t padded_tile_height = properties.m_tile_height + 2 * m_margin_height;
const size_t padded_pixel_count = padded_tile_width * padded_tile_height;
const size_t pixel_count = properties.m_tile_width * properties.m_tile_height;
const size_t overhead_pixel_count = padded_pixel_count - pixel_count;
const double wasted_effort = static_cast<double>(overhead_pixel_count) / pixel_count * 100.0;
const double MaxWastedEffort = 15.0; // percents
if (primary)
{
RENDERER_LOG(
wasted_effort > MaxWastedEffort ? LogMessage::Warning : LogMessage::Info,
"rendering effort wasted by tile borders: %s (tile dimensions: %sx%s, tile margins: %sx%s)",
pretty_percent(overhead_pixel_count, pixel_count).c_str(),
pretty_uint(properties.m_tile_width).c_str(),
pretty_uint(properties.m_tile_height).c_str(),
pretty_uint(2 * m_margin_width).c_str(),
pretty_uint(2 * m_margin_height).c_str());
}
}
void compute_pixel_ordering(const Frame& frame)
{
// Compute the dimensions in pixels of the padded tile.
const CanvasProperties& properties = frame.image().properties();
const size_t padded_tile_width = properties.m_tile_width + 2 * m_margin_width;
const size_t padded_tile_height = properties.m_tile_height + 2 * m_margin_height;
const size_t pixel_count = padded_tile_width * padded_tile_height;
// Generate the pixel ordering inside the padded tile.
vector<size_t> ordering;
ordering.reserve(pixel_count);
hilbert_ordering(ordering, padded_tile_width, padded_tile_height);
assert(ordering.size() == pixel_count);
// Convert the pixel ordering to a 2D representation.
m_pixel_ordering.resize(pixel_count);
for (size_t i = 0; i < pixel_count; ++i)
{
const size_t x = ordering[i] % padded_tile_width;
const size_t y = ordering[i] / padded_tile_width;
assert(x < padded_tile_width);
assert(y < padded_tile_height);
m_pixel_ordering[i].x = static_cast<int16>(x) - m_margin_width;
m_pixel_ordering[i].y = static_cast<int16>(y) - m_margin_height;
}
}
};
}
//
// GenericTileRendererFactory class implementation.
//
GenericTileRendererFactory::GenericTileRendererFactory(
const Frame& frame,
IPixelRendererFactory* pixel_renderer_factory,
IShadingResultFrameBufferFactory* framebuffer_factory,
const ParamArray& params)
: m_frame(frame)
, m_pixel_renderer_factory(pixel_renderer_factory)
, m_framebuffer_factory(framebuffer_factory)
, m_params(params)
{
}
void GenericTileRendererFactory::release()
{
delete this;
}
ITileRenderer* GenericTileRendererFactory::create(const bool primary)
{
return
new GenericTileRenderer(
m_frame,
m_pixel_renderer_factory,
m_framebuffer_factory,
m_params,
primary);
}
} // namespace renderer
<commit_msg>bug fix: some pixels were computed even though they were outside the crop window (they were not stored though).<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
//
// 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.
//
// Interface header.
#include "generictilerenderer.h"
// appleseed.renderer headers.
#include "renderer/global/globallogger.h"
#include "renderer/global/globaltypes.h"
#include "renderer/kernel/aov/imagestack.h"
#include "renderer/kernel/aov/tilestack.h"
#include "renderer/kernel/rendering/ipixelrenderer.h"
#include "renderer/kernel/rendering/ishadingresultframebufferfactory.h"
#include "renderer/kernel/rendering/pixelcontext.h"
#include "renderer/kernel/rendering/shadingresultframebuffer.h"
#include "renderer/modeling/frame/frame.h"
// appleseed.foundation headers.
#include "foundation/image/canvasproperties.h"
#include "foundation/image/image.h"
#include "foundation/image/tile.h"
#include "foundation/math/aabb.h"
#include "foundation/math/filter.h"
#include "foundation/math/ordering.h"
#include "foundation/math/scalar.h"
#include "foundation/math/vector.h"
#include "foundation/platform/breakpoint.h"
#include "foundation/platform/types.h"
#include "foundation/utility/autoreleaseptr.h"
#include "foundation/utility/iostreamop.h"
#include "foundation/utility/job.h"
#include "foundation/utility/statistics.h"
#include "foundation/utility/string.h"
// Standard headers.
#include <cassert>
#include <cmath>
#include <cstddef>
#include <memory>
#include <string>
#include <vector>
using namespace foundation;
using namespace std;
namespace renderer
{
namespace
{
//
// Generic tile renderer.
//
#ifndef NDEBUG
// Define this symbol to break execution into the debugger
// when a specific pixel is about to be rendered.
// #define DEBUG_BREAK_AT_PIXEL Vector2i(0, 0)
#endif
class GenericTileRenderer
: public ITileRenderer
{
public:
GenericTileRenderer(
const Frame& frame,
IPixelRendererFactory* pixel_renderer_factory,
IShadingResultFrameBufferFactory* framebuffer_factory,
const ParamArray& params,
const bool primary)
: m_pixel_renderer(pixel_renderer_factory->create(primary))
, m_framebuffer_factory(framebuffer_factory)
{
compute_tile_margins(frame, primary);
compute_pixel_ordering(frame);
}
virtual void release() OVERRIDE
{
delete this;
}
virtual void render_tile(
const Frame& frame,
const size_t tile_x,
const size_t tile_y,
const size_t pass_hash,
AbortSwitch& abort_switch) OVERRIDE
{
// Retrieve frame properties.
const CanvasProperties& frame_properties = frame.image().properties();
assert(tile_x < frame_properties.m_tile_count_x);
assert(tile_y < frame_properties.m_tile_count_y);
// Retrieve tile properties.
Tile& tile = frame.image().tile(tile_x, tile_y);
TileStack aov_tiles = frame.aov_images().tiles(tile_x, tile_y);
const size_t tile_origin_x = frame_properties.m_tile_width * tile_x;
const size_t tile_origin_y = frame_properties.m_tile_height * tile_y;
// Compute the image space bounding box of the pixels to render.
AABB2u tile_bbox;
tile_bbox.min.x = tile_origin_x;
tile_bbox.min.y = tile_origin_y;
tile_bbox.max.x = tile_origin_x + tile.get_width() - 1;
tile_bbox.max.y = tile_origin_y + tile.get_height() - 1;
tile_bbox = AABB2u::intersect(tile_bbox, frame.get_crop_window());
if (!tile_bbox.is_valid())
return;
// Transform the bounding box to local (tile) space.
tile_bbox.min.x -= tile_origin_x;
tile_bbox.min.y -= tile_origin_y;
tile_bbox.max.x -= tile_origin_x;
tile_bbox.max.y -= tile_origin_y;
// Inform the pixel renderer that we are about to render a tile.
m_pixel_renderer->on_tile_begin(frame, tile, aov_tiles);
// Create the framebuffer into which we will accumulate the samples.
ShadingResultFrameBuffer* framebuffer =
m_framebuffer_factory->create(
frame,
tile_x,
tile_y,
tile_bbox);
assert(framebuffer);
// Seed the RNG with the tile index.
m_rng = SamplingContext::RNGType(
static_cast<uint32>(
tile_y * frame_properties.m_tile_count_x + tile_x));
// Loop over tile pixels.
const size_t tile_pixel_count = m_pixel_ordering.size();
for (size_t i = 0; i < tile_pixel_count; ++i)
{
// Cancel any work done on this tile if rendering is aborted.
if (abort_switch.is_aborted())
return;
// Retrieve the coordinates of the pixel in the padded tile.
const int tx = m_pixel_ordering[i].x;
const int ty = m_pixel_ordering[i].y;
// Skip pixels outside the intersection of the padded tile and the crop window.
if (tx < static_cast<int>(tile_bbox.min.x) - m_margin_width ||
ty < static_cast<int>(tile_bbox.min.y) - m_margin_height ||
tx > static_cast<int>(tile_bbox.max.x) + m_margin_width ||
ty > static_cast<int>(tile_bbox.max.y) + m_margin_height)
continue;
// Create a pixel context that identifies the pixel currently being rendered.
const PixelContext pixel_context(
static_cast<int>(tile_origin_x) + tx,
static_cast<int>(tile_origin_y) + ty);
#ifdef DEBUG_BREAK_AT_PIXEL
// Break in the debugger when this pixel is reached.
if (pixel_context.get_pixel_coordinates() == DEBUG_BREAK_AT_PIXEL)
BREAKPOINT();
#endif
// Render this pixel.
m_pixel_renderer->render_pixel(
frame,
tile,
aov_tiles,
AABB2i(tile_bbox),
pixel_context,
pass_hash,
tx, ty,
m_rng,
*framebuffer);
}
// Develop the framebuffer to the tile.
if (frame.is_premultiplied_alpha())
framebuffer->develop_to_tile_premult_alpha(tile, aov_tiles);
else framebuffer->develop_to_tile_straight_alpha(tile, aov_tiles);
// Release the framebuffer.
m_framebuffer_factory->destroy(framebuffer);
// Inform the pixel renderer that we are done rendering the tile.
m_pixel_renderer->on_tile_end(frame, tile, aov_tiles);
}
virtual StatisticsVector get_statistics() const OVERRIDE
{
return m_pixel_renderer->get_statistics();
}
protected:
auto_release_ptr<IPixelRenderer> m_pixel_renderer;
IShadingResultFrameBufferFactory* m_framebuffer_factory;
int m_margin_width;
int m_margin_height;
vector<Vector<int16, 2> > m_pixel_ordering;
SamplingContext::RNGType m_rng;
void compute_tile_margins(const Frame& frame, const bool primary)
{
m_margin_width = truncate<int>(ceil(frame.get_filter().get_xradius() - 0.5));
m_margin_height = truncate<int>(ceil(frame.get_filter().get_yradius() - 0.5));
const CanvasProperties& properties = frame.image().properties();
const size_t padded_tile_width = properties.m_tile_width + 2 * m_margin_width;
const size_t padded_tile_height = properties.m_tile_height + 2 * m_margin_height;
const size_t padded_pixel_count = padded_tile_width * padded_tile_height;
const size_t pixel_count = properties.m_tile_width * properties.m_tile_height;
const size_t overhead_pixel_count = padded_pixel_count - pixel_count;
const double wasted_effort = static_cast<double>(overhead_pixel_count) / pixel_count * 100.0;
const double MaxWastedEffort = 15.0; // percents
if (primary)
{
RENDERER_LOG(
wasted_effort > MaxWastedEffort ? LogMessage::Warning : LogMessage::Info,
"rendering effort wasted by tile borders: %s (tile dimensions: %sx%s, tile margins: %sx%s)",
pretty_percent(overhead_pixel_count, pixel_count).c_str(),
pretty_uint(properties.m_tile_width).c_str(),
pretty_uint(properties.m_tile_height).c_str(),
pretty_uint(2 * m_margin_width).c_str(),
pretty_uint(2 * m_margin_height).c_str());
}
}
void compute_pixel_ordering(const Frame& frame)
{
// Compute the dimensions in pixels of the padded tile.
const CanvasProperties& properties = frame.image().properties();
const size_t padded_tile_width = properties.m_tile_width + 2 * m_margin_width;
const size_t padded_tile_height = properties.m_tile_height + 2 * m_margin_height;
const size_t pixel_count = padded_tile_width * padded_tile_height;
// Generate the pixel ordering inside the padded tile.
vector<size_t> ordering;
ordering.reserve(pixel_count);
hilbert_ordering(ordering, padded_tile_width, padded_tile_height);
assert(ordering.size() == pixel_count);
// Convert the pixel ordering to a 2D representation.
m_pixel_ordering.resize(pixel_count);
for (size_t i = 0; i < pixel_count; ++i)
{
const size_t x = ordering[i] % padded_tile_width;
const size_t y = ordering[i] / padded_tile_width;
assert(x < padded_tile_width);
assert(y < padded_tile_height);
m_pixel_ordering[i].x = static_cast<int16>(x) - m_margin_width;
m_pixel_ordering[i].y = static_cast<int16>(y) - m_margin_height;
}
}
};
}
//
// GenericTileRendererFactory class implementation.
//
GenericTileRendererFactory::GenericTileRendererFactory(
const Frame& frame,
IPixelRendererFactory* pixel_renderer_factory,
IShadingResultFrameBufferFactory* framebuffer_factory,
const ParamArray& params)
: m_frame(frame)
, m_pixel_renderer_factory(pixel_renderer_factory)
, m_framebuffer_factory(framebuffer_factory)
, m_params(params)
{
}
void GenericTileRendererFactory::release()
{
delete this;
}
ITileRenderer* GenericTileRendererFactory::create(const bool primary)
{
return
new GenericTileRenderer(
m_frame,
m_pixel_renderer_factory,
m_framebuffer_factory,
m_params,
primary);
}
} // namespace renderer
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: TestLabelPlacerExodus.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME Test of vtkLabelPlacer
// .SECTION Description
// this program tests vtkLabelPlacer which uses a sophisticated algorithm to
// prune labels/icons preventing them from overlapping.
#include "vtkActor.h"
#include "vtkActor2D.h"
#include "vtkCamera.h"
#include "vtkCellCenters.h"
#include "vtkCellData.h"
#include "vtkClipDataSet.h"
#include "vtkContourFilter.h"
#include "vtkColorTransferFunction.h"
#include "vtkExodusReader.h"
#include "vtkGeometryFilter.h"
#include "vtkIntArray.h"
#include "vtkLabeledDataMapper.h"
#include "vtkLabelHierarchy.h"
#include "vtkLabelPlacer.h"
#include "vtkLabelSizeCalculator.h"
#include "vtkLookupTable.h"
#include "vtkMath.h"
#include "vtkPlane.h"
#include "vtkPointSetToLabelHierarchy.h"
#include "vtkPoints.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
#include "vtkPolyDataMapper.h"
#include "vtkPolyDataMapper2D.h"
#include "vtkPolyDataNormals.h"
#include "vtkProperty.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkTextProperty.h"
#include "vtkTIFFWriter.h"
#include "vtkXMLPolyDataReader.h"
#include "vtkXMLPolyDataWriter.h"
#include "vtkPolyData.h"
#include "vtkImageData.h"
#include "vtkSmartPointer.h"
#include "vtkSphereSource.h"
#include "vtkStructuredGrid.h"
#include "vtkUnstructuredGrid.h"
#include "vtkRectilinearGrid.h"
#include "vtkWindowToImageFilter.h"
#include <vtkTestUtilities.h>
#include <vtkRegressionTestImage.h>
int TestLabelPlacerExodus(int argc, char *argv[])
{
int maxLevels = 5;
int targetLabels = 32;
double labelRatio = 0.05;
char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/disk_out_ref.ex2");
//int iteratorType = vtkLabelHierarchy::FULL_SORT;
int iteratorType = vtkLabelHierarchy::QUEUE;
//int iteratorType = vtkLabelHierarchy::DEPTH_FIRST;
bool showBounds = false;
vtkSmartPointer<vtkLabelSizeCalculator> labelSizeCalculator =
vtkSmartPointer<vtkLabelSizeCalculator>::New();
vtkSmartPointer<vtkLabelHierarchy> labelHierarchy =
vtkSmartPointer<vtkLabelHierarchy>::New();
vtkSmartPointer<vtkLabelPlacer> labelPlacer =
vtkSmartPointer<vtkLabelPlacer>::New();
vtkSmartPointer<vtkPointSetToLabelHierarchy> pointSetToLabelHierarchy =
vtkSmartPointer<vtkPointSetToLabelHierarchy>::New();
vtkSmartPointer<vtkExodusReader> exoReader =
vtkSmartPointer<vtkExodusReader>::New();
vtkSmartPointer<vtkPlane> plane1 = vtkSmartPointer<vtkPlane>::New();
vtkSmartPointer<vtkPlane> plane2 = vtkSmartPointer<vtkPlane>::New();
vtkSmartPointer<vtkClipDataSet> clip1 = vtkSmartPointer<vtkClipDataSet>::New();
vtkSmartPointer<vtkClipDataSet> clip2 = vtkSmartPointer<vtkClipDataSet>::New();
plane1->SetNormal(0.874613683283037, 0.0, -0.484820487411659);
plane2->SetNormal(-0.483077342911335, 0.875577684026794, 0.0);
vtkSmartPointer<vtkContourFilter> contour = vtkSmartPointer<vtkContourFilter>::New();
vtkSmartPointer<vtkColorTransferFunction> contourXfer = vtkSmartPointer<vtkColorTransferFunction>::New();
vtkSmartPointer<vtkColorTransferFunction> modelXfer = vtkSmartPointer<vtkColorTransferFunction>::New();
vtkSmartPointer<vtkPolyDataMapper> modelMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
vtkSmartPointer<vtkPolyDataMapper> contourMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
vtkSmartPointer<vtkActor> modelActor = vtkSmartPointer<vtkActor>::New();
vtkSmartPointer<vtkActor> contourActor = vtkSmartPointer<vtkActor>::New();
vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renWin = vtkSmartPointer<vtkRenderWindow>::New();
vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkSmartPointer<vtkRenderWindowInteractor>::New();
vtkSmartPointer<vtkLabeledDataMapper> labeledMapper =
vtkSmartPointer<vtkLabeledDataMapper>::New();
vtkSmartPointer<vtkActor2D> textActor = vtkSmartPointer<vtkActor2D>::New();
vtkSmartPointer<vtkCellCenters> cellCenters = vtkSmartPointer<vtkCellCenters>::New();
vtkSmartPointer<vtkGeometryFilter> geometry1 = vtkSmartPointer<vtkGeometryFilter>::New();
vtkSmartPointer<vtkGeometryFilter> geometry2 = vtkSmartPointer<vtkGeometryFilter>::New();
vtkSmartPointer<vtkPolyDataNormals> normals1 = vtkSmartPointer<vtkPolyDataNormals>::New();
vtkSmartPointer<vtkPolyDataNormals> normals2 = vtkSmartPointer<vtkPolyDataNormals>::New();
normals1->SplittingOn();
normals1->ConsistencyOn();
normals1->NonManifoldTraversalOn();
normals2->SplittingOn();
normals2->ConsistencyOn();
normals2->NonManifoldTraversalOn();
//xmlPolyDataReader->SetFileName( fname );
exoReader->SetFileName( fname );
//exoReader->SetPointArrayStatus("Temp", 1);
exoReader->SetAllPointArrayStatus(1);
delete [] fname;
contour->SetInputConnection(exoReader->GetOutputPort());
contour->ComputeNormalsOn();
contour->ComputeGradientsOn();
contour->ComputeScalarsOn();
contour->SetValue(0, 362);
contour->SetValue(1, 500);
contour->SetValue(2, 638);
contour->SetValue(3, 775);
contour->SetValue(4, 844);
contour->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, "Temp");
clip1->SetInputConnection(exoReader->GetOutputPort());
clip1->SetClipFunction(plane1);
clip1->InsideOutOn();
geometry1->SetInputConnection(clip1->GetOutputPort());
clip2->SetInputConnection(contour->GetOutputPort());
clip2->SetClipFunction(plane2);
geometry2->SetInputConnection(clip2->GetOutputPort());
cellCenters->SetInputConnection(clip2->GetOutputPort());
cellCenters->Update();
//cellCenters->GetOutput()->Print(cout);
//geometry2->Update();
//geometry2->GetOutput()->Print(cout);
int numTemps = cellCenters->GetOutput()->GetNumberOfPoints();
vtkSmartPointer<vtkIntArray> priority = vtkSmartPointer<vtkIntArray>::New();
priority->SetName("Priority");
priority->SetNumberOfComponents(1);
priority->SetNumberOfValues(numTemps);
for(int i = 0; i < numTemps; i++)
{
priority->SetValue(i, static_cast<int>(vtkMath::Random(0.0, 5.0)));
}
geometry2->Update();
vtkSmartPointer<vtkPolyData> temp = vtkSmartPointer<vtkPolyData>::New();
temp->ShallowCopy(cellCenters->GetOutput());
temp->GetPointData()->AddArray(priority);
//temp->GetPointData()->AddArray(geometry2->GetOutput()->GetPointData()->GetArray("Temp"));
//temp-
//temp->Print(cout);
/// Label ///
labelSizeCalculator->SetInput(temp);
labelSizeCalculator->GetFontProperty()->SetFontSize( 14 );
labelSizeCalculator->GetFontProperty()->SetFontFamily( vtkTextProperty::GetFontFamilyFromString( "Arial" ) );
labelSizeCalculator->GetFontProperty()->ShadowOn();
labelSizeCalculator->SetInputArrayToProcess( 0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, "PedigreeElementId" );
pointSetToLabelHierarchy->AddInputConnection(labelSizeCalculator->GetOutputPort());
pointSetToLabelHierarchy->SetInputArrayToProcess( 0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, "Priority" );
pointSetToLabelHierarchy->SetInputArrayToProcess( 1, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, "LabelSize" );
pointSetToLabelHierarchy->SetInputArrayToProcess( 2, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, "PedigreeElementId" );
pointSetToLabelHierarchy->SetMaximumDepth( maxLevels );
pointSetToLabelHierarchy->SetTargetLabelCount( targetLabels );
labelPlacer->SetInputConnection( pointSetToLabelHierarchy->GetOutputPort() );
labelPlacer->SetIteratorType( iteratorType );
labelPlacer->SetOutputTraversedBounds( showBounds );
labelPlacer->SetRenderer( renderer );
labelPlacer->SetMaximumLabelFraction( labelRatio );
labelPlacer->UseDepthBufferOn();
labeledMapper->SetInputConnection(labelPlacer->GetOutputPort());
labeledMapper->SetLabelTextProperty(labelSizeCalculator->GetFontProperty());
labeledMapper->SetFieldDataName("LabelText");
labeledMapper->SetLabelModeToLabelFieldData();
labeledMapper->GetLabelTextProperty()->SetColor(1.0, 1.0, 1.0);
textActor->SetMapper(labeledMapper);
/// End Label ///
normals1->SetInputConnection(geometry1->GetOutputPort());
modelXfer->SetColorSpaceToDiverging();
modelXfer->AddRGBPoint(0.08, 0.138094, 0.241093, 0.709102);
modelXfer->AddRGBPoint(0.18, 0.672801, 0.140795, 0.126604);
modelXfer->SetScaleToLinear();
modelXfer->Build();
modelMapper->SetInputConnection(normals1->GetOutputPort());
modelMapper->SelectColorArray("AsH3");
modelMapper->ScalarVisibilityOn();
modelMapper->SetLookupTable(modelXfer);
modelMapper->UseLookupTableScalarRangeOn();
modelMapper->SetColorModeToMapScalars();
modelMapper->ScalarVisibilityOn();
modelMapper->SetScalarModeToUsePointFieldData();
modelActor->SetMapper(modelMapper);
contourXfer->SetColorSpaceToRGB();
contourXfer->AddRGBPoint(293.0, 0.0, 0.666667, 0.0);
contourXfer->AddRGBPoint(913.5, 0.67451, 0.443137, 0.113725);
contourXfer->SetScaleToLinear();
contourXfer->Build();
normals2->SetInputConnection(geometry2->GetOutputPort());
contourMapper->SetInputConnection(normals2->GetOutputPort());
contourMapper->SelectColorArray("Temp");
contourMapper->ScalarVisibilityOn();
contourMapper->SetLookupTable(contourXfer);
contourMapper->UseLookupTableScalarRangeOn();
contourMapper->SetColorModeToMapScalars();
contourMapper->ScalarVisibilityOn();
contourMapper->SetScalarModeToUsePointFieldData();
contourActor->SetMapper(contourMapper);
modelActor->SetPosition(0.05, -0.05, 0.0);
renderer->AddActor(contourActor);
renderer->AddActor(modelActor);
renderer->AddActor(textActor);
renWin->SetSize(600, 600);
renWin->AddRenderer(renderer);
renderer->SetBackground(1.0, 1.0, 1.0);
iren->SetRenderWindow(renWin);
renderer->GetActiveCamera()->SetFocalPoint(-9.25157, 7.70629, 3.69546);
renderer->GetActiveCamera()->SetPosition(24.9979, -27.946, -4.03877);
renderer->GetActiveCamera()->SetViewAngle(30);
renderer->GetActiveCamera()->SetViewUp(0.248261, 0.427108, -8.869451);
renWin->Render();
renderer->ResetCamera();
renderer->ResetCamera();
renderer->ResetCamera();
vtkSmartPointer<vtkWindowToImageFilter> capture = vtkSmartPointer<vtkWindowToImageFilter>::New();
//capture->SetInput(renWin);
//char buffer[1024];
//vtkSmartPointer<vtkTIFFWriter> tiffWriter = vtkSmartPointer<vtkTIFFWriter>::New();
//tiffWriter->SetInputConnection(capture->GetOutputPort());
//tiffWriter->SetCompressionToNoCompression();
int j = 0;
/*for(j = 0; j < 20; j++)
{
renderer->GetActiveCamera()->Azimuth(-0.5);
renWin->Render();
capture->Modified();
sprintf(buffer, "%04d.tiff", j );
tiffWriter->SetFileName(buffer);
tiffWriter->Write();
}*/
for(; j < 80; j++)
{
renderer->GetActiveCamera()->Zoom(1.01);
renWin->Render();
//capture->Modified();
//sprintf(buffer, "%04d.tiff", j );
//tiffWriter->SetFileName(buffer);
//tiffWriter->Write();
}
for(; j < 400; j++)
{
renderer->GetActiveCamera()->Azimuth(-0.25);
renWin->Render();
//capture->Modified();
//sprintf(buffer, "%04d.tiff", j );
//tiffWriter->SetFileName(buffer);
//tiffWriter->Write();
}
int retVal = vtkRegressionTestImage( renWin );
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
return !retVal;
}
<commit_msg>ENH: shrink size of test window.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: TestLabelPlacerExodus.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME Test of vtkLabelPlacer
// .SECTION Description
// this program tests vtkLabelPlacer which uses a sophisticated algorithm to
// prune labels/icons preventing them from overlapping.
#include "vtkActor.h"
#include "vtkActor2D.h"
#include "vtkCamera.h"
#include "vtkCellCenters.h"
#include "vtkCellData.h"
#include "vtkClipDataSet.h"
#include "vtkContourFilter.h"
#include "vtkColorTransferFunction.h"
#include "vtkExodusReader.h"
#include "vtkGeometryFilter.h"
#include "vtkIntArray.h"
#include "vtkLabeledDataMapper.h"
#include "vtkLabelHierarchy.h"
#include "vtkLabelPlacer.h"
#include "vtkLabelSizeCalculator.h"
#include "vtkLookupTable.h"
#include "vtkMath.h"
#include "vtkPlane.h"
#include "vtkPointSetToLabelHierarchy.h"
#include "vtkPoints.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
#include "vtkPolyDataMapper.h"
#include "vtkPolyDataMapper2D.h"
#include "vtkPolyDataNormals.h"
#include "vtkProperty.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkTextProperty.h"
#include "vtkTIFFWriter.h"
#include "vtkXMLPolyDataReader.h"
#include "vtkXMLPolyDataWriter.h"
#include "vtkPolyData.h"
#include "vtkImageData.h"
#include "vtkSmartPointer.h"
#include "vtkSphereSource.h"
#include "vtkStructuredGrid.h"
#include "vtkUnstructuredGrid.h"
#include "vtkRectilinearGrid.h"
#include "vtkWindowToImageFilter.h"
#include <vtkTestUtilities.h>
#include <vtkRegressionTestImage.h>
int TestLabelPlacerExodus(int argc, char *argv[])
{
int maxLevels = 5;
int targetLabels = 32;
double labelRatio = 0.05;
char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/disk_out_ref.ex2");
//int iteratorType = vtkLabelHierarchy::FULL_SORT;
int iteratorType = vtkLabelHierarchy::QUEUE;
//int iteratorType = vtkLabelHierarchy::DEPTH_FIRST;
bool showBounds = false;
vtkSmartPointer<vtkLabelSizeCalculator> labelSizeCalculator =
vtkSmartPointer<vtkLabelSizeCalculator>::New();
vtkSmartPointer<vtkLabelHierarchy> labelHierarchy =
vtkSmartPointer<vtkLabelHierarchy>::New();
vtkSmartPointer<vtkLabelPlacer> labelPlacer =
vtkSmartPointer<vtkLabelPlacer>::New();
vtkSmartPointer<vtkPointSetToLabelHierarchy> pointSetToLabelHierarchy =
vtkSmartPointer<vtkPointSetToLabelHierarchy>::New();
vtkSmartPointer<vtkExodusReader> exoReader =
vtkSmartPointer<vtkExodusReader>::New();
vtkSmartPointer<vtkPlane> plane1 = vtkSmartPointer<vtkPlane>::New();
vtkSmartPointer<vtkPlane> plane2 = vtkSmartPointer<vtkPlane>::New();
vtkSmartPointer<vtkClipDataSet> clip1 = vtkSmartPointer<vtkClipDataSet>::New();
vtkSmartPointer<vtkClipDataSet> clip2 = vtkSmartPointer<vtkClipDataSet>::New();
plane1->SetNormal(0.874613683283037, 0.0, -0.484820487411659);
plane2->SetNormal(-0.483077342911335, 0.875577684026794, 0.0);
vtkSmartPointer<vtkContourFilter> contour = vtkSmartPointer<vtkContourFilter>::New();
vtkSmartPointer<vtkColorTransferFunction> contourXfer = vtkSmartPointer<vtkColorTransferFunction>::New();
vtkSmartPointer<vtkColorTransferFunction> modelXfer = vtkSmartPointer<vtkColorTransferFunction>::New();
vtkSmartPointer<vtkPolyDataMapper> modelMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
vtkSmartPointer<vtkPolyDataMapper> contourMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
vtkSmartPointer<vtkActor> modelActor = vtkSmartPointer<vtkActor>::New();
vtkSmartPointer<vtkActor> contourActor = vtkSmartPointer<vtkActor>::New();
vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renWin = vtkSmartPointer<vtkRenderWindow>::New();
vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkSmartPointer<vtkRenderWindowInteractor>::New();
vtkSmartPointer<vtkLabeledDataMapper> labeledMapper =
vtkSmartPointer<vtkLabeledDataMapper>::New();
vtkSmartPointer<vtkActor2D> textActor = vtkSmartPointer<vtkActor2D>::New();
vtkSmartPointer<vtkCellCenters> cellCenters = vtkSmartPointer<vtkCellCenters>::New();
vtkSmartPointer<vtkGeometryFilter> geometry1 = vtkSmartPointer<vtkGeometryFilter>::New();
vtkSmartPointer<vtkGeometryFilter> geometry2 = vtkSmartPointer<vtkGeometryFilter>::New();
vtkSmartPointer<vtkPolyDataNormals> normals1 = vtkSmartPointer<vtkPolyDataNormals>::New();
vtkSmartPointer<vtkPolyDataNormals> normals2 = vtkSmartPointer<vtkPolyDataNormals>::New();
normals1->SplittingOn();
normals1->ConsistencyOn();
normals1->NonManifoldTraversalOn();
normals2->SplittingOn();
normals2->ConsistencyOn();
normals2->NonManifoldTraversalOn();
//xmlPolyDataReader->SetFileName( fname );
exoReader->SetFileName( fname );
//exoReader->SetPointArrayStatus("Temp", 1);
exoReader->SetAllPointArrayStatus(1);
delete [] fname;
contour->SetInputConnection(exoReader->GetOutputPort());
contour->ComputeNormalsOn();
contour->ComputeGradientsOn();
contour->ComputeScalarsOn();
contour->SetValue(0, 362);
contour->SetValue(1, 500);
contour->SetValue(2, 638);
contour->SetValue(3, 775);
contour->SetValue(4, 844);
contour->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, "Temp");
clip1->SetInputConnection(exoReader->GetOutputPort());
clip1->SetClipFunction(plane1);
clip1->InsideOutOn();
geometry1->SetInputConnection(clip1->GetOutputPort());
clip2->SetInputConnection(contour->GetOutputPort());
clip2->SetClipFunction(plane2);
geometry2->SetInputConnection(clip2->GetOutputPort());
cellCenters->SetInputConnection(clip2->GetOutputPort());
cellCenters->Update();
//cellCenters->GetOutput()->Print(cout);
//geometry2->Update();
//geometry2->GetOutput()->Print(cout);
int numTemps = cellCenters->GetOutput()->GetNumberOfPoints();
vtkSmartPointer<vtkIntArray> priority = vtkSmartPointer<vtkIntArray>::New();
priority->SetName("Priority");
priority->SetNumberOfComponents(1);
priority->SetNumberOfValues(numTemps);
for(int i = 0; i < numTemps; i++)
{
priority->SetValue(i, static_cast<int>(vtkMath::Random(0.0, 5.0)));
}
geometry2->Update();
vtkSmartPointer<vtkPolyData> temp = vtkSmartPointer<vtkPolyData>::New();
temp->ShallowCopy(cellCenters->GetOutput());
temp->GetPointData()->AddArray(priority);
//temp->GetPointData()->AddArray(geometry2->GetOutput()->GetPointData()->GetArray("Temp"));
//temp-
//temp->Print(cout);
/// Label ///
labelSizeCalculator->SetInput(temp);
labelSizeCalculator->GetFontProperty()->SetFontSize( 14 );
labelSizeCalculator->GetFontProperty()->SetFontFamily( vtkTextProperty::GetFontFamilyFromString( "Arial" ) );
labelSizeCalculator->GetFontProperty()->ShadowOn();
labelSizeCalculator->SetInputArrayToProcess( 0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, "PedigreeElementId" );
pointSetToLabelHierarchy->AddInputConnection(labelSizeCalculator->GetOutputPort());
pointSetToLabelHierarchy->SetInputArrayToProcess( 0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, "Priority" );
pointSetToLabelHierarchy->SetInputArrayToProcess( 1, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, "LabelSize" );
pointSetToLabelHierarchy->SetInputArrayToProcess( 2, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, "PedigreeElementId" );
pointSetToLabelHierarchy->SetMaximumDepth( maxLevels );
pointSetToLabelHierarchy->SetTargetLabelCount( targetLabels );
labelPlacer->SetInputConnection( pointSetToLabelHierarchy->GetOutputPort() );
labelPlacer->SetIteratorType( iteratorType );
labelPlacer->SetOutputTraversedBounds( showBounds );
labelPlacer->SetRenderer( renderer );
labelPlacer->SetMaximumLabelFraction( labelRatio );
labelPlacer->UseDepthBufferOn();
labeledMapper->SetInputConnection(labelPlacer->GetOutputPort());
labeledMapper->SetLabelTextProperty(labelSizeCalculator->GetFontProperty());
labeledMapper->SetFieldDataName("LabelText");
labeledMapper->SetLabelModeToLabelFieldData();
labeledMapper->GetLabelTextProperty()->SetColor(1.0, 1.0, 1.0);
textActor->SetMapper(labeledMapper);
/// End Label ///
normals1->SetInputConnection(geometry1->GetOutputPort());
modelXfer->SetColorSpaceToDiverging();
modelXfer->AddRGBPoint(0.08, 0.138094, 0.241093, 0.709102);
modelXfer->AddRGBPoint(0.18, 0.672801, 0.140795, 0.126604);
modelXfer->SetScaleToLinear();
modelXfer->Build();
modelMapper->SetInputConnection(normals1->GetOutputPort());
modelMapper->SelectColorArray("AsH3");
modelMapper->ScalarVisibilityOn();
modelMapper->SetLookupTable(modelXfer);
modelMapper->UseLookupTableScalarRangeOn();
modelMapper->SetColorModeToMapScalars();
modelMapper->ScalarVisibilityOn();
modelMapper->SetScalarModeToUsePointFieldData();
modelActor->SetMapper(modelMapper);
contourXfer->SetColorSpaceToRGB();
contourXfer->AddRGBPoint(293.0, 0.0, 0.666667, 0.0);
contourXfer->AddRGBPoint(913.5, 0.67451, 0.443137, 0.113725);
contourXfer->SetScaleToLinear();
contourXfer->Build();
normals2->SetInputConnection(geometry2->GetOutputPort());
contourMapper->SetInputConnection(normals2->GetOutputPort());
contourMapper->SelectColorArray("Temp");
contourMapper->ScalarVisibilityOn();
contourMapper->SetLookupTable(contourXfer);
contourMapper->UseLookupTableScalarRangeOn();
contourMapper->SetColorModeToMapScalars();
contourMapper->ScalarVisibilityOn();
contourMapper->SetScalarModeToUsePointFieldData();
contourActor->SetMapper(contourMapper);
modelActor->SetPosition(0.05, -0.05, 0.0);
renderer->AddActor(contourActor);
renderer->AddActor(modelActor);
renderer->AddActor(textActor);
renWin->SetSize(300, 300);
renWin->AddRenderer(renderer);
renderer->SetBackground(1.0, 1.0, 1.0);
iren->SetRenderWindow(renWin);
renderer->GetActiveCamera()->SetFocalPoint(-9.25157, 7.70629, 3.69546);
renderer->GetActiveCamera()->SetPosition(24.9979, -27.946, -4.03877);
renderer->GetActiveCamera()->SetViewAngle(30);
renderer->GetActiveCamera()->SetViewUp(0.248261, 0.427108, -8.869451);
renWin->Render();
renderer->ResetCamera();
renderer->ResetCamera();
renderer->ResetCamera();
vtkSmartPointer<vtkWindowToImageFilter> capture = vtkSmartPointer<vtkWindowToImageFilter>::New();
//capture->SetInput(renWin);
//char buffer[1024];
//vtkSmartPointer<vtkTIFFWriter> tiffWriter = vtkSmartPointer<vtkTIFFWriter>::New();
//tiffWriter->SetInputConnection(capture->GetOutputPort());
//tiffWriter->SetCompressionToNoCompression();
int j = 0;
/*for(j = 0; j < 20; j++)
{
renderer->GetActiveCamera()->Azimuth(-0.5);
renWin->Render();
capture->Modified();
sprintf(buffer, "%04d.tiff", j );
tiffWriter->SetFileName(buffer);
tiffWriter->Write();
}*/
for(; j < 80; j++)
{
renderer->GetActiveCamera()->Zoom(1.01);
renWin->Render();
//capture->Modified();
//sprintf(buffer, "%04d.tiff", j );
//tiffWriter->SetFileName(buffer);
//tiffWriter->Write();
}
for(; j < 400; j++)
{
renderer->GetActiveCamera()->Azimuth(-0.25);
renWin->Render();
//capture->Modified();
//sprintf(buffer, "%04d.tiff", j );
//tiffWriter->SetFileName(buffer);
//tiffWriter->Write();
}
int retVal = vtkRegressionTestImage( renWin );
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
return !retVal;
}
<|endoftext|>
|
<commit_before>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.
This file is part of Navitia,
the software to build cool stuff with public transport.
Hope you'll enjoy and contribute to this project,
powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
a non ending quest to the responsive locomotion way of traveling!
LICENCE: 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/>.
Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE test_ed
#include <boost/test/unit_test.hpp>
#include "ed/build_helper.h"
#include "type/type.h"
#include "tests/utils_test.h"
#include "time_tables/route_schedules.h"
//for more concice test
static pt::ptime d(std::string str) {
return boost::posix_time::from_iso_string(str);
}
/*
Wanted schedules:
VJ1 VJ2 VJ3 VJ4
A 8h00 8h05
B 8h10 8h20 8h25
C 8h05
D 9h30 9h35
But the thermometer algorithm is buggy, is doesn't give the shorest common superstring..
So, actually we have this schedule
VJ1
C
D
A 8h
B 8h10
D
With VJ1, and VJ2, we ensure that we are no more comparing the two first jpp of
each VJ, but we have a more human order.
VJ2 and VJ3, is a basic test.
The difficulty with VJ4 comes when we have to compare it to VJ1.
When comparing VJ1 and VJ4, we compare VJ1(stopC) with VJ4(stopD)
and when we compare VJ4 and VJ1, we compare VJ4(stopB) with VJ1(stopC).
*/
struct route_schedule_fixture {
ed::builder b = {"20120614"};
route_schedule_fixture() {
const std::string a_name = "stopA",
b_name = "stopB",
c_name = "stopC",
d_name = "stopD";
b.vj("A", "1111111", "", true, "1", "1", "JP1")(c_name, 8*3600 + 5*60)(d_name, 9*3600 + 30*60);
b.vj("A", "1111111", "", true, "2", "2", "JP2")(a_name, 8*3600)(b_name, 8*3600 + 10*60);
b.vj("A", "1111111", "", true, "3", "3", "JP2")(a_name, 8*3600 + 5*60)(b_name, 8*3600 + 20*60);
b.vj("A", "1111111", "", true, "4", "4", "JP3")(b_name, 8*3600+25*60)(d_name, 9*3600 + 35*60);
b.finish();
b.data->pt_data->index();
b.data->build_raptor();
boost::gregorian::date begin = boost::gregorian::date_from_iso_string("20120613");
boost::gregorian::date end = boost::gregorian::date_from_iso_string("20120630");
b.data->meta->production_date = boost::gregorian::date_period(begin, end);
}
};
BOOST_FIXTURE_TEST_CASE(test1, route_schedule_fixture) {
pbnavitia::Response resp = navitia::timetables::route_schedule("line.uri=A", boost::optional<const std::string>(), {}, d("20120615T070000"), 86400, 100,
1, 3, 10, 0, *(b.data), false, false);
BOOST_REQUIRE_EQUAL(resp.route_schedules().size(), 1);
pbnavitia::RouteSchedule route_schedule = resp.route_schedules(0);
auto get_vj = [](pbnavitia::RouteSchedule r, int i) {
return r.table().headers(i).pt_display_informations().uris().vehicle_journey();
};
BOOST_REQUIRE_EQUAL(get_vj(route_schedule, 0), "1");
BOOST_REQUIRE_EQUAL(get_vj(route_schedule, 1), "2");
BOOST_REQUIRE_EQUAL(get_vj(route_schedule, 2), "3");
BOOST_REQUIRE_EQUAL(get_vj(route_schedule, 3), "4");
}
BOOST_FIXTURE_TEST_CASE(test_max_nb_stop_times, route_schedule_fixture) {
pbnavitia::Response resp = navitia::timetables::route_schedule("line.uri=A", boost::optional<const std::string>(), {}, d("20120615T070000"), 86400, 0,
1, 3, 10, 0, *(b.data), false, false);
BOOST_REQUIRE_EQUAL(resp.route_schedules().size(), 1);
pbnavitia::RouteSchedule route_schedule = resp.route_schedules(0);
BOOST_REQUIRE_EQUAL(route_schedule.table().headers().size(), 0);
}
<commit_msg>Timetable: add unit test on calendar filter for route_schedules<commit_after>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.
This file is part of Navitia,
the software to build cool stuff with public transport.
Hope you'll enjoy and contribute to this project,
powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
a non ending quest to the responsive locomotion way of traveling!
LICENCE: 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/>.
Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE test_ed
#include <boost/test/unit_test.hpp>
#include "ed/build_helper.h"
#include "type/type.h"
#include "tests/utils_test.h"
#include "time_tables/route_schedules.h"
struct logger_initialized {
logger_initialized() { init_logger(); }
};
BOOST_GLOBAL_FIXTURE( logger_initialized )
//for more concice test
static pt::ptime d(std::string str) {
return boost::posix_time::from_iso_string(str);
}
/*
Wanted schedules:
VJ1 VJ2 VJ3 VJ4
A 8h00 8h05
B 8h10 8h20 8h25
C 8h05
D 9h30 9h35
But the thermometer algorithm is buggy, is doesn't give the shorest common superstring..
So, actually we have this schedule
VJ1
C
D
A 8h
B 8h10
D
With VJ1, and VJ2, we ensure that we are no more comparing the two first jpp of
each VJ, but we have a more human order.
VJ2 and VJ3, is a basic test.
The difficulty with VJ4 comes when we have to compare it to VJ1.
When comparing VJ1 and VJ4, we compare VJ1(stopC) with VJ4(stopD)
and when we compare VJ4 and VJ1, we compare VJ4(stopB) with VJ1(stopC).
*/
struct route_schedule_fixture {
ed::builder b = {"20120614"};
route_schedule_fixture() {
const std::string a_name = "stopA",
b_name = "stopB",
c_name = "stopC",
d_name = "stopD";
b.vj("A", "1111111", "", true, "1", "1", "JP1")(c_name, 8*3600 + 5*60)(d_name, 9*3600 + 30*60);
b.vj("A", "1111111", "", true, "2", "2", "JP2")(a_name, 8*3600)(b_name, 8*3600 + 10*60);
b.vj("A", "1111111", "", true, "3", "3", "JP2")(a_name, 8*3600 + 5*60)(b_name, 8*3600 + 20*60);
b.vj("A", "1111111", "", true, "4", "4", "JP3")(b_name, 8*3600+25*60)(d_name, 9*3600 + 35*60);
b.finish();
b.data->pt_data->index();
b.data->build_raptor();
boost::gregorian::date begin = boost::gregorian::date_from_iso_string("20120613");
boost::gregorian::date end = boost::gregorian::date_from_iso_string("20120630");
b.data->meta->production_date = boost::gregorian::date_period(begin, end);
}
};
BOOST_FIXTURE_TEST_CASE(test1, route_schedule_fixture) {
pbnavitia::Response resp = navitia::timetables::route_schedule("line.uri=A", {}, {}, d("20120615T070000"), 86400, 100,
1, 3, 10, 0, *(b.data), false, false);
BOOST_REQUIRE_EQUAL(resp.route_schedules().size(), 1);
pbnavitia::RouteSchedule route_schedule = resp.route_schedules(0);
auto get_vj = [](pbnavitia::RouteSchedule r, int i) {
return r.table().headers(i).pt_display_informations().uris().vehicle_journey();
};
BOOST_REQUIRE_EQUAL(get_vj(route_schedule, 0), "1");
BOOST_REQUIRE_EQUAL(get_vj(route_schedule, 1), "2");
BOOST_REQUIRE_EQUAL(get_vj(route_schedule, 2), "3");
BOOST_REQUIRE_EQUAL(get_vj(route_schedule, 3), "4");
}
BOOST_FIXTURE_TEST_CASE(test_max_nb_stop_times, route_schedule_fixture) {
pbnavitia::Response resp = navitia::timetables::route_schedule("line.uri=A", {}, {}, d("20120615T070000"), 86400, 0,
1, 3, 10, 0, *(b.data), false, false);
BOOST_REQUIRE_EQUAL(resp.route_schedules().size(), 1);
pbnavitia::RouteSchedule route_schedule = resp.route_schedules(0);
BOOST_REQUIRE_EQUAL(route_schedule.table().headers().size(), 0);
}
/*
We have 3 vehicle journeys VJ5, VJ6, VJ7 and 3 stops S1, S2, S3 :
VJ5 VJ6 VJ7
S1 10:00 11:00 13:00
S2 10:30 11:30 13:37
s3 11:00 12:00 14:00
We have 4 calendars, C1, C2, C3, C4 :
- C1 : week (monday to friday),
- C2 : week end,
- C3 : holiday (monday to sunday during holidays),
- C4 : random calendar nobody uses.
Each vehicle_journey has its respective meta_vj : MVJ5, MVJ6, MVJ7.
We have the following associations :
- MVJ5 => C1,C2
- MVJ6 => C2,C3
- MVJ7 => ∅
*/
struct route_schedule_calendar_fixture {
ed::builder b = {"20120614"};
navitia::type::Calendar *c1, *c2, *c3, *c4;
navitia::type::VehicleJourney *vj5, *vj6, *vj7;
route_schedule_calendar_fixture() {
const std::string S1_name = "S1",
S2_name = "S2",
S3_name = "S3";
boost::gregorian::date begin = boost::gregorian::date_from_iso_string("20120613");
boost::gregorian::date end = boost::gregorian::date_from_iso_string("20120630");
vj5 = b.vj("B", "1111111", "", true, "VJ5", "MVJ5", "JP4")(S1_name, 10*3600)(S2_name, 10*3600 + 30*60)(S3_name, 11*3600).vj;
vj6 = b.vj("B", "1111111", "", true, "VJ6", "MVJ6", "JP4")(S1_name, 11*3600)(S2_name, 11*3600 + 30*60)(S3_name, 12*3600).vj;
vj7 = b.vj("B", "1111111", "", true, "VJ7", "MVJ7", "JP4")(S1_name, 13*3600)(S2_name, 13*3600 + 37*60)(S3_name, 14*3600).vj;
c1 = new navitia::type::Calendar(begin);
c1->uri = "C1";
c1->active_periods.push_back({begin, end});
c1->week_pattern = std::bitset<7>("1111100");
c2 = new navitia::type::Calendar(begin);
c2->uri = "C2";
c2->active_periods.push_back({begin, end});
c2->week_pattern = std::bitset<7>("0000011");
c3 = new navitia::type::Calendar(begin);
c3->uri = "C3";
c3->active_periods.push_back({begin, end});
c3->week_pattern = std::bitset<7>("1111111");
c4 = new navitia::type::Calendar(begin);
c4->uri = "C4";
c4->active_periods.push_back({begin, end});
c4->week_pattern = std::bitset<7>("0000000");
navitia::type::AssociatedCalendar a1;
a1.calendar = c1;
navitia::type::AssociatedCalendar a2;
a1.calendar = c2;
navitia::type::AssociatedCalendar a3;
a1.calendar = c3;
b.get_or_create_metavj("MVJ5")->associated_calendars.insert({c1->uri, &a1});
b.get_or_create_metavj("MVJ5")->associated_calendars.insert({c2->uri, &a2});
b.get_or_create_metavj("MVJ6")->associated_calendars.insert({c2->uri, &a2});
b.get_or_create_metavj("MVJ6")->associated_calendars.insert({c3->uri, &a3});
b.finish();
b.data->pt_data->index();
b.data->build_raptor();
b.data->meta->production_date = boost::gregorian::date_period(begin, end);
}
std::string get_vj(pbnavitia::RouteSchedule r, int i) {
return r.table().headers(i).pt_display_informations().uris().vehicle_journey();
}
void check_calendar_results(boost::optional<const std::string> calendar, std::vector<std::string> expected_vjs) {
pbnavitia::Response resp = navitia::timetables::route_schedule("line.uri=B", calendar, {}, d("20120615T070000"), 86400, 100,
1, 3, 10, 0, *(b.data), false, false);
BOOST_REQUIRE_EQUAL(resp.route_schedules().size(), 1);
pbnavitia::RouteSchedule route_schedule = resp.route_schedules(0);
BOOST_REQUIRE_EQUAL(route_schedule.table().headers_size(), expected_vjs.size());
for(int i = 0 ; i < route_schedule.table().headers_size() ; i++) {
BOOST_REQUIRE_EQUAL(get_vj(route_schedule, i), expected_vjs[i]);
}
}
};
BOOST_FIXTURE_TEST_CASE(test_calendar_filter, route_schedule_calendar_fixture) {
// No filter, all 3 VJs expected
check_calendar_results({}, {vj5->uri, vj6->uri, vj7->uri});
// For each calendar only the VJs explicitly linked to it expected
check_calendar_results(c1->uri, {vj5->uri});
check_calendar_results(c2->uri, {vj5->uri, vj6->uri});
check_calendar_results(c3->uri, {vj6->uri});
// No results for calendar C4
check_calendar_results(c4->uri, {});
}
<|endoftext|>
|
<commit_before>//
//#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <ctime>
#include <algorithm>
#include <cmath>
#include "GPIOClass.h"
using namespace std;
void Pulse(GPIOClass* pin, double cycles);
void Wait(double seconds);
clock_t timer;
double time_to_complete;
double resolution = CLOCKS_PER_SEC/10;
#define PI 4*atan(1)
int main (int argc, char *argv[]) {
string type = argv[1];
transform(type.begin(), type.end(), type.begin(), :: tolower);
// lets assume that the way to run this is
// pwm.exe [rising/falling/sine/constant]
if (argc != 2) {
cout << "Usage: pwm [rising/falling/sine/constant/blink]" << endl;
return -1;
}
while (time_to_complete <= 0) {
cout << "Input How Long To Run (in seconds)" << endl;
cin >> time_to_complete;
}
GPIOClass* out1 = new GPIOClass("4");
GPIOClass* in2 = new GPIOClass("17");
out1->export_gpio();
in2->export_gpio();
out1->setdir_gpio("out");
in2->setdir_gpio("in");
cout << "Pins are setup." << endl;
cout << "resolution of cpu" << CLOCKS_PER_SEC << endl;
// avoiding flickering will be at 100hz
// aka turn on and off 100 times a sec
// a cycle of 0 is off
// a cycle of 100 is on
if (type == "rising") {
clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
double t = time_to_complete;
while (clock() < finish) {
// pulse for however long we need to to achieve brightness.
if(t == 0){
t = 1;
}
else{
t -=(1/resolution);
}
//Pulse(out1, sin((2PI/2) * abs(1/t)));
//Wait(sin((PI/2) * abs(1/t)));
cout << sin((2*PI)/t) << endl;
cout << "this is t" << t << endl;
Pulse(out1, 1/resolution);
Wait(sin((2*PI)/t));
}
}
if (type == "falling") {
}
if (type == "sine") {
clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
while (clock() < finish) {
// pulse for however long we need to to achieve brightness.
for (double i = 0; i < 1; i += resolution) {
Pulse(out1, 1/resolution);
cout << sin(i)/resolution << endl;
Wait(sin(i)/resolution);
}
}
}
if (type == "constant") {
out1->setval_gpio("1"); // turn the pin on
Wait(time_to_complete); // sleep for number of cycles / 1/100 sec
//cout << "Waiting during pulse" << endl;
out1->setval_gpio("0"); // turn the pin off
}
if (type == "blink") { // aka. TESTR
clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
while (clock() < finish) {
// pulse for however long we need to to achieve brightness.
Pulse(out1, 1/resolution);
Wait(4/resolution);
}
}
cout << "Done." << endl;
}
//1 cycle is 1/100th of a second
//100 cycles is 1 sec
void Pulse(GPIOClass* pin, double cycles) {
bool running = true;
while (running) {
pin->setval_gpio("1"); // turn the pin on
Wait(cycles / resolution); // sleep for number of cycles / 1/100 sec
//cout << "Waiting during pulse" << endl;
pin->setval_gpio("0"); // turn the pin off
running = false; // this is unnessesary but could be useful if modified a bit.
}
}
void Wait ( double seconds )
{
clock_t endwait;
endwait = clock () + seconds * CLOCKS_PER_SEC ;
while (clock() < endwait) {}
}
<commit_msg>Update pwm.cpp<commit_after>//
//#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <ctime>
#include <algorithm>
#include <cmath>
#include "GPIOClass.h"
using namespace std;
void Pulse(GPIOClass* pin, double cycles);
void Wait(double seconds);
clock_t timer;
double time_to_complete;
double resolution = CLOCKS_PER_SEC/10;
#define PI 4*atan(1)
int main (int argc, char *argv[]) {
string type = argv[1];
transform(type.begin(), type.end(), type.begin(), :: tolower);
// lets assume that the way to run this is
// pwm.exe [rising/falling/sine/constant]
if (argc != 2) {
cout << "Usage: pwm [rising/falling/sine/constant/blink]" << endl;
return -1;
}
while (time_to_complete <= 0) {
cout << "Input How Long To Run (in seconds)" << endl;
cin >> time_to_complete;
}
GPIOClass* out1 = new GPIOClass("4");
GPIOClass* in2 = new GPIOClass("17");
out1->export_gpio();
in2->export_gpio();
out1->setdir_gpio("out");
in2->setdir_gpio("in");
cout << "Pins are setup." << endl;
cout << "resolution of cpu" << CLOCKS_PER_SEC << endl;
// avoiding flickering will be at 100hz
// aka turn on and off 100 times a sec
// a cycle of 0 is off
// a cycle of 100 is on
if (type == "rising") {
clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
double t = time_to_complete;
while (clock() < finish) {
// pulse for however long we need to to achieve brightness.
if(t == 0){
t = time_to_complete;
}
else{
t -=;
}
//Pulse(out1, sin((2PI/2) * abs(1/t)));
//Wait(sin((PI/2) * abs(1/t)));
cout << sin((2*PI)/t) << endl;
cout << "this is t" << t << endl;
Pulse(out1, 1/resolution);
Wait(sin((2*PI)/t));
}
}
if (type == "falling") {
}
if (type == "sine") {
clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
while (clock() < finish) {
// pulse for however long we need to to achieve brightness.
for (double i = 0; i < 1; i += resolution) {
Pulse(out1, 1/resolution);
cout << sin(i)/resolution << endl;
Wait(sin(i)/resolution);
}
}
}
if (type == "constant") {
out1->setval_gpio("1"); // turn the pin on
Wait(time_to_complete); // sleep for number of cycles / 1/100 sec
//cout << "Waiting during pulse" << endl;
out1->setval_gpio("0"); // turn the pin off
}
if (type == "blink") { // aka. TESTR
clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
while (clock() < finish) {
// pulse for however long we need to to achieve brightness.
Pulse(out1, 1/resolution);
Wait(4/resolution);
}
}
cout << "Done." << endl;
}
//1 cycle is 1/100th of a second
//100 cycles is 1 sec
void Pulse(GPIOClass* pin, double cycles) {
bool running = true;
while (running) {
pin->setval_gpio("1"); // turn the pin on
Wait(cycles / resolution); // sleep for number of cycles / 1/100 sec
//cout << "Waiting during pulse" << endl;
pin->setval_gpio("0"); // turn the pin off
running = false; // this is unnessesary but could be useful if modified a bit.
}
}
void Wait ( double seconds )
{
clock_t endwait;
endwait = clock () + seconds * CLOCKS_PER_SEC ;
while (clock() < endwait) {}
}
<|endoftext|>
|
<commit_before><commit_msg>Revert "Fix n#653688"<commit_after><|endoftext|>
|
<commit_before>//===----------------------------------------------------------------------===//
//
// Peloton
//
// runtime_state.cpp
//
// Identification: src/codegen/runtime_state.cpp
//
// Copyright (c) 2015-17, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "codegen/runtime_state.h"
#include "codegen/vector.h"
namespace peloton {
namespace codegen {
// Constructor
RuntimeState::RuntimeState() : constructed_type_(nullptr) {}
// Register some state of the given type and with the given name. The last
// argument indicates whether this state is local (i.e., lives on the stack) or
// whether the requesting operator wants to manage the memory.
RuntimeState::StateID RuntimeState::RegisterState(std::string name,
llvm::Type *type,
bool is_on_stack) {
PL_ASSERT(constructed_type_ == nullptr);
RuntimeState::StateID state_id = state_slots_.size();
RuntimeState::StateInfo state_info;
state_info.name = name;
state_info.type = type;
state_info.local = is_on_stack;
state_slots_.push_back(state_info);
return state_id;
}
llvm::Value *RuntimeState::LoadStatePtr(CodeGen &codegen,
RuntimeState::StateID state_id) const {
// At this point, the runtime state type must have been finalized. Otherwise,
// it'd be impossible for us to index into it because the type would be
// incomplete.
PL_ASSERT(constructed_type_ != nullptr);
PL_ASSERT(state_id < state_slots_.size());
auto &state_info = state_slots_[state_id];
PL_ASSERT(!state_info.local);
// We index into the runtime state to get a pointer to the state
std::string ptr_name{state_info.name + "Ptr"};
llvm::Value *runtime_state = codegen.GetState();
llvm::Value *state_ptr = codegen->CreateConstInBoundsGEP2_32(
constructed_type_, runtime_state, 0, state_info.index, ptr_name);
return state_ptr;
}
llvm::Value *RuntimeState::LoadStateValue(CodeGen &codegen,
RuntimeState::StateID state_id) const {
auto &state_info = state_slots_[state_id];
if (state_info.local) {
return state_info.val;
}
llvm::Value *state_ptr = LoadStatePtr(codegen, state_id);
llvm::Value *state = codegen->CreateLoad(state_ptr);
#ifndef NDEBUG
PL_ASSERT(state->getType() == state_info.type);
if (state->getType()->isStructTy()) {
PL_ASSERT(state_info.type->isStructTy());
auto *our_type = llvm::cast<llvm::StructType>(state_info.type);
auto *ret_type = llvm::cast<llvm::StructType>(state->getType());
PL_ASSERT(ret_type->isLayoutIdentical(our_type));
}
#endif
return state;
}
llvm::Type *RuntimeState::FinalizeType(CodeGen &codegen) {
// Check if we've already constructed the type
if (constructed_type_ != nullptr) {
return constructed_type_;
}
// Construct a type capturing all non-local state
std::vector<llvm::Type *> types;
for (uint32_t i = 0, index = 0; i < state_slots_.size(); i++) {
if (!state_slots_[i].local) {
// We set the index in the overall state where this instance is found
state_slots_[i].index = index++;
types.push_back(state_slots_[i].type);
}
}
constructed_type_ =
llvm::StructType::create(codegen.GetContext(), types, "RuntimeState");
return constructed_type_;
}
void RuntimeState::CreateLocalState(CodeGen &codegen) {
for (auto &state_info : state_slots_) {
if (state_info.local) {
if (auto *arr_type = llvm::dyn_cast<llvm::ArrayType>(state_info.type)) {
// Do the stack allocation of the array
llvm::AllocaInst *arr = codegen->CreateAlloca(
arr_type->getArrayElementType(),
codegen.Const32(arr_type->getArrayNumElements()));
// Set the alignment
arr->setAlignment(Vector::kDefaultVectorAlignment);
// Zero-out the allocated space
uint64_t sz = codegen.SizeOf(state_info.type);
codegen->CreateMemSet(arr, codegen.Const8(0), sz, arr->getAlignment());
state_info.val = arr;
} else {
state_info.val = codegen->CreateAlloca(state_info.type);
}
// Set the name of the local state to what the client wants
state_info.val->setName(state_info.name);
}
}
}
} // namespace codegen
} // namespace peloton<commit_msg>Formatting<commit_after>//===----------------------------------------------------------------------===//
//
// Peloton
//
// runtime_state.cpp
//
// Identification: src/codegen/runtime_state.cpp
//
// Copyright (c) 2015-17, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "codegen/runtime_state.h"
#include "codegen/vector.h"
namespace peloton {
namespace codegen {
// Constructor
RuntimeState::RuntimeState() : constructed_type_(nullptr) {}
// Register some state of the given type and with the given name. The last
// argument indicates whether this state is local (i.e., lives on the stack) or
// whether the requesting operator wants to manage the memory.
RuntimeState::StateID RuntimeState::RegisterState(std::string name,
llvm::Type *type,
bool is_on_stack) {
PL_ASSERT(constructed_type_ == nullptr);
RuntimeState::StateID state_id = state_slots_.size();
RuntimeState::StateInfo state_info;
state_info.name = name;
state_info.type = type;
state_info.local = is_on_stack;
state_slots_.push_back(state_info);
return state_id;
}
llvm::Value *RuntimeState::LoadStatePtr(CodeGen &codegen,
RuntimeState::StateID state_id) const {
// At this point, the runtime state type must have been finalized. Otherwise,
// it'd be impossible for us to index into it because the type would be
// incomplete.
PL_ASSERT(constructed_type_ != nullptr);
PL_ASSERT(state_id < state_slots_.size());
auto &state_info = state_slots_[state_id];
PL_ASSERT(!state_info.local);
// We index into the runtime state to get a pointer to the state
std::string ptr_name{state_info.name + "Ptr"};
llvm::Value *runtime_state = codegen.GetState();
llvm::Value *state_ptr = codegen->CreateConstInBoundsGEP2_32(
constructed_type_, runtime_state, 0, state_info.index, ptr_name);
return state_ptr;
}
llvm::Value *RuntimeState::LoadStateValue(
CodeGen &codegen, RuntimeState::StateID state_id) const {
auto &state_info = state_slots_[state_id];
if (state_info.local) {
return state_info.val;
}
llvm::Value *state_ptr = LoadStatePtr(codegen, state_id);
llvm::Value *state = codegen->CreateLoad(state_ptr);
#ifndef NDEBUG
PL_ASSERT(state->getType() == state_info.type);
if (state->getType()->isStructTy()) {
PL_ASSERT(state_info.type->isStructTy());
auto *our_type = llvm::cast<llvm::StructType>(state_info.type);
auto *ret_type = llvm::cast<llvm::StructType>(state->getType());
PL_ASSERT(ret_type->isLayoutIdentical(our_type));
}
#endif
return state;
}
llvm::Type *RuntimeState::FinalizeType(CodeGen &codegen) {
// Check if we've already constructed the type
if (constructed_type_ != nullptr) {
return constructed_type_;
}
// Construct a type capturing all non-local state
std::vector<llvm::Type *> types;
for (uint32_t i = 0, index = 0; i < state_slots_.size(); i++) {
if (!state_slots_[i].local) {
// We set the index in the overall state where this instance is found
state_slots_[i].index = index++;
types.push_back(state_slots_[i].type);
}
}
constructed_type_ =
llvm::StructType::create(codegen.GetContext(), types, "RuntimeState");
return constructed_type_;
}
void RuntimeState::CreateLocalState(CodeGen &codegen) {
for (auto &state_info : state_slots_) {
if (state_info.local) {
if (auto *arr_type = llvm::dyn_cast<llvm::ArrayType>(state_info.type)) {
// Do the stack allocation of the array
llvm::AllocaInst *arr = codegen->CreateAlloca(
arr_type->getArrayElementType(),
codegen.Const32(arr_type->getArrayNumElements()));
// Set the alignment
arr->setAlignment(Vector::kDefaultVectorAlignment);
// Zero-out the allocated space
uint64_t sz = codegen.SizeOf(state_info.type);
codegen->CreateMemSet(arr, codegen.Const8(0), sz, arr->getAlignment());
state_info.val = arr;
} else {
state_info.val = codegen->CreateAlloca(state_info.type);
}
// Set the name of the local state to what the client wants
state_info.val->setName(state_info.name);
}
}
}
} // namespace codegen
} // namespace peloton<|endoftext|>
|
<commit_before>/* You can use one of the both BSD 3-Clause License or GNU Lesser General Public License 3.0 for this source. */
/* BSD 3-Clause License:
* Copyright (c) 2013 - 2021, kazunobu watatsu.
* 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 or other materials provided with the distribution.
* Neither the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if !defined(_LINEAR_OPT_)
using std::cerr;
using std::flush;
template <typename T> SimpleVector<T> inner(const SimpleMatrix<T>& A, const SimpleVector<T>& bl, const SimpleVector<T>& bu) {
#if defined(_FLOAT_BITS_)
static const auto epsilon(T(1) >> int64_t(mybits - 1));
#else
static const auto epsilon(std::numeric_limits<T>::epsilon());
#endif
assert(A.rows() == bl.size() && A.rows() == bu.size() &&
0 < A.cols() && 0 < A.rows());
// cout << A << endl << b << endl << c.transpose() << endl;
cerr << " (" << A.rows() << ", " << A.cols() << ")";
// bu - bb == A, bl - bb == - A <=> bu - bl == 2 A
const auto bb(bu - (bu - bl) / T(2));
const auto upper(bu - bb);
SimpleMatrix<T> AA(A.rows() * 2 - 1, A.cols() + 1);
SimpleVector<T> one(AA.rows());
std::vector<std::pair<T, int> > fidx;
fidx.reserve(A.rows());
for(int i = 0; i < A.rows(); i ++) {
for(int j = 0; j < A.cols(); j ++)
AA(i, j) = A(i, j);
AA(i, A.cols()) = - bb[i];
if(upper[i] == T(0)) {
const auto n2(AA.row(i).dot(AA.row(i)));
if(n2 != T(0)) {
fidx.emplace_back(std::make_pair(- T(1), i));
AA.row(i) /= sqrt(n2);
}
} else {
AA.row(i) /= upper[i];
AA(i, A.cols()) -= T(1);
}
one[i] = T(1);
assert(isfinite(AA.row(i).dot(AA.row(i))));
if(A.rows() - 1 <= i) break;
AA.row(i + A.rows()) = - AA.row(i);
one[i + A.rows()] = T(1);
}
SimpleMatrix<T> Pt(AA.cols(), AA.rows());
for(int i = 0; i < Pt.rows(); i ++)
for(int j = 0; j < Pt.cols(); j ++)
Pt(i, j) = T(0);
std::vector<int> residue;
for(int i = 0; i < AA.cols(); i ++) {
const auto Atrowi(AA.col(i));
const auto work(Atrowi - Pt.projectionPt(Atrowi));
const auto n2(work.dot(work));
if(n2 <= epsilon) {
residue.emplace_back(i);
continue;
}
Pt.row(i) = work / sqrt(n2);
}
int ii(0);
for(int j = 0; j < Pt.cols() && ii < residue.size(); j ++) {
SimpleVector<T> ek(Pt.cols());
for(int k = 0; k < Pt.cols(); k ++)
ek[k] = j == k ? T(1) : T(0);
ek -= Pt.projectionPt(ek);
const auto n2(ek.dot(ek));
if(n2 <= epsilon) continue;
Pt.row(residue[ii ++]) = ek / sqrt(n2);
}
assert(residue.size() <= ii);
cerr << "Q" << flush;
const auto R(Pt * AA);
cerr << "R" << flush;
const auto on(Pt.projectionPt(- one));
for(int i = 0; i < on.size(); i ++)
if(T(0) < on[i])
fidx.emplace_back(std::make_pair(on[i], i));
std::sort(fidx.begin(), fidx.end());
// worst case O(mn^2) over all in this function,
// we can make this function better case it's O(n^3) but not now.
for(int n_fixed = 0, idx = 0; n_fixed < Pt.rows() - 1 && idx < fidx.size(); n_fixed ++, idx ++) {
const auto& iidx(fidx[idx].second);
const auto orth(Pt.col(iidx));
const auto norm2orth(orth.dot(orth));
// XXX error:
if(norm2orth <= epsilon) {
n_fixed --;
continue;
}
#if defined(_OPENMP)
#pragma omp parallel for schedule(static, 1)
#endif
for(int j = 0; j < Pt.cols(); j ++)
Pt.setCol(j, Pt.col(j) - orth * (Pt.col(j).dot(orth) + T(n_fixed ? 0 : 1)) / norm2orth);
}
cerr << "G" << flush;
#if defined(_WITHOUT_EIGEN_)
auto rvec(- R.solve(Pt * one));
#else
auto rvec(- R.inverse() * (Pt * one));
#endif
cerr << "I" << flush;
SimpleVector<T> rrvec(rvec.size() - 1);
// | [A, - bb == - upper] [x t] | <= epsilon 1.
for(int i = 0; i < rrvec.size(); i ++)
rrvec[i] = rvec[i] / rvec[rvec.size() - 1];
return rrvec;
}
#define _LINEAR_OPT_
#endif
<commit_msg>sign fix with logic fix.<commit_after>/* You can use one of the both BSD 3-Clause License or GNU Lesser General Public License 3.0 for this source. */
/* BSD 3-Clause License:
* Copyright (c) 2013 - 2021, kazunobu watatsu.
* 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 or other materials provided with the distribution.
* Neither the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if !defined(_LINEAR_OPT_)
using std::cerr;
using std::flush;
template <typename T> SimpleVector<T> inner(const SimpleMatrix<T>& A, const SimpleVector<T>& bl, const SimpleVector<T>& bu) {
#if defined(_FLOAT_BITS_)
static const auto epsilon(T(1) >> int64_t(mybits - 1));
#else
static const auto epsilon(std::numeric_limits<T>::epsilon());
#endif
assert(A.rows() == bl.size() && A.rows() == bu.size() &&
0 < A.cols() && 0 < A.rows());
// cout << A << endl << b << endl << c.transpose() << endl;
cerr << " (" << A.rows() << ", " << A.cols() << ")";
// bu - bb == A, bl - bb == - A <=> bu - bl == 2 A
const auto bb(bu - (bu - bl) / T(2));
const auto upper(bu - bb);
SimpleMatrix<T> AA(A.rows() * 2 - 1, A.cols() + 1);
SimpleVector<T> one(AA.rows());
std::vector<std::pair<T, int> > fidx;
fidx.reserve(A.rows());
for(int i = 0; i < A.rows(); i ++) {
for(int j = 0; j < A.cols(); j ++)
AA(i, j) = A(i, j);
AA(i, A.cols()) = bb[i];
if(upper[i] == T(0)) {
const auto n2(AA.row(i).dot(AA.row(i)));
if(n2 != T(0)) {
fidx.emplace_back(std::make_pair(- T(1), i));
AA.row(i) /= sqrt(n2);
}
} else {
AA.row(i) /= upper[i];
// N.B. [A, [-b 1]] [x t] <= {0, 1}^m, t == 1 <=>
// bl - bb t <= Ax - bb t <= bu - bb t.
AA(i, A.cols()) -= T(1);
}
one[i] = T(1);
assert(isfinite(AA.row(i).dot(AA.row(i))));
if(A.rows() - 1 <= i) break;
AA.row(i + A.rows()) = - AA.row(i);
one[i + A.rows()] = - T(1);
}
SimpleMatrix<T> Pt(AA.cols(), AA.rows());
for(int i = 0; i < Pt.rows(); i ++)
for(int j = 0; j < Pt.cols(); j ++)
Pt(i, j) = T(0);
std::vector<int> residue;
for(int i = 0; i < AA.cols(); i ++) {
const auto Atrowi(AA.col(i));
const auto work(Atrowi - Pt.projectionPt(Atrowi));
const auto n2(work.dot(work));
if(n2 <= epsilon) {
residue.emplace_back(i);
continue;
}
Pt.row(i) = work / sqrt(n2);
}
int ii(0);
for(int j = 0; j < Pt.cols() && ii < residue.size(); j ++) {
SimpleVector<T> ek(Pt.cols());
for(int k = 0; k < Pt.cols(); k ++)
ek[k] = j == k ? T(1) : T(0);
ek -= Pt.projectionPt(ek);
const auto n2(ek.dot(ek));
if(n2 <= epsilon) continue;
Pt.row(residue[ii ++]) = ek / sqrt(n2);
}
assert(residue.size() <= ii);
cerr << "Q" << flush;
const auto R(Pt * AA);
cerr << "R" << flush;
const auto on(Pt.projectionPt(- one));
for(int i = 0; i < on.size(); i ++)
if(T(0) < on[i])
fidx.emplace_back(std::make_pair(on[i], i));
std::sort(fidx.begin(), fidx.end());
// worst case O(mn^2) over all in this function,
// we can make this function better case it's O(n^3) but not now.
for(int n_fixed = 0, idx = 0; n_fixed < Pt.rows() - 1 && idx < fidx.size(); n_fixed ++, idx ++) {
const auto& iidx(fidx[idx].second);
const auto orth(Pt.col(iidx));
const auto norm2orth(orth.dot(orth));
// XXX error:
if(norm2orth <= epsilon) {
n_fixed --;
continue;
}
#if defined(_OPENMP)
#pragma omp parallel for schedule(static, 1)
#endif
for(int j = 0; j < Pt.cols(); j ++)
Pt.setCol(j, Pt.col(j) - orth * (Pt.col(j).dot(orth) + T(n_fixed ? 0 : 1)) / norm2orth);
}
cerr << "G" << flush;
#if defined(_WITHOUT_EIGEN_)
auto rvec(- R.solve(Pt * one));
#else
auto rvec(- R.inverse() * (Pt * one));
#endif
cerr << "I" << flush;
SimpleVector<T> rrvec(rvec.size() - 1);
// | [A, - bb == - upper] [x t] | <= epsilon 1.
for(int i = 0; i < rrvec.size(); i ++)
rrvec[i] = rvec[i] / rvec[rvec.size() - 1];
return rrvec;
}
#define _LINEAR_OPT_
#endif
<|endoftext|>
|
<commit_before>/*
SWARM
Copyright (C) 2012-2022 Torbjorn Rognes and Frederic Mahe
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/>.
Contact: Torbjorn Rognes <torognes@ifi.uio.no>,
Department of Informatics, University of Oslo,
PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/
#include "swarm.h"
#include "db.h"
#include "threads.h"
static pthread_mutex_t scan_mutex;
static ThreadRunner * search_threads = nullptr;
struct search_data
{
BYTE ** qtable;
WORD ** qtable_w;
BYTE * dprofile;
WORD * dprofile_w;
BYTE * hearray;
uint64_t * dir_array;
uint64_t target_count;
uint64_t target_index;
};
static struct search_data * sd;
static uint64_t master_next;
static uint64_t master_length;
static uint64_t remainingchunks;
static uint64_t * master_targets;
static uint64_t * master_scores;
static uint64_t * master_diffs;
static uint64_t * master_alignlengths;
static int master_bits;
static uint64_t dirbufferbytes;
queryinfo_t query;
uint64_t longestdbsequence;
void search_alloc(struct search_data * sdp);
void search_free(struct search_data * sdp);
void search_init(struct search_data * sdp);
void search_chunk(struct search_data * sdp, int64_t bits);
auto search_getwork(uint64_t * countref, uint64_t * firstref) -> bool;
void search_worker_core(int64_t t);
auto search_worker(void * vp) -> void *;
void search_alloc(struct search_data * sdp)
{
constexpr unsigned int one_kilobyte {1024};
constexpr unsigned int nt_per_uint64 {32};
constexpr unsigned int bytes_per_uint64 {8};
dirbufferbytes =
bytes_per_uint64 * longestdbsequence * ((longestdbsequence + 3) / 4) * 4;
sdp->qtable = static_cast<BYTE**>
(xmalloc(longestdbsequence * sizeof(BYTE*)));
sdp->qtable_w = static_cast<WORD**>
(xmalloc(longestdbsequence * sizeof(WORD*)));
sdp->dprofile = static_cast<BYTE*>
(xmalloc(2 * one_kilobyte)); // 4 * 16 * 32
sdp->dprofile_w = static_cast<WORD*>
(xmalloc(2 * one_kilobyte)); // 4 * 2 * 8 * 32
sdp->hearray = static_cast<BYTE*>
(xmalloc(longestdbsequence * nt_per_uint64));
sdp->dir_array = static_cast<uint64_t *>
(xmalloc(dirbufferbytes));
memset(sdp->hearray, 0, longestdbsequence * nt_per_uint64);
memset(sdp->dir_array, 0, dirbufferbytes);
}
void search_free(struct search_data * sdp)
{
xfree(sdp->qtable);
xfree(sdp->qtable_w);
xfree(sdp->dprofile);
xfree(sdp->dprofile_w);
xfree(sdp->hearray);
xfree(sdp->dir_array);
}
void search_init(struct search_data * sdp)
{
constexpr int byte_multiplier {64};
constexpr int word_multiplier {32};
for(auto i = 0U; i < query.len; i++)
{
int nt_value {nt_extract(query.seq, i) + 1}; // 1, 2, 3, or 4
int byte_offset {byte_multiplier * nt_value}; // 1, 64, 128, or 192
int word_offset {word_multiplier * nt_value}; // 1, 32, 64, or 128
sdp->qtable[i] = sdp->dprofile + byte_offset;
sdp->qtable_w[i] = sdp->dprofile_w + word_offset;
}
}
void search_chunk(struct search_data * sdp, int64_t bits)
{
constexpr unsigned int bit_mode_16 {16};
if (sdp->target_count == 0) {
return;
}
#if 0
for(auto i = 0ULL; i < sdp->target_count; i++)
{
char * dseq;
unsigned int dlen;
char * nwalignment;
uint64_t seqno = master_targets[sdp->target_index + i];
db_getsequenceandlength(seqno, & dseq, & dlen);
nw(dseq, dlen,
query.seq, query.len,
score_matrix_63,
penalty_gapopen, penalty_gapextend,
(int64_t *)(master_scores) + sdp->target_index + i,
(int64_t *)(master_diffs) + sdp->target_index + i,
(int64_t *)(master_alignlengths) + sdp->target_index + i,
& nwalignment,
(unsigned char *) sdp->dir_array,
(int64_t *) sdp->hearray,
query.qno, seqno);
#if 0
printf("\nAlignment: %s\n", nwalignment);
#endif
xfree(nwalignment);
}
return;
#endif
if (bits == bit_mode_16)
{
search16(sdp->qtable_w,
static_cast<WORD>(penalty_gapopen),
static_cast<WORD>(penalty_gapextend),
static_cast<WORD*>(score_matrix_16),
sdp->dprofile_w,
reinterpret_cast<WORD*>(sdp->hearray),
sdp->target_count,
master_targets + sdp->target_index,
master_scores + sdp->target_index,
master_diffs + sdp->target_index,
master_alignlengths + sdp->target_index,
static_cast<uint64_t>(query.len),
dirbufferbytes / sizeof(uint64_t),
sdp->dir_array);
}
else {
search8(sdp->qtable,
static_cast<BYTE>(penalty_gapopen),
static_cast<BYTE>(penalty_gapextend),
static_cast<BYTE*>(score_matrix_8),
sdp->dprofile,
sdp->hearray,
sdp->target_count,
master_targets + sdp->target_index,
master_scores + sdp->target_index,
master_diffs + sdp->target_index,
master_alignlengths + sdp->target_index,
static_cast<uint64_t>(query.len),
dirbufferbytes / sizeof(uint64_t),
sdp->dir_array);
}
}
auto search_getwork(uint64_t * countref, uint64_t * firstref) -> bool
{
// * countref = how many sequences to search
// * firstref = index into master_targets/scores/diffs where thread should start
bool status {false};
pthread_mutex_lock(&scan_mutex);
if (master_next < master_length)
{
uint64_t chunksize =
((master_length - master_next + remainingchunks - 1) / remainingchunks);
* countref = chunksize;
* firstref = master_next;
master_next += chunksize;
remainingchunks--;
status = true;
}
pthread_mutex_unlock(&scan_mutex);
return status;
}
#if 0
/* never used */
void master_dump()
{
printf("master_dump\n");
printf(" i t s d\n");
for(auto i = 0ULL; i < 1403; i++)
{
printf("%4" PRIu64 " %4" PRIu64 " %4" PRIu64 " %4" PRIu64 "\n",
i, master_targets[i], master_scores[i], master_diffs[i]);
}
}
#endif
void search_worker_core(int64_t t)
{
search_init(sd + t);
while(search_getwork(& sd[t].target_count, & sd[t].target_index)) {
search_chunk(sd + t, master_bits);
}
}
void search_do(uint64_t query_no,
uint64_t listlength,
uint64_t * targets,
uint64_t * scores,
uint64_t * diffs,
uint64_t * alignlengths,
int bits)
{
// constexpr unsigned int bit_mode_16 {16};
constexpr unsigned int channels_8 {8};
constexpr unsigned int bit_mode_8 {8};
constexpr unsigned int channels_16 {16};
query.qno = query_no;
unsigned int query_len = 0;
db_getsequenceandlength(query_no, &query.seq, &query_len);
query.len = query_len;
master_next = 0;
master_length = listlength;
master_targets = targets;
master_scores = scores;
master_diffs = diffs;
master_alignlengths = alignlengths;
master_bits = bits;
auto thr = static_cast<uint64_t>(opt_threads);
if (bits == bit_mode_8)
{
if (master_length <= (channels_16 - 1) * thr) {
thr = (master_length + channels_16 - 1) / channels_16;
}
}
else
{
if (master_length <= (channels_8 - 1) * thr) {
thr = (master_length + channels_8 - 1) / channels_8;
}
}
remainingchunks = thr;
if (thr == 1) {
search_worker_core(0);
}
else {
search_threads->run();
}
}
void search_begin()
{
longestdbsequence = db_getlongestsequence();
sd = static_cast<struct search_data *>
(xmalloc(sizeof(search_data) * static_cast<uint64_t>(opt_threads)));
for(auto t = 0LL; t < opt_threads; t++) {
search_alloc(sd+t);
}
pthread_mutex_init(& scan_mutex, nullptr);
/* start threads */
search_threads
= new ThreadRunner(static_cast<int>(opt_threads), search_worker_core);
}
void search_end()
{
/* finish and clean up worker threads */
delete search_threads;
pthread_mutex_destroy(& scan_mutex);
for(auto t = 0LL; t < opt_threads; t++) {
search_free(sd+t);
}
xfree(sd);
}
<commit_msg>remove debugging function<commit_after>/*
SWARM
Copyright (C) 2012-2022 Torbjorn Rognes and Frederic Mahe
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/>.
Contact: Torbjorn Rognes <torognes@ifi.uio.no>,
Department of Informatics, University of Oslo,
PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/
#include "swarm.h"
#include "db.h"
#include "threads.h"
static pthread_mutex_t scan_mutex;
static ThreadRunner * search_threads = nullptr;
struct search_data
{
BYTE ** qtable;
WORD ** qtable_w;
BYTE * dprofile;
WORD * dprofile_w;
BYTE * hearray;
uint64_t * dir_array;
uint64_t target_count;
uint64_t target_index;
};
static struct search_data * sd;
static uint64_t master_next;
static uint64_t master_length;
static uint64_t remainingchunks;
static uint64_t * master_targets;
static uint64_t * master_scores;
static uint64_t * master_diffs;
static uint64_t * master_alignlengths;
static int master_bits;
static uint64_t dirbufferbytes;
queryinfo_t query;
uint64_t longestdbsequence;
void search_alloc(struct search_data * sdp);
void search_free(struct search_data * sdp);
void search_init(struct search_data * sdp);
void search_chunk(struct search_data * sdp, int64_t bits);
auto search_getwork(uint64_t * countref, uint64_t * firstref) -> bool;
void search_worker_core(int64_t t);
auto search_worker(void * vp) -> void *;
void search_alloc(struct search_data * sdp)
{
constexpr unsigned int one_kilobyte {1024};
constexpr unsigned int nt_per_uint64 {32};
constexpr unsigned int bytes_per_uint64 {8};
dirbufferbytes =
bytes_per_uint64 * longestdbsequence * ((longestdbsequence + 3) / 4) * 4;
sdp->qtable = static_cast<BYTE**>
(xmalloc(longestdbsequence * sizeof(BYTE*)));
sdp->qtable_w = static_cast<WORD**>
(xmalloc(longestdbsequence * sizeof(WORD*)));
sdp->dprofile = static_cast<BYTE*>
(xmalloc(2 * one_kilobyte)); // 4 * 16 * 32
sdp->dprofile_w = static_cast<WORD*>
(xmalloc(2 * one_kilobyte)); // 4 * 2 * 8 * 32
sdp->hearray = static_cast<BYTE*>
(xmalloc(longestdbsequence * nt_per_uint64));
sdp->dir_array = static_cast<uint64_t *>
(xmalloc(dirbufferbytes));
memset(sdp->hearray, 0, longestdbsequence * nt_per_uint64);
memset(sdp->dir_array, 0, dirbufferbytes);
}
void search_free(struct search_data * sdp)
{
xfree(sdp->qtable);
xfree(sdp->qtable_w);
xfree(sdp->dprofile);
xfree(sdp->dprofile_w);
xfree(sdp->hearray);
xfree(sdp->dir_array);
}
void search_init(struct search_data * sdp)
{
constexpr int byte_multiplier {64};
constexpr int word_multiplier {32};
for(auto i = 0U; i < query.len; i++)
{
int nt_value {nt_extract(query.seq, i) + 1}; // 1, 2, 3, or 4
int byte_offset {byte_multiplier * nt_value}; // 1, 64, 128, or 192
int word_offset {word_multiplier * nt_value}; // 1, 32, 64, or 128
sdp->qtable[i] = sdp->dprofile + byte_offset;
sdp->qtable_w[i] = sdp->dprofile_w + word_offset;
}
}
void search_chunk(struct search_data * sdp, int64_t bits)
{
constexpr unsigned int bit_mode_16 {16};
if (sdp->target_count == 0) {
return;
}
#if 0
for(auto i = 0ULL; i < sdp->target_count; i++)
{
char * dseq;
unsigned int dlen;
char * nwalignment;
uint64_t seqno = master_targets[sdp->target_index + i];
db_getsequenceandlength(seqno, & dseq, & dlen);
nw(dseq, dlen,
query.seq, query.len,
score_matrix_63,
penalty_gapopen, penalty_gapextend,
(int64_t *)(master_scores) + sdp->target_index + i,
(int64_t *)(master_diffs) + sdp->target_index + i,
(int64_t *)(master_alignlengths) + sdp->target_index + i,
& nwalignment,
(unsigned char *) sdp->dir_array,
(int64_t *) sdp->hearray,
query.qno, seqno);
#if 0
printf("\nAlignment: %s\n", nwalignment);
#endif
xfree(nwalignment);
}
return;
#endif
if (bits == bit_mode_16)
{
search16(sdp->qtable_w,
static_cast<WORD>(penalty_gapopen),
static_cast<WORD>(penalty_gapextend),
static_cast<WORD*>(score_matrix_16),
sdp->dprofile_w,
reinterpret_cast<WORD*>(sdp->hearray),
sdp->target_count,
master_targets + sdp->target_index,
master_scores + sdp->target_index,
master_diffs + sdp->target_index,
master_alignlengths + sdp->target_index,
static_cast<uint64_t>(query.len),
dirbufferbytes / sizeof(uint64_t),
sdp->dir_array);
}
else {
search8(sdp->qtable,
static_cast<BYTE>(penalty_gapopen),
static_cast<BYTE>(penalty_gapextend),
static_cast<BYTE*>(score_matrix_8),
sdp->dprofile,
sdp->hearray,
sdp->target_count,
master_targets + sdp->target_index,
master_scores + sdp->target_index,
master_diffs + sdp->target_index,
master_alignlengths + sdp->target_index,
static_cast<uint64_t>(query.len),
dirbufferbytes / sizeof(uint64_t),
sdp->dir_array);
}
}
auto search_getwork(uint64_t * countref, uint64_t * firstref) -> bool
{
// * countref = how many sequences to search
// * firstref = index into master_targets/scores/diffs where thread should start
bool status {false};
pthread_mutex_lock(&scan_mutex);
if (master_next < master_length)
{
uint64_t chunksize =
((master_length - master_next + remainingchunks - 1) / remainingchunks);
* countref = chunksize;
* firstref = master_next;
master_next += chunksize;
remainingchunks--;
status = true;
}
pthread_mutex_unlock(&scan_mutex);
return status;
}
void search_worker_core(int64_t t)
{
search_init(sd + t);
while(search_getwork(& sd[t].target_count, & sd[t].target_index)) {
search_chunk(sd + t, master_bits);
}
}
void search_do(uint64_t query_no,
uint64_t listlength,
uint64_t * targets,
uint64_t * scores,
uint64_t * diffs,
uint64_t * alignlengths,
int bits)
{
// constexpr unsigned int bit_mode_16 {16};
constexpr unsigned int channels_8 {8};
constexpr unsigned int bit_mode_8 {8};
constexpr unsigned int channels_16 {16};
query.qno = query_no;
unsigned int query_len = 0;
db_getsequenceandlength(query_no, &query.seq, &query_len);
query.len = query_len;
master_next = 0;
master_length = listlength;
master_targets = targets;
master_scores = scores;
master_diffs = diffs;
master_alignlengths = alignlengths;
master_bits = bits;
auto thr = static_cast<uint64_t>(opt_threads);
if (bits == bit_mode_8)
{
if (master_length <= (channels_16 - 1) * thr) {
thr = (master_length + channels_16 - 1) / channels_16;
}
}
else
{
if (master_length <= (channels_8 - 1) * thr) {
thr = (master_length + channels_8 - 1) / channels_8;
}
}
remainingchunks = thr;
if (thr == 1) {
search_worker_core(0);
}
else {
search_threads->run();
}
}
void search_begin()
{
longestdbsequence = db_getlongestsequence();
sd = static_cast<struct search_data *>
(xmalloc(sizeof(search_data) * static_cast<uint64_t>(opt_threads)));
for(auto t = 0LL; t < opt_threads; t++) {
search_alloc(sd+t);
}
pthread_mutex_init(& scan_mutex, nullptr);
/* start threads */
search_threads
= new ThreadRunner(static_cast<int>(opt_threads), search_worker_core);
}
void search_end()
{
/* finish and clean up worker threads */
delete search_threads;
pthread_mutex_destroy(& scan_mutex);
for(auto t = 0LL; t < opt_threads; t++) {
search_free(sd+t);
}
xfree(sd);
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <cmake.h>
#include <sstream>
#include <stdlib.h>
#include <Context.h>
#include <ViewText.h>
#include <Date.h>
#include <main.h>
#include <i18n.h>
#include <text.h>
#include <CmdTimesheet.h>
extern Context context;
////////////////////////////////////////////////////////////////////////////////
CmdTimesheet::CmdTimesheet ()
{
_keyword = "timesheet";
_usage = "task timesheet [weeks]";
_description = STRING_CMD_TIMESHEET_USAGE;
_read_only = true;
_displays_id = false;
}
////////////////////////////////////////////////////////////////////////////////
int CmdTimesheet::execute (std::string& output)
{
int rc = 0;
// Scan the pending tasks.
handleRecurrence ();
std::vector <Task> all = context.tdb2.all_tasks ();
// What day of the week does the user consider the first?
int weekStart = Date::dayOfWeek (context.config.get ("weekstart"));
if (weekStart != 0 && weekStart != 1)
throw std::string (STRING_DATE_BAD_WEEKSTART);
// Determine the date of the first day of the most recent report.
Date today;
Date start;
start -= (((today.dayOfWeek () - weekStart) + 7) % 7) * 86400;
// Roll back to midnight.
start = Date (start.month (), start.day (), start.year ());
Date end = start + (7 * 86400);
// Determine how many reports to run.
int quantity = 1;
std::vector <std::string> words = context.cli.getWords ();
if (words.size () == 1)
quantity = strtol (words[0].c_str (), NULL, 10);;
std::stringstream out;
for (int week = 0; week < quantity; ++week)
{
Date endString (end);
endString -= 86400;
std::string title = start.toString (context.config.get ("dateformat"))
+ " - "
+ endString.toString (context.config.get ("dateformat"));
Color bold (Color::nocolor, Color::nocolor, false, true, false);
out << "\n"
<< (context.color () ? bold.colorize (title) : title)
<< "\n";
// Render the completed table.
ViewText completed;
completed.width (context.getWidth ());
completed.add (Column::factory ("string", " "));
completed.add (Column::factory ("string", STRING_COLUMN_LABEL_PROJECT));
completed.add (Column::factory ("string.right", STRING_COLUMN_LABEL_DUE));
completed.add (Column::factory ("string", STRING_COLUMN_LABEL_DESC));
Color label (context.config.get ("color.label"));
completed.colorHeader (label);
for (auto& task : all)
{
// If task completed within range.
if (task.getStatus () == Task::completed)
{
Date compDate (task.get_date ("end"));
if (compDate >= start && compDate < end)
{
Color c;
if (context.color ())
autoColorize (task, c);
int row = completed.addRow ();
std::string format = context.config.get ("dateformat.report");
if (format == "")
format = context.config.get ("dateformat");
completed.set (row, 1, task.get ("project"), c);
if(task.has ("due"))
{
Date dt (task.get_date ("due"));
completed.set (row, 2, dt.toString (format));
}
std::string description = task.get ("description");
int indent = context.config.getInteger ("indent.annotation");
std::map <std::string, std::string> annotations;
task.getAnnotations (annotations);
for (auto& ann : annotations)
description += "\n"
+ std::string (indent, ' ')
+ Date (ann.first.substr (11)).toString (context.config.get ("dateformat"))
+ " "
+ ann.second;
completed.set (row, 3, description, c);
}
}
}
out << " " << format (STRING_CMD_TIMESHEET_DONE, completed.rows ()) << "\n";
if (completed.rows ())
out << completed.render ()
<< "\n";
// Now render the started table.
ViewText started;
started.width (context.getWidth ());
started.add (Column::factory ("string", " "));
started.add (Column::factory ("string", STRING_COLUMN_LABEL_PROJECT));
started.add (Column::factory ("string.right", STRING_COLUMN_LABEL_DUE));
started.add (Column::factory ("string", STRING_COLUMN_LABEL_DESC));
started.colorHeader (label);
for (auto& task : all)
{
// If task started within range, but not completed withing range.
if (task.getStatus () == Task::pending &&
task.has ("start"))
{
Date startDate (task.get_date ("start"));
if (startDate >= start && startDate < end)
{
Color c;
if (context.color ())
autoColorize (task, c);
int row = started.addRow ();
std::string format = context.config.get ("dateformat.report");
if (format == "")
format = context.config.get ("dateformat");
started.set (row, 1, task.get ("project"), c);
if (task.has ("due"))
{
Date dt (task.get_date ("due"));
started.set (row, 2, dt.toString (format));
}
std::string description = task.get ("description");
int indent = context.config.getInteger ("indent.annotation");
std::map <std::string, std::string> annotations;
task.getAnnotations (annotations);
for (auto& ann : annotations)
description += "\n"
+ std::string (indent, ' ')
+ Date (ann.first.substr (11)).toString (context.config.get ("dateformat"))
+ " "
+ ann.second;
started.set (row, 3, description, c);
}
}
}
out << " " << format (STRING_CMD_TIMESHEET_STARTED, started.rows ()) << "\n";
if (started.rows ())
out << started.render ()
<< "\n\n";
// Prior week.
start -= 7 * 86400;
end -= 7 * 86400;
}
output = out.str ();
return rc;
}
////////////////////////////////////////////////////////////////////////////////
<commit_msg>CmdTimesheet: Converted from CLI to CLI2<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <cmake.h>
#include <sstream>
#include <stdlib.h>
#include <Context.h>
#include <ViewText.h>
#include <Date.h>
#include <main.h>
#include <i18n.h>
#include <text.h>
#include <CmdTimesheet.h>
extern Context context;
////////////////////////////////////////////////////////////////////////////////
CmdTimesheet::CmdTimesheet ()
{
_keyword = "timesheet";
_usage = "task timesheet [weeks]";
_description = STRING_CMD_TIMESHEET_USAGE;
_read_only = true;
_displays_id = false;
}
////////////////////////////////////////////////////////////////////////////////
int CmdTimesheet::execute (std::string& output)
{
int rc = 0;
// Scan the pending tasks.
handleRecurrence ();
std::vector <Task> all = context.tdb2.all_tasks ();
// What day of the week does the user consider the first?
int weekStart = Date::dayOfWeek (context.config.get ("weekstart"));
if (weekStart != 0 && weekStart != 1)
throw std::string (STRING_DATE_BAD_WEEKSTART);
// Determine the date of the first day of the most recent report.
Date today;
Date start;
start -= (((today.dayOfWeek () - weekStart) + 7) % 7) * 86400;
// Roll back to midnight.
start = Date (start.month (), start.day (), start.year ());
Date end = start + (7 * 86400);
// Determine how many reports to run.
int quantity = 1;
std::vector <std::string> words = context.cli2.getWords ();
if (words.size () == 1)
quantity = strtol (words[0].c_str (), NULL, 10);;
std::stringstream out;
for (int week = 0; week < quantity; ++week)
{
Date endString (end);
endString -= 86400;
std::string title = start.toString (context.config.get ("dateformat"))
+ " - "
+ endString.toString (context.config.get ("dateformat"));
Color bold (Color::nocolor, Color::nocolor, false, true, false);
out << "\n"
<< (context.color () ? bold.colorize (title) : title)
<< "\n";
// Render the completed table.
ViewText completed;
completed.width (context.getWidth ());
completed.add (Column::factory ("string", " "));
completed.add (Column::factory ("string", STRING_COLUMN_LABEL_PROJECT));
completed.add (Column::factory ("string.right", STRING_COLUMN_LABEL_DUE));
completed.add (Column::factory ("string", STRING_COLUMN_LABEL_DESC));
Color label (context.config.get ("color.label"));
completed.colorHeader (label);
for (auto& task : all)
{
// If task completed within range.
if (task.getStatus () == Task::completed)
{
Date compDate (task.get_date ("end"));
if (compDate >= start && compDate < end)
{
Color c;
if (context.color ())
autoColorize (task, c);
int row = completed.addRow ();
std::string format = context.config.get ("dateformat.report");
if (format == "")
format = context.config.get ("dateformat");
completed.set (row, 1, task.get ("project"), c);
if(task.has ("due"))
{
Date dt (task.get_date ("due"));
completed.set (row, 2, dt.toString (format));
}
std::string description = task.get ("description");
int indent = context.config.getInteger ("indent.annotation");
std::map <std::string, std::string> annotations;
task.getAnnotations (annotations);
for (auto& ann : annotations)
description += "\n"
+ std::string (indent, ' ')
+ Date (ann.first.substr (11)).toString (context.config.get ("dateformat"))
+ " "
+ ann.second;
completed.set (row, 3, description, c);
}
}
}
out << " " << format (STRING_CMD_TIMESHEET_DONE, completed.rows ()) << "\n";
if (completed.rows ())
out << completed.render ()
<< "\n";
// Now render the started table.
ViewText started;
started.width (context.getWidth ());
started.add (Column::factory ("string", " "));
started.add (Column::factory ("string", STRING_COLUMN_LABEL_PROJECT));
started.add (Column::factory ("string.right", STRING_COLUMN_LABEL_DUE));
started.add (Column::factory ("string", STRING_COLUMN_LABEL_DESC));
started.colorHeader (label);
for (auto& task : all)
{
// If task started within range, but not completed withing range.
if (task.getStatus () == Task::pending &&
task.has ("start"))
{
Date startDate (task.get_date ("start"));
if (startDate >= start && startDate < end)
{
Color c;
if (context.color ())
autoColorize (task, c);
int row = started.addRow ();
std::string format = context.config.get ("dateformat.report");
if (format == "")
format = context.config.get ("dateformat");
started.set (row, 1, task.get ("project"), c);
if (task.has ("due"))
{
Date dt (task.get_date ("due"));
started.set (row, 2, dt.toString (format));
}
std::string description = task.get ("description");
int indent = context.config.getInteger ("indent.annotation");
std::map <std::string, std::string> annotations;
task.getAnnotations (annotations);
for (auto& ann : annotations)
description += "\n"
+ std::string (indent, ' ')
+ Date (ann.first.substr (11)).toString (context.config.get ("dateformat"))
+ " "
+ ann.second;
started.set (row, 3, description, c);
}
}
}
out << " " << format (STRING_CMD_TIMESHEET_STARTED, started.rows ()) << "\n";
if (started.rows ())
out << started.render ()
<< "\n\n";
// Prior week.
start -= 7 * 86400;
end -= 7 * 86400;
}
output = out.str ();
return rc;
}
////////////////////////////////////////////////////////////////////////////////
<|endoftext|>
|
<commit_before>#include "iteration/updater/source_updater_gauss_seidel.h"
#include <memory>
#include <iteration/updater/angular_source_updater_gauss_seidel.h>
#include "test_helpers/gmock_wrapper.h"
#include "quadrature/tests/quadrature_set_mock.h"
#include "formulation/tests/angular_stamper_mock.h"
namespace {
using namespace bart;
template <typename DimensionWrapper>
class IterationUpdaterAngularSourceUpdaterGaussSeidelTest :
public ::testing::Test {
public:
static constexpr int dim = DimensionWrapper::value;
using UpdaterType = iteration::updater::AngularSourceUpdaterGaussSeidel<formulation::AngularStamperI<dim>>;
using StamperType = formulation::AngularStamperMock<dim>;
using QuadratureSetType = quadrature::QuadratureSetMock<dim>;
std::shared_ptr<StamperType> stamper_ptr_;
std::shared_ptr<QuadratureSetType> quadrature_set_ptr_;
std::unique_ptr<UpdaterType> test_updater_;
void SetUp() override;
};
template <typename DimensionWrapper>
void IterationUpdaterAngularSourceUpdaterGaussSeidelTest<DimensionWrapper>::SetUp() {
stamper_ptr_ = std::make_shared<StamperType>();
quadrature_set_ptr_ = std::make_shared<QuadratureSetType>();
test_updater_ = std::make_unique<UpdaterType>(stamper_ptr_, quadrature_set_ptr_);
}
TYPED_TEST_SUITE(IterationUpdaterAngularSourceUpdaterGaussSeidelTest,
bart::testing::AllDimensions);
TYPED_TEST(IterationUpdaterAngularSourceUpdaterGaussSeidelTest, Constructor) {
constexpr int dim = this->dim;
using UpdaterType = iteration::updater::AngularSourceUpdaterGaussSeidel<formulation::AngularStamperI<dim>>;
using StamperType = formulation::AngularStamperMock<dim>;
auto stamper_ptr = std::make_shared<StamperType>();
auto quadrature_set_ptr = std::make_shared<quadrature::QuadratureSetMock<dim>>();
EXPECT_NO_THROW({ UpdaterType test_updater(stamper_ptr, quadrature_set_ptr); });
EXPECT_ANY_THROW({ UpdaterType test_updater(nullptr, quadrature_set_ptr); });
EXPECT_ANY_THROW({ UpdaterType test_updater(stamper_ptr, nullptr); });
}
TYPED_TEST(IterationUpdaterAngularSourceUpdaterGaussSeidelTest, Getters) {
auto quadrature_set_ptr = this->test_updater_->quadrature_set_ptr();
auto stamper_ptr = this->test_updater_->stamper_ptr();
EXPECT_EQ(quadrature_set_ptr, this->quadrature_set_ptr_.get());
EXPECT_EQ(stamper_ptr, this->stamper_ptr_.get());
}
} // namespace
<commit_msg>started adding test to tests for AngularSourceUpdater<commit_after>#include "iteration/updater/source_updater_gauss_seidel.h"
#include <memory>
#include <iteration/updater/angular_source_updater_gauss_seidel.h>
#include <deal.II/base/mpi.h>
#include "test_helpers/gmock_wrapper.h"
#include "quadrature/tests/quadrature_set_mock.h"
#include "formulation/tests/angular_stamper_mock.h"
#include "system/terms/tests/linear_term_mock.h"
namespace {
using namespace bart;
using ::testing::A, ::testing::Return, ::testing::_;
template <typename DimensionWrapper>
class IterationUpdaterAngularSourceUpdaterGaussSeidelTest :
public ::testing::Test {
public:
static constexpr int dim = DimensionWrapper::value;
using UpdaterType = iteration::updater::AngularSourceUpdaterGaussSeidel<formulation::AngularStamperI<dim>>;
using StamperType = formulation::AngularStamperMock<dim>;
using QuadratureSetType = quadrature::QuadratureSetMock<dim>;
using RightHandSideType = bart::system::terms::LinearTermMock;
// Tested object
std::unique_ptr<UpdaterType> test_updater_;
// Dependencies
std::shared_ptr<StamperType> stamper_ptr_;
std::shared_ptr<QuadratureSetType> quadrature_set_ptr_;
// Other test objects
bart::system::System test_system_;
std::shared_ptr<system::MPIVector> source_vector_ptr_;
bart::system::MPIVector expected_vector_;
RightHandSideType* right_hand_side_obs_ptr_;
void SetUp() override;
void SetUpTestObject();
void SetUpSystem();
};
template <typename DimensionWrapper>
void IterationUpdaterAngularSourceUpdaterGaussSeidelTest<DimensionWrapper>::SetUp() {
SetUpTestObject();
SetUpSystem();
}
template <typename DimensionWrapper>
void IterationUpdaterAngularSourceUpdaterGaussSeidelTest<DimensionWrapper>::SetUpTestObject() {
stamper_ptr_ = std::make_shared<StamperType>();
quadrature_set_ptr_ = std::make_shared<QuadratureSetType>();
test_updater_ = std::make_unique<UpdaterType>(stamper_ptr_, quadrature_set_ptr_);
}
template <typename DimensionWrapper>
void IterationUpdaterAngularSourceUpdaterGaussSeidelTest<DimensionWrapper>::SetUpSystem() {
auto mock_right_hand_side_ptr = std::make_unique<RightHandSideType>();
right_hand_side_obs_ptr_ = mock_right_hand_side_ptr.get();
source_vector_ptr_ = std::make_shared<system::MPIVector>();
auto n_processes = dealii::Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD);
source_vector_ptr_->reinit(MPI_COMM_WORLD, n_processes*5, 5);
expected_vector_.reinit(*source_vector_ptr_);
ON_CALL(*mock_right_hand_side_ptr, GetVariableTermPtr(A<system::Index>(), _))
.WillByDefault(Return(source_vector_ptr_));
test_system_.right_hand_side_ptr_ = std::move(mock_right_hand_side_ptr);
}
TYPED_TEST_SUITE(IterationUpdaterAngularSourceUpdaterGaussSeidelTest,
bart::testing::AllDimensions);
TYPED_TEST(IterationUpdaterAngularSourceUpdaterGaussSeidelTest, Constructor) {
constexpr int dim = this->dim;
using UpdaterType = iteration::updater::AngularSourceUpdaterGaussSeidel<formulation::AngularStamperI<dim>>;
using StamperType = formulation::AngularStamperMock<dim>;
auto stamper_ptr = std::make_shared<StamperType>();
auto quadrature_set_ptr = std::make_shared<quadrature::QuadratureSetMock<dim>>();
EXPECT_NO_THROW({ UpdaterType test_updater(stamper_ptr, quadrature_set_ptr); });
EXPECT_ANY_THROW({ UpdaterType test_updater(nullptr, quadrature_set_ptr); });
EXPECT_ANY_THROW({ UpdaterType test_updater(stamper_ptr, nullptr); });
}
TYPED_TEST(IterationUpdaterAngularSourceUpdaterGaussSeidelTest, Getters) {
auto quadrature_set_ptr = this->test_updater_->quadrature_set_ptr();
auto stamper_ptr = this->test_updater_->stamper_ptr();
EXPECT_EQ(quadrature_set_ptr, this->quadrature_set_ptr_.get());
EXPECT_EQ(stamper_ptr, this->stamper_ptr_.get());
}
} // namespace
<|endoftext|>
|
<commit_before>/**************************************************************************
* Copyright(c) 2006-2008, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//-----------------------------------------------------------------
// Implementation of the base Vertex class
// This class contains the Secondary Vertex
// of a set of tracks
// And it is the base class for primary vertices
// Origin: F.Prino, Torino, prino@to.infn.it
//-----------------------------------------------------------------
#include "AliVertex.h"
ClassImp(AliVertex)
//--------------------------------------------------------------------------
AliVertex::AliVertex() :
TNamed(),
fSigma(0),
fNContributors(0),
fNIndices(0)
{
//
// Default Constructor, set everything to 0
//
for(Int_t k=0;k<3;k++) fPosition[k] = 0;
fIndices = 0;
}
//--------------------------------------------------------------------------
AliVertex::AliVertex(Double_t position[3],Double_t dispersion,
Int_t nContributors):
TNamed(),
fSigma(dispersion),
fNContributors(nContributors),
fNIndices(0)
{
//
// Standard Constructor
//
for(Int_t k=0;k<3;k++) fPosition[k] = position[k];
fIndices = 0;
SetName("BaseVertex");
}
//--------------------------------------------------------------------------
AliVertex::AliVertex(const AliVertex &source):
TNamed(source),
fSigma(source.GetDispersion()),
fNContributors(source.GetNContributors()),
fNIndices(source.GetNIndices())
{
//
// Copy constructor
//
for(Int_t i=0;i<3;i++)fPosition[i] = source.fPosition[i];
if(source.fNIndices>0) {
fIndices = new UShort_t[fNIndices];
memcpy(fIndices,source.fIndices,fNIndices*sizeof(UShort_t));
}
}
//--------------------------------------------------------------------------
AliVertex &AliVertex::operator=(const AliVertex &source){
//
// assignment operator
//
if(&source == this) return *this;
this->SetName(source.GetName());
this->SetTitle(source.GetTitle());
for(Int_t i=0;i<3;i++)fPosition[i] = source.fPosition[i];
fSigma = source.GetDispersion();
fNContributors = source.GetNContributors();
fNIndices = source.GetNIndices();
if(source.fNIndices>0) {
fIndices = new UShort_t[fNIndices];
memcpy(fIndices,source.fIndices,fNIndices*sizeof(UShort_t));
}
return *this;
}
//--------------------------------------------------------------------------
AliVertex::~AliVertex() {
//
// Default Destructor
//
delete [] fIndices;
}
//--------------------------------------------------------------------------
void AliVertex::GetXYZ(Double_t position[3]) const {
//
// Return position of the vertex in global frame
//
position[0] = fPosition[0];
position[1] = fPosition[1];
position[2] = fPosition[2];
return;
}
//--------------------------------------------------------------------------
void AliVertex::SetIndices(Int_t nindices,UShort_t *indices) {
//
// Set indices of tracks used for vertex determination
//
if(fNContributors<1) { printf("fNContributors<1"); return; }
fNIndices = nindices;
fIndices = new UShort_t[fNIndices];
for(Int_t i=0;i<fNIndices;i++) fIndices[i] = indices[i];
return;
}
//--------------------------------------------------------------------------
Bool_t AliVertex::UsesTrack(Int_t index) const {
//
// checks if a track is used for the vertex
//
if(fNIndices<1) { printf("fNIndices<1"); return kFALSE; }
for(Int_t i=0;i<fNIndices;i++) {
if((Int_t)fIndices[i]==index) return kTRUE;
}
return kFALSE;
}
//--------------------------------------------------------------------------
void AliVertex::Print(Option_t* /*option*/) const {
//
// Print out information on all data members
//
printf("Vertex position:\n");
printf(" x = %f\n",fPosition[0]);
printf(" y = %f\n",fPosition[1]);
printf(" z = %f\n",fPosition[2]);
printf(" Dispersion = %f\n",fSigma);
printf(" # tracks = %d\n",fNContributors);
return;
}
<commit_msg>Corrected initialization of pointers (Solaris x86)<commit_after>/**************************************************************************
* Copyright(c) 2006-2008, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//-----------------------------------------------------------------
// Implementation of the base Vertex class
// This class contains the Secondary Vertex
// of a set of tracks
// And it is the base class for primary vertices
// Origin: F.Prino, Torino, prino@to.infn.it
//-----------------------------------------------------------------
#include "AliVertex.h"
ClassImp(AliVertex)
//--------------------------------------------------------------------------
AliVertex::AliVertex() :
TNamed(),
fSigma(0),
fNContributors(0),
fNIndices(0)
{
//
// Default Constructor, set everything to 0
//
for(Int_t k=0;k<3;k++) fPosition[k] = 0;
fIndices = 0;
}
//--------------------------------------------------------------------------
AliVertex::AliVertex(Double_t position[3],Double_t dispersion,
Int_t nContributors):
TNamed(),
fSigma(dispersion),
fNContributors(nContributors),
fNIndices(0)
{
//
// Standard Constructor
//
for(Int_t k=0;k<3;k++) fPosition[k] = position[k];
fIndices = 0;
SetName("BaseVertex");
}
//--------------------------------------------------------------------------
AliVertex::AliVertex(const AliVertex &source):
TNamed(source),
fSigma(source.GetDispersion()),
fNContributors(source.GetNContributors()),
fNIndices(source.GetNIndices()),
fIndices(0x0)
{
//
// Copy constructor
//
for(Int_t i=0;i<3;i++)fPosition[i] = source.fPosition[i];
if(source.fNIndices>0) {
fIndices = new UShort_t[fNIndices];
memcpy(fIndices,source.fIndices,fNIndices*sizeof(UShort_t));
}
}
//--------------------------------------------------------------------------
AliVertex &AliVertex::operator=(const AliVertex &source){
//
// assignment operator
//
if(&source == this) return *this;
this->SetName(source.GetName());
this->SetTitle(source.GetTitle());
for(Int_t i=0;i<3;i++)fPosition[i] = source.fPosition[i];
fSigma = source.GetDispersion();
fNContributors = source.GetNContributors();
fNIndices = source.GetNIndices();
fIndices = 0x0;
if(source.fNIndices>0) {
fIndices = new UShort_t[fNIndices];
memcpy(fIndices,source.fIndices,fNIndices*sizeof(UShort_t));
}
return *this;
}
//--------------------------------------------------------------------------
AliVertex::~AliVertex() {
//
// Default Destructor
//
delete [] fIndices;
}
//--------------------------------------------------------------------------
void AliVertex::GetXYZ(Double_t position[3]) const {
//
// Return position of the vertex in global frame
//
position[0] = fPosition[0];
position[1] = fPosition[1];
position[2] = fPosition[2];
return;
}
//--------------------------------------------------------------------------
void AliVertex::SetIndices(Int_t nindices,UShort_t *indices) {
//
// Set indices of tracks used for vertex determination
//
if(fNContributors<1) { printf("fNContributors<1"); return; }
fNIndices = nindices;
delete [] fIndices;
fIndices = new UShort_t[fNIndices];
for(Int_t i=0;i<fNIndices;i++) fIndices[i] = indices[i];
return;
}
//--------------------------------------------------------------------------
Bool_t AliVertex::UsesTrack(Int_t index) const {
//
// checks if a track is used for the vertex
//
if(fNIndices<1) { printf("fNIndices<1"); return kFALSE; }
for(Int_t i=0;i<fNIndices;i++) {
if((Int_t)fIndices[i]==index) return kTRUE;
}
return kFALSE;
}
//--------------------------------------------------------------------------
void AliVertex::Print(Option_t* /*option*/) const {
//
// Print out information on all data members
//
printf("Vertex position:\n");
printf(" x = %f\n",fPosition[0]);
printf(" y = %f\n",fPosition[1]);
printf(" z = %f\n",fPosition[2]);
printf(" Dispersion = %f\n",fSigma);
printf(" # tracks = %d\n",fNContributors);
return;
}
<|endoftext|>
|
<commit_before>
/*
* kPPP: A front end for pppd for the KDE project
*
* $Id$
*
* Copyright (C) 1997 Bernd Johannes Wuebben
* wuebben@math.cornell.edu
*
* based on EzPPP:
* Copyright (C) 1997 Jay Painter
*
* This program 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 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library 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.
*/
#include "scriptedit.h"
#include <qlayout.h>
#include <qcombobox.h>
#include <qlineedit.h>
//Added by qt3to4:
#include <QHBoxLayout>
ScriptEdit::ScriptEdit( QWidget *parent )
: QWidget(parent)
{
QHBoxLayout *tl = new QHBoxLayout(this);
tl->setSpacing(10);
tl->setMargin(0);
st = new QComboBox(this, "st");
st->addItem("Expect");
st->addItem("Send");
st->addItem("Pause (sec)");
st->addItem("Hangup");
st->addItem("Answer");
st->addItem("Timeout (sec)");
st->addItem("Password");
st->addItem("ID");
st->addItem("Prompt");
st->addItem("PWPrompt");
st->addItem("LoopStart");
st->addItem("LoopEnd");
st->addItem("Scan");
st->addItem("Save");
st->addItem("SendNoEcho");
connect(st, SIGNAL(activated(int)), SLOT(setType(int)));
se = new QLineEdit(this, "se");
se->setGeometry(120, 5, 140, 25);
se->setMaxLength(50);
connect(se, SIGNAL(returnPressed()), SLOT(seReturnPressed()));
tl->addWidget(st, 3);
tl->addWidget(se, 7);
setType(0);
tl->activate();
}
void ScriptEdit::setEnabled(bool b) {
se->setEnabled(b);
st->setEnabled(b);
}
void ScriptEdit::seReturnPressed() {
emit returnPressed();
}
QString ScriptEdit::text()const {
return se->text();
}
void ScriptEdit::setText(const QString &t) {
se->setText(t);
}
int ScriptEdit::type()const {
return st->currentIndex();
}
void ScriptEdit::setType(int i) {
switch(i) {
case Expect:
se->setText("");
se->setEnabled(TRUE);
break;
case Send:
se->setText("");
se->setEnabled(TRUE);
break;
case Pause:
se->setText("");
se->setEnabled(TRUE);
break;
case Hangup:
se->setText("");
se->setEnabled(FALSE);
break;
case Answer:
se->setText("");
se->setEnabled(FALSE);
break;
case Timeout:
se->setText("");
se->setEnabled(TRUE);
break;
case Password:
se->setText("");
se->setEnabled(TRUE);
break;
case ID:
se->setText("");
se->setEnabled(TRUE);
break;
case Prompt:
se->setText("");
se->setEnabled(TRUE);
break;
case PWPrompt:
se->setText("");
se->setEnabled(TRUE);
break;
case LoopStart:
se->setText("");
se->setEnabled(TRUE);
break;
case LoopEnd:
se->setText("");
se->setEnabled(TRUE);
break;
case Scan:
se->setText("");
se->setEnabled(TRUE);
break;
case Save:
se->setText("password");
se->setEnabled(FALSE);
break;
default: break;
}
}
#include "scriptedit.moc"
<commit_msg>replace deprecated functions<commit_after>
/*
* kPPP: A front end for pppd for the KDE project
*
* $Id$
*
* Copyright (C) 1997 Bernd Johannes Wuebben
* wuebben@math.cornell.edu
*
* based on EzPPP:
* Copyright (C) 1997 Jay Painter
*
* This program 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 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library 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.
*/
#include "scriptedit.h"
#include <qlayout.h>
#include <qcombobox.h>
#include <qlineedit.h>
//Added by qt3to4:
#include <QHBoxLayout>
ScriptEdit::ScriptEdit( QWidget *parent )
: QWidget(parent)
{
QHBoxLayout *tl = new QHBoxLayout(this);
tl->setSpacing(10);
tl->setMargin(0);
st = new QComboBox(this);
st->setObjectName("st");
st->addItem("Expect");
st->addItem("Send");
st->addItem("Pause (sec)");
st->addItem("Hangup");
st->addItem("Answer");
st->addItem("Timeout (sec)");
st->addItem("Password");
st->addItem("ID");
st->addItem("Prompt");
st->addItem("PWPrompt");
st->addItem("LoopStart");
st->addItem("LoopEnd");
st->addItem("Scan");
st->addItem("Save");
st->addItem("SendNoEcho");
connect(st, SIGNAL(activated(int)), SLOT(setType(int)));
se = new QLineEdit(this, "se");
se->setGeometry(120, 5, 140, 25);
se->setMaxLength(50);
connect(se, SIGNAL(returnPressed()), SLOT(seReturnPressed()));
tl->addWidget(st, 3);
tl->addWidget(se, 7);
setType(0);
tl->activate();
}
void ScriptEdit::setEnabled(bool b) {
se->setEnabled(b);
st->setEnabled(b);
}
void ScriptEdit::seReturnPressed() {
emit returnPressed();
}
QString ScriptEdit::text()const {
return se->text();
}
void ScriptEdit::setText(const QString &t) {
se->setText(t);
}
int ScriptEdit::type()const {
return st->currentIndex();
}
void ScriptEdit::setType(int i) {
switch(i) {
case Expect:
se->setText("");
se->setEnabled(TRUE);
break;
case Send:
se->setText("");
se->setEnabled(TRUE);
break;
case Pause:
se->setText("");
se->setEnabled(TRUE);
break;
case Hangup:
se->setText("");
se->setEnabled(FALSE);
break;
case Answer:
se->setText("");
se->setEnabled(FALSE);
break;
case Timeout:
se->setText("");
se->setEnabled(TRUE);
break;
case Password:
se->setText("");
se->setEnabled(TRUE);
break;
case ID:
se->setText("");
se->setEnabled(TRUE);
break;
case Prompt:
se->setText("");
se->setEnabled(TRUE);
break;
case PWPrompt:
se->setText("");
se->setEnabled(TRUE);
break;
case LoopStart:
se->setText("");
se->setEnabled(TRUE);
break;
case LoopEnd:
se->setText("");
se->setEnabled(TRUE);
break;
case Scan:
se->setText("");
se->setEnabled(TRUE);
break;
case Save:
se->setText("password");
se->setEnabled(FALSE);
break;
default: break;
}
}
#include "scriptedit.moc"
<|endoftext|>
|
<commit_before>#include <inttypes.h>
#include "constants.h"
#include "main.h"
#include "types.h"
#include "GetNextTargetRequired.h"
compact_target_t GetNextTargetRequired(CBlockIndex const * pindexTail0, bool fProofOfStake)
{
target_t initialTarget = POW_INITIAL_TARGET;
if (pindexTail0 == NULL)
return initialTarget.GetCompact(); // genesis block
CBlockIndex const * pindexTail1 = GetLastBlockIndex(pindexTail0, fProofOfStake);
if (pindexTail1->pprev == NULL)
return initialTarget.GetCompact(); // first block
CBlockIndex const * pindexTail2 = GetLastBlockIndex(pindexTail1->pprev, fProofOfStake);
if (pindexTail2->pprev == NULL)
return initialTarget.GetCompact(); // second block
timestamp_t actualSpacing = pindexTail1->GetBlockTime() - pindexTail2->GetBlockTime();
timestamp_t targetSpacing = fProofOfStake ? POS_TARGET_SPACING : POW_TARGET_SPACING;
timestamp_t targetInterval = TARGET_TIMESPAN / targetSpacing;
// ppcoin: target change every block
// ppcoin: retarget with exponential moving toward target spacing
target_t currentTarget = CBigNum().SetCompact(pindexTail1->nBits);
target_t newTarget = currentTarget;
newTarget *= ((targetInterval - 1) * targetSpacing + actualSpacing + actualSpacing);
newTarget /= ((targetInterval + 1) * targetSpacing);
target_t maxTarget = fProofOfStake ? POS_MAX_TARGET : POW_MAX_TARGET;
if (newTarget > maxTarget)
newTarget = maxTarget;
printf("Expecting: %llis Actual: %llis Old Difficulty: %x New Difficulty: %x (%s)\n", targetSpacing, actualSpacing, currentTarget.GetCompact(), newTarget.GetCompact(), fProofOfStake ? "PoS" : "PoW");
return newTarget.GetCompact();
}
<commit_msg>Comments out debug informations<commit_after>#include <inttypes.h>
#include "constants.h"
#include "main.h"
#include "types.h"
#include "GetNextTargetRequired.h"
compact_target_t GetNextTargetRequired(CBlockIndex const * pindexTail0, bool fProofOfStake)
{
target_t initialTarget = POW_INITIAL_TARGET;
if (pindexTail0 == NULL)
return initialTarget.GetCompact(); // genesis block
CBlockIndex const * pindexTail1 = GetLastBlockIndex(pindexTail0, fProofOfStake);
if (pindexTail1->pprev == NULL)
return initialTarget.GetCompact(); // first block
CBlockIndex const * pindexTail2 = GetLastBlockIndex(pindexTail1->pprev, fProofOfStake);
if (pindexTail2->pprev == NULL)
return initialTarget.GetCompact(); // second block
timestamp_t actualSpacing = pindexTail1->GetBlockTime() - pindexTail2->GetBlockTime();
timestamp_t targetSpacing = fProofOfStake ? POS_TARGET_SPACING : POW_TARGET_SPACING;
timestamp_t targetInterval = TARGET_TIMESPAN / targetSpacing;
// ppcoin: target change every block
// ppcoin: retarget with exponential moving toward target spacing
target_t currentTarget = CBigNum().SetCompact(pindexTail1->nBits);
target_t newTarget = currentTarget;
newTarget *= ((targetInterval - 1) * targetSpacing + actualSpacing + actualSpacing);
newTarget /= ((targetInterval + 1) * targetSpacing);
target_t maxTarget = fProofOfStake ? POS_MAX_TARGET : POW_MAX_TARGET;
if (newTarget > maxTarget)
newTarget = maxTarget;
//printf("Expecting: %llis Actual: %llis Old Difficulty: %x New Difficulty: %x (%s)\n", targetSpacing, actualSpacing, currentTarget.GetCompact(), newTarget.GetCompact(), fProofOfStake ? "PoS" : "PoW");
return newTarget.GetCompact();
}
<|endoftext|>
|
<commit_before><commit_msg>Add Workbench name as Tab item tooltip<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/audio_coding/neteq4/decoder_database.h"
#include <assert.h>
#include <stdlib.h>
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "webrtc/modules/audio_coding/neteq4/mock/mock_audio_decoder.h"
#include "webrtc/test/testsupport/gtest_disable.h"
namespace webrtc {
TEST(DecoderDatabase, CreateAndDestroy) {
DecoderDatabase db;
EXPECT_EQ(0, db.Size());
EXPECT_TRUE(db.Empty());
}
TEST(DecoderDatabase, InsertAndRemove) {
DecoderDatabase db;
const uint8_t kPayloadType = 0;
EXPECT_EQ(DecoderDatabase::kOK,
db.RegisterPayload(kPayloadType, kDecoderPCMu));
EXPECT_EQ(1, db.Size());
EXPECT_FALSE(db.Empty());
EXPECT_EQ(DecoderDatabase::kOK, db.Remove(kPayloadType));
EXPECT_EQ(0, db.Size());
EXPECT_TRUE(db.Empty());
}
TEST(DecoderDatabase, GetDecoderInfo) {
DecoderDatabase db;
const uint8_t kPayloadType = 0;
EXPECT_EQ(DecoderDatabase::kOK,
db.RegisterPayload(kPayloadType, kDecoderPCMu));
const DecoderDatabase::DecoderInfo* info;
info = db.GetDecoderInfo(kPayloadType);
ASSERT_TRUE(info != NULL);
EXPECT_EQ(kDecoderPCMu, info->codec_type);
EXPECT_EQ(NULL, info->decoder);
EXPECT_EQ(8000, info->fs_hz);
EXPECT_FALSE(info->external);
info = db.GetDecoderInfo(kPayloadType + 1); // Other payload type.
EXPECT_TRUE(info == NULL); // Should not be found.
}
TEST(DecoderDatabase, GetRtpPayloadType) {
DecoderDatabase db;
const uint8_t kPayloadType = 0;
EXPECT_EQ(DecoderDatabase::kOK,
db.RegisterPayload(kPayloadType, kDecoderPCMu));
EXPECT_EQ(kPayloadType, db.GetRtpPayloadType(kDecoderPCMu));
const uint8_t expected_value = DecoderDatabase::kRtpPayloadTypeError;
EXPECT_EQ(expected_value,
db.GetRtpPayloadType(kDecoderISAC)); // iSAC is not registered.
}
TEST(DecoderDatabase, DISABLED_ON_ANDROID(GetDecoder)) {
DecoderDatabase db;
const uint8_t kPayloadType = 0;
EXPECT_EQ(DecoderDatabase::kOK,
db.RegisterPayload(kPayloadType, kDecoderILBC));
AudioDecoder* dec = db.GetDecoder(kPayloadType);
ASSERT_TRUE(dec != NULL);
}
TEST(DecoderDatabase, TypeTests) {
DecoderDatabase db;
const uint8_t kPayloadTypePcmU = 0;
const uint8_t kPayloadTypeCng = 13;
const uint8_t kPayloadTypeDtmf = 100;
const uint8_t kPayloadTypeRed = 101;
const uint8_t kPayloadNotUsed = 102;
// Load into database.
EXPECT_EQ(DecoderDatabase::kOK,
db.RegisterPayload(kPayloadTypePcmU, kDecoderPCMu));
EXPECT_EQ(DecoderDatabase::kOK,
db.RegisterPayload(kPayloadTypeCng, kDecoderCNGnb));
EXPECT_EQ(DecoderDatabase::kOK,
db.RegisterPayload(kPayloadTypeDtmf, kDecoderAVT));
EXPECT_EQ(DecoderDatabase::kOK,
db.RegisterPayload(kPayloadTypeRed, kDecoderRED));
EXPECT_EQ(4, db.Size());
// Test.
EXPECT_FALSE(db.IsComfortNoise(kPayloadNotUsed));
EXPECT_FALSE(db.IsDtmf(kPayloadNotUsed));
EXPECT_FALSE(db.IsRed(kPayloadNotUsed));
EXPECT_FALSE(db.IsComfortNoise(kPayloadTypePcmU));
EXPECT_FALSE(db.IsDtmf(kPayloadTypePcmU));
EXPECT_FALSE(db.IsRed(kPayloadTypePcmU));
EXPECT_FALSE(db.IsType(kPayloadTypePcmU, kDecoderISAC));
EXPECT_TRUE(db.IsType(kPayloadTypePcmU, kDecoderPCMu));
EXPECT_TRUE(db.IsComfortNoise(kPayloadTypeCng));
EXPECT_TRUE(db.IsDtmf(kPayloadTypeDtmf));
EXPECT_TRUE(db.IsRed(kPayloadTypeRed));
}
TEST(DecoderDatabase, ExternalDecoder) {
DecoderDatabase db;
const uint8_t kPayloadType = 0;
MockAudioDecoder decoder;
// Load into database.
EXPECT_EQ(DecoderDatabase::kOK,
db.InsertExternal(kPayloadType, kDecoderPCMu, 8000,
&decoder));
EXPECT_EQ(1, db.Size());
// Get decoder and make sure we get the external one.
EXPECT_EQ(&decoder, db.GetDecoder(kPayloadType));
// Get the decoder info struct and check it too.
const DecoderDatabase::DecoderInfo* info;
info = db.GetDecoderInfo(kPayloadType);
ASSERT_TRUE(info != NULL);
EXPECT_EQ(kDecoderPCMu, info->codec_type);
EXPECT_EQ(&decoder, info->decoder);
EXPECT_EQ(8000, info->fs_hz);
EXPECT_TRUE(info->external);
// Expect not to delete the decoder when removing it from the database, since
// it was declared externally.
EXPECT_CALL(decoder, Die()).Times(0);
EXPECT_EQ(DecoderDatabase::kOK, db.Remove(kPayloadType));
EXPECT_TRUE(db.Empty());
EXPECT_CALL(decoder, Die()).Times(1); // Will be called when |db| is deleted.
}
TEST(DecoderDatabase, CheckPayloadTypes) {
DecoderDatabase db;
// Load a number of payloads into the database. Payload types are 0, 1, ...,
// while the decoder type is the same for all payload types (this does not
// matter for the test).
const int kNumPayloads = 10;
for (uint8_t payload_type = 0; payload_type < kNumPayloads; ++payload_type) {
EXPECT_EQ(DecoderDatabase::kOK,
db.RegisterPayload(payload_type, kDecoderArbitrary));
}
PacketList packet_list;
for (int i = 0; i < kNumPayloads + 1; ++i) {
// Create packet with payload type |i|. The last packet will have a payload
// type that is not registered in the decoder database.
Packet* packet = new Packet;
packet->header.payloadType = i;
packet_list.push_back(packet);
}
// Expect to return false, since the last packet is of an unknown type.
EXPECT_EQ(DecoderDatabase::kDecoderNotFound,
db.CheckPayloadTypes(packet_list));
delete packet_list.back();
packet_list.pop_back(); // Remove the unknown one.
EXPECT_EQ(DecoderDatabase::kOK, db.CheckPayloadTypes(packet_list));
// Delete all packets.
PacketList::iterator it = packet_list.begin();
while (it != packet_list.end()) {
delete packet_list.front();
it = packet_list.erase(it);
}
}
// Test the methods for setting and getting active speech and CNG decoders.
TEST(DecoderDatabase, ActiveDecoders) {
DecoderDatabase db;
// Load payload types.
ASSERT_EQ(DecoderDatabase::kOK, db.RegisterPayload(0, kDecoderPCMu));
ASSERT_EQ(DecoderDatabase::kOK, db.RegisterPayload(103, kDecoderISAC));
ASSERT_EQ(DecoderDatabase::kOK, db.RegisterPayload(13, kDecoderCNGnb));
// Verify that no decoders are active from the start.
EXPECT_EQ(NULL, db.GetActiveDecoder());
EXPECT_EQ(NULL, db.GetActiveCngDecoder());
// Set active speech codec.
bool changed; // Should be true when the active decoder changed.
EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveDecoder(0, &changed));
EXPECT_TRUE(changed);
AudioDecoder* decoder = db.GetActiveDecoder();
ASSERT_FALSE(decoder == NULL); // Should get a decoder here.
EXPECT_EQ(kDecoderPCMu, decoder->codec_type());
// Set the same again. Expect no change.
EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveDecoder(0, &changed));
EXPECT_FALSE(changed);
decoder = db.GetActiveDecoder();
ASSERT_FALSE(decoder == NULL); // Should get a decoder here.
EXPECT_EQ(kDecoderPCMu, decoder->codec_type());
// Change active decoder.
EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveDecoder(103, &changed));
EXPECT_TRUE(changed);
decoder = db.GetActiveDecoder();
ASSERT_FALSE(decoder == NULL); // Should get a decoder here.
EXPECT_EQ(kDecoderISAC, decoder->codec_type());
// Remove the active decoder, and verify that the active becomes NULL.
EXPECT_EQ(DecoderDatabase::kOK, db.Remove(103));
EXPECT_EQ(NULL, db.GetActiveDecoder());
// Set active CNG codec.
EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveCngDecoder(13));
decoder = db.GetActiveCngDecoder();
ASSERT_FALSE(decoder == NULL); // Should get a decoder here.
EXPECT_EQ(kDecoderCNGnb, decoder->codec_type());
// Remove the active CNG decoder, and verify that the active becomes NULL.
EXPECT_EQ(DecoderDatabase::kOK, db.Remove(13));
EXPECT_EQ(NULL, db.GetActiveCngDecoder());
// Try to set non-existing codecs as active.
EXPECT_EQ(DecoderDatabase::kDecoderNotFound,
db.SetActiveDecoder(17, &changed));
EXPECT_EQ(DecoderDatabase::kDecoderNotFound,
db.SetActiveCngDecoder(17));
}
} // namespace webrtc
<commit_msg>Re-enable NetEQ DecoderDatabase test for Android<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/audio_coding/neteq4/decoder_database.h"
#include <assert.h>
#include <stdlib.h>
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "webrtc/modules/audio_coding/neteq4/mock/mock_audio_decoder.h"
#include "webrtc/test/testsupport/gtest_disable.h"
namespace webrtc {
TEST(DecoderDatabase, CreateAndDestroy) {
DecoderDatabase db;
EXPECT_EQ(0, db.Size());
EXPECT_TRUE(db.Empty());
}
TEST(DecoderDatabase, InsertAndRemove) {
DecoderDatabase db;
const uint8_t kPayloadType = 0;
EXPECT_EQ(DecoderDatabase::kOK,
db.RegisterPayload(kPayloadType, kDecoderPCMu));
EXPECT_EQ(1, db.Size());
EXPECT_FALSE(db.Empty());
EXPECT_EQ(DecoderDatabase::kOK, db.Remove(kPayloadType));
EXPECT_EQ(0, db.Size());
EXPECT_TRUE(db.Empty());
}
TEST(DecoderDatabase, GetDecoderInfo) {
DecoderDatabase db;
const uint8_t kPayloadType = 0;
EXPECT_EQ(DecoderDatabase::kOK,
db.RegisterPayload(kPayloadType, kDecoderPCMu));
const DecoderDatabase::DecoderInfo* info;
info = db.GetDecoderInfo(kPayloadType);
ASSERT_TRUE(info != NULL);
EXPECT_EQ(kDecoderPCMu, info->codec_type);
EXPECT_EQ(NULL, info->decoder);
EXPECT_EQ(8000, info->fs_hz);
EXPECT_FALSE(info->external);
info = db.GetDecoderInfo(kPayloadType + 1); // Other payload type.
EXPECT_TRUE(info == NULL); // Should not be found.
}
TEST(DecoderDatabase, GetRtpPayloadType) {
DecoderDatabase db;
const uint8_t kPayloadType = 0;
EXPECT_EQ(DecoderDatabase::kOK,
db.RegisterPayload(kPayloadType, kDecoderPCMu));
EXPECT_EQ(kPayloadType, db.GetRtpPayloadType(kDecoderPCMu));
const uint8_t expected_value = DecoderDatabase::kRtpPayloadTypeError;
EXPECT_EQ(expected_value,
db.GetRtpPayloadType(kDecoderISAC)); // iSAC is not registered.
}
TEST(DecoderDatabase, GetDecoder) {
DecoderDatabase db;
const uint8_t kPayloadType = 0;
EXPECT_EQ(DecoderDatabase::kOK,
db.RegisterPayload(kPayloadType, kDecoderPCM16B));
AudioDecoder* dec = db.GetDecoder(kPayloadType);
ASSERT_TRUE(dec != NULL);
}
TEST(DecoderDatabase, TypeTests) {
DecoderDatabase db;
const uint8_t kPayloadTypePcmU = 0;
const uint8_t kPayloadTypeCng = 13;
const uint8_t kPayloadTypeDtmf = 100;
const uint8_t kPayloadTypeRed = 101;
const uint8_t kPayloadNotUsed = 102;
// Load into database.
EXPECT_EQ(DecoderDatabase::kOK,
db.RegisterPayload(kPayloadTypePcmU, kDecoderPCMu));
EXPECT_EQ(DecoderDatabase::kOK,
db.RegisterPayload(kPayloadTypeCng, kDecoderCNGnb));
EXPECT_EQ(DecoderDatabase::kOK,
db.RegisterPayload(kPayloadTypeDtmf, kDecoderAVT));
EXPECT_EQ(DecoderDatabase::kOK,
db.RegisterPayload(kPayloadTypeRed, kDecoderRED));
EXPECT_EQ(4, db.Size());
// Test.
EXPECT_FALSE(db.IsComfortNoise(kPayloadNotUsed));
EXPECT_FALSE(db.IsDtmf(kPayloadNotUsed));
EXPECT_FALSE(db.IsRed(kPayloadNotUsed));
EXPECT_FALSE(db.IsComfortNoise(kPayloadTypePcmU));
EXPECT_FALSE(db.IsDtmf(kPayloadTypePcmU));
EXPECT_FALSE(db.IsRed(kPayloadTypePcmU));
EXPECT_FALSE(db.IsType(kPayloadTypePcmU, kDecoderISAC));
EXPECT_TRUE(db.IsType(kPayloadTypePcmU, kDecoderPCMu));
EXPECT_TRUE(db.IsComfortNoise(kPayloadTypeCng));
EXPECT_TRUE(db.IsDtmf(kPayloadTypeDtmf));
EXPECT_TRUE(db.IsRed(kPayloadTypeRed));
}
TEST(DecoderDatabase, ExternalDecoder) {
DecoderDatabase db;
const uint8_t kPayloadType = 0;
MockAudioDecoder decoder;
// Load into database.
EXPECT_EQ(DecoderDatabase::kOK,
db.InsertExternal(kPayloadType, kDecoderPCMu, 8000,
&decoder));
EXPECT_EQ(1, db.Size());
// Get decoder and make sure we get the external one.
EXPECT_EQ(&decoder, db.GetDecoder(kPayloadType));
// Get the decoder info struct and check it too.
const DecoderDatabase::DecoderInfo* info;
info = db.GetDecoderInfo(kPayloadType);
ASSERT_TRUE(info != NULL);
EXPECT_EQ(kDecoderPCMu, info->codec_type);
EXPECT_EQ(&decoder, info->decoder);
EXPECT_EQ(8000, info->fs_hz);
EXPECT_TRUE(info->external);
// Expect not to delete the decoder when removing it from the database, since
// it was declared externally.
EXPECT_CALL(decoder, Die()).Times(0);
EXPECT_EQ(DecoderDatabase::kOK, db.Remove(kPayloadType));
EXPECT_TRUE(db.Empty());
EXPECT_CALL(decoder, Die()).Times(1); // Will be called when |db| is deleted.
}
TEST(DecoderDatabase, CheckPayloadTypes) {
DecoderDatabase db;
// Load a number of payloads into the database. Payload types are 0, 1, ...,
// while the decoder type is the same for all payload types (this does not
// matter for the test).
const int kNumPayloads = 10;
for (uint8_t payload_type = 0; payload_type < kNumPayloads; ++payload_type) {
EXPECT_EQ(DecoderDatabase::kOK,
db.RegisterPayload(payload_type, kDecoderArbitrary));
}
PacketList packet_list;
for (int i = 0; i < kNumPayloads + 1; ++i) {
// Create packet with payload type |i|. The last packet will have a payload
// type that is not registered in the decoder database.
Packet* packet = new Packet;
packet->header.payloadType = i;
packet_list.push_back(packet);
}
// Expect to return false, since the last packet is of an unknown type.
EXPECT_EQ(DecoderDatabase::kDecoderNotFound,
db.CheckPayloadTypes(packet_list));
delete packet_list.back();
packet_list.pop_back(); // Remove the unknown one.
EXPECT_EQ(DecoderDatabase::kOK, db.CheckPayloadTypes(packet_list));
// Delete all packets.
PacketList::iterator it = packet_list.begin();
while (it != packet_list.end()) {
delete packet_list.front();
it = packet_list.erase(it);
}
}
// Test the methods for setting and getting active speech and CNG decoders.
TEST(DecoderDatabase, ActiveDecoders) {
DecoderDatabase db;
// Load payload types.
ASSERT_EQ(DecoderDatabase::kOK, db.RegisterPayload(0, kDecoderPCMu));
ASSERT_EQ(DecoderDatabase::kOK, db.RegisterPayload(103, kDecoderISAC));
ASSERT_EQ(DecoderDatabase::kOK, db.RegisterPayload(13, kDecoderCNGnb));
// Verify that no decoders are active from the start.
EXPECT_EQ(NULL, db.GetActiveDecoder());
EXPECT_EQ(NULL, db.GetActiveCngDecoder());
// Set active speech codec.
bool changed; // Should be true when the active decoder changed.
EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveDecoder(0, &changed));
EXPECT_TRUE(changed);
AudioDecoder* decoder = db.GetActiveDecoder();
ASSERT_FALSE(decoder == NULL); // Should get a decoder here.
EXPECT_EQ(kDecoderPCMu, decoder->codec_type());
// Set the same again. Expect no change.
EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveDecoder(0, &changed));
EXPECT_FALSE(changed);
decoder = db.GetActiveDecoder();
ASSERT_FALSE(decoder == NULL); // Should get a decoder here.
EXPECT_EQ(kDecoderPCMu, decoder->codec_type());
// Change active decoder.
EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveDecoder(103, &changed));
EXPECT_TRUE(changed);
decoder = db.GetActiveDecoder();
ASSERT_FALSE(decoder == NULL); // Should get a decoder here.
EXPECT_EQ(kDecoderISAC, decoder->codec_type());
// Remove the active decoder, and verify that the active becomes NULL.
EXPECT_EQ(DecoderDatabase::kOK, db.Remove(103));
EXPECT_EQ(NULL, db.GetActiveDecoder());
// Set active CNG codec.
EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveCngDecoder(13));
decoder = db.GetActiveCngDecoder();
ASSERT_FALSE(decoder == NULL); // Should get a decoder here.
EXPECT_EQ(kDecoderCNGnb, decoder->codec_type());
// Remove the active CNG decoder, and verify that the active becomes NULL.
EXPECT_EQ(DecoderDatabase::kOK, db.Remove(13));
EXPECT_EQ(NULL, db.GetActiveCngDecoder());
// Try to set non-existing codecs as active.
EXPECT_EQ(DecoderDatabase::kDecoderNotFound,
db.SetActiveDecoder(17, &changed));
EXPECT_EQ(DecoderDatabase::kDecoderNotFound,
db.SetActiveCngDecoder(17));
}
} // namespace webrtc
<|endoftext|>
|
<commit_before>/* dlvhex -- Answer-Set Programming with external interfaces.
* Copyright (C) 2005-2007 Roman Schindlauer
* Copyright (C) 2006-2015 Thomas Krennwallner
* Copyright (C) 2009-2016 Peter Schüller
* Copyright (C) 2011-2016 Christoph Redl
* Copyright (C) 2015-2016 Tobias Kaminski
* Copyright (C) 2015-2016 Antonius Weinzierl
*
* This file is part of dlvhex.
*
* dlvhex 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.
*
* dlvhex 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 dlvhex; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA.
*/
/**
* @file InconsistencyAnalyzer.cpp
* @author Christoph Redl
* @date Wed April 20 2016
*
* @brief Computes a reason for the inconsistency in a program unit.
*
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "dlvhex2/BaseModelGenerator.h"
#include "dlvhex2/InconsistencyAnalyzer.h"
#include "dlvhex2/Printer.h"
#include "dlvhex2/ProgramCtx.h"
#include "dlvhex2/Benchmarking.h"
#include "dlvhex2/Benchmarking.h"
#include "dlvhex2/InternalGrounder.h"
#include "dlvhex2/SATSolver.h"
#include <boost/graph/breadth_first_search.hpp>
#include <boost/graph/visitors.hpp>
#include <boost/graph/strong_components.hpp>
#include <boost/graph/filtered_graph.hpp>
#include <boost/foreach.hpp>
DLVHEX_NAMESPACE_BEGIN
InconsistencyAnalyzer::InconsistencyAnalyzer(ProgramCtx& ctx) : ctx(ctx){
}
ID InconsistencyAnalyzer::getAuxiliaryAtom(char type, ID id){
OrdinaryAtom oatom(ID::MAINKIND_ATOM | ID::SUBKIND_ATOM_ORDINARYG | ID::PROPERTY_AUX);
oatom.tuple.push_back(ctx.registry()->getAuxiliaryConstantSymbol(type, id));
return ctx.registry()->storeOrdinaryAtom(oatom);
}
Nogood InconsistencyAnalyzer::getInconsistencyReason(BaseModelGenerator* mg, InterpretationConstPtr explAtoms, std::vector<ID>& innerEatoms, OrdinaryASPProgram& program, AnnotatedGroundProgram& annotatedOptimizedProgram, bool* haveInconsistencyReason){
#ifndef NDEBUG
DBGLOG(DBG, "Performing inconsistency analyzis for program:" << std::endl << *program.edb << std::endl << printManyToString<RawPrinter>(program.idb, "\n", ctx.registry()));
#endif
// ground the program without optimization
InternalGrounder grounder(ctx, program, InternalGrounder::builtin);
OrdinaryASPProgram gp = grounder.getGroundProgram();
#ifndef NDEBUG
DBGLOG(DBG, "Unoptimized grounded program:" << std::endl << *gp.edb << std::endl << printManyToString<RawPrinter>(gp.idb, "\n", ctx.registry()));
#endif
InterpretationPtr programAtoms(new Interpretation(*gp.edb));
BOOST_FOREACH (ID ruleID, gp.idb) {
const Rule& rule = ctx.registry()->rules.getByID(ruleID);
BOOST_FOREACH (ID h, rule.head) programAtoms->setFact(h.address);
BOOST_FOREACH (ID b, rule.body) programAtoms->setFact(b.address);
}
// construct analysis program
InterpretationPtr analysisProgramEdb(new Interpretation(ctx.registry()));
OrdinaryASPProgram analysisProgram(ctx.registry(), std::vector<ID>(), analysisProgramEdb, ctx.maxint);
bm::bvector<>::enumerator en, en_end;
int nextAtomID = 0;
ID satAtom = getAuxiliaryAtom('x', ID::termFromInteger(nextAtomID++));
// explanation guess
DBGLOG(DBG, "Adding guessing rules for explanation atoms " << *explAtoms);
InterpretationPtr negExplAtoms(new Interpretation(ctx.registry()));
en = explAtoms->getStorage().first();
en_end = explAtoms->getStorage().end();
while (en < en_end) {
Rule explanationGuess(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR | ID::PROPERTY_RULE_DISJ);
ID eAtomID = ctx.registry()->ogatoms.getIDByAddress(*en);
ID neAtomID = getAuxiliaryAtom('x', eAtomID);
negExplAtoms->setFact(neAtomID.address);
explanationGuess.head.push_back(eAtomID); // atom is in R+
explanationGuess.head.push_back(neAtomID); // atom is in R-
explanationGuess.head.push_back(getAuxiliaryAtom('y', eAtomID)); // atom is neither in R+ nor in R-
analysisProgram.idb.push_back(ctx.registry()->storeRule(explanationGuess));
en++;
}
// interpretation guess and saturation
DBGLOG(DBG, "Adding guessing and saturation rules for program atoms " << *programAtoms);
en = programAtoms->getStorage().first();
en_end = programAtoms->getStorage().end();
while (en < en_end) {
// interpretation guess
Rule interpretationGuess(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR | ID::PROPERTY_RULE_DISJ);
ID atomID = ctx.registry()->ogatoms.getIDByAddress(*en);
interpretationGuess.head.push_back(getAuxiliaryAtom('p', atomID)); // atom in interpretation
interpretationGuess.head.push_back(getAuxiliaryAtom('n', atomID)); // -atom in interpretation
analysisProgram.idb.push_back(ctx.registry()->storeRule(interpretationGuess));
// saturation on discrepancy of interpretation guess from explanation guess
{
Rule discrepancy(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);
discrepancy.head.push_back(satAtom);
discrepancy.body.push_back(ID::posLiteralFromAtom(atomID)); // atom in explanation guess
discrepancy.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('n', atomID))); // -atom in interpretation
analysisProgram.idb.push_back(ctx.registry()->storeRule(discrepancy));
}{
Rule discrepancy(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);
discrepancy.head.push_back(satAtom);
discrepancy.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('x', atomID))); // atom in explanation guess
discrepancy.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('p', atomID))); // -atom in interpretation
analysisProgram.idb.push_back(ctx.registry()->storeRule(discrepancy));
}
{
Rule satInterpretation(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);
satInterpretation.head.push_back(getAuxiliaryAtom('p', atomID)); // -atom in interpretation
satInterpretation.body.push_back(ID::posLiteralFromAtom(satAtom));
analysisProgram.idb.push_back(ctx.registry()->storeRule(satInterpretation));
}{
Rule satInterpretation(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);
satInterpretation.head.push_back(getAuxiliaryAtom('n', atomID)); // -atom in interpretation
satInterpretation.body.push_back(ID::posLiteralFromAtom(satAtom));
analysisProgram.idb.push_back(ctx.registry()->storeRule(satInterpretation));
}
en++;
}
// saturation for non-models
en = gp.edb->getStorage().first();
en_end = gp.edb->getStorage().end();
while (en < en_end) {
// explanation atoms cannot be part of the EDB
if (!explAtoms->getFact(*en)) {
Rule satOnModelRule(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);
satOnModelRule.head.push_back(satAtom);
satOnModelRule.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('n', ctx.registry()->ogatoms.getIDByAddress(*en))));
analysisProgram.idb.push_back(ctx.registry()->storeRule(satOnModelRule));
}
en++;
}
BOOST_FOREACH (ID ruleID, gp.idb) {
DBGLOG(DBG, "Adding saturation rule for program rule " << printToString<RawPrinter>(ruleID, ctx.registry()));
const Rule& rule = ctx.registry()->rules.getByID(ruleID);
Rule satOnModelRule(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);
satOnModelRule.head.push_back(satAtom);
BOOST_FOREACH (ID h, rule.head) { satOnModelRule.body.push_back(getAuxiliaryAtom('n', h)); }
BOOST_FOREACH (ID b, rule.body) {
if (!b.isNaf()) {
satOnModelRule.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('p', ID::atomFromLiteral(b))));
}else{
satOnModelRule.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('n', ID::atomFromLiteral(b))));
}
}
analysisProgram.idb.push_back(ctx.registry()->storeRule(satOnModelRule));
}
// restrict search to models with atom sat
{
DBGLOG(DBG, "Adding sat constraint");
Rule satConstraint(ID::MAINKIND_RULE | ID::SUBKIND_RULE_CONSTRAINT);
satConstraint.body.push_back(ID::nafLiteralFromAtom(satAtom));
analysisProgram.idb.push_back(ctx.registry()->storeRule(satConstraint));
}
#ifndef NDEBUG
if (!!gp.edb) {
DBGLOG(DBG, "Analysis program:" << std::endl << *gp.edb << std::endl << printManyToString<RawPrinter>(analysisProgram.idb, "\n", ctx.registry()));
}else{
DBGLOG(DBG, "Analysis program:" << std::endl << printManyToString<RawPrinter>(analysisProgram.idb, "\n", ctx.registry()));
}
#endif
// solve the instance
GenuineGroundSolverPtr analysisSolver = GenuineGroundSolver::getInstance(ctx, analysisProgram);
InterpretationConstPtr model;
while ( (model = analysisSolver->getNextModel()) != InterpretationConstPtr() ) {
DBGLOG(DBG, "Answer set of analysis program: " << *model);
// extract explanation
Nogood explanation;
en = model->getStorage().first();
en_end = model->getStorage().end();
while (en < en_end) {
if (explAtoms->getFact(*en)) explanation.insert(NogoodContainer::createLiteral(*en, true));
else if (negExplAtoms->getFact(*en)) explanation.insert(NogoodContainer::createLiteral(ctx.registry()->getIDByAuxiliaryConstantSymbol(ctx.registry()->ogatoms.getByAddress(*en).tuple[0]).address, false));
en++;
}
DBGLOG(DBG, "Explanation: " << explanation.getStringRepresentation(ctx.registry()));
if (ctx.config.getOption("UserInconsistencyAnalysis")) {
std::cout << "Inconsistency explanation: " << explanation.getStringRepresentation(ctx.registry()) << std::endl;
}
}
return Nogood();
}
DLVHEX_NAMESPACE_END
// vim:expandtab:ts=4:sw=4:
// mode: C++
// End:
<commit_msg>fix debug output<commit_after>/* dlvhex -- Answer-Set Programming with external interfaces.
* Copyright (C) 2005-2007 Roman Schindlauer
* Copyright (C) 2006-2015 Thomas Krennwallner
* Copyright (C) 2009-2016 Peter Schüller
* Copyright (C) 2011-2016 Christoph Redl
* Copyright (C) 2015-2016 Tobias Kaminski
* Copyright (C) 2015-2016 Antonius Weinzierl
*
* This file is part of dlvhex.
*
* dlvhex 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.
*
* dlvhex 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 dlvhex; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA.
*/
/**
* @file InconsistencyAnalyzer.cpp
* @author Christoph Redl
* @date Wed April 20 2016
*
* @brief Computes a reason for the inconsistency in a program unit.
*
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "dlvhex2/BaseModelGenerator.h"
#include "dlvhex2/InconsistencyAnalyzer.h"
#include "dlvhex2/Printer.h"
#include "dlvhex2/ProgramCtx.h"
#include "dlvhex2/Benchmarking.h"
#include "dlvhex2/Benchmarking.h"
#include "dlvhex2/InternalGrounder.h"
#include "dlvhex2/SATSolver.h"
#include <boost/graph/breadth_first_search.hpp>
#include <boost/graph/visitors.hpp>
#include <boost/graph/strong_components.hpp>
#include <boost/graph/filtered_graph.hpp>
#include <boost/foreach.hpp>
DLVHEX_NAMESPACE_BEGIN
InconsistencyAnalyzer::InconsistencyAnalyzer(ProgramCtx& ctx) : ctx(ctx){
}
ID InconsistencyAnalyzer::getAuxiliaryAtom(char type, ID id){
OrdinaryAtom oatom(ID::MAINKIND_ATOM | ID::SUBKIND_ATOM_ORDINARYG | ID::PROPERTY_AUX);
oatom.tuple.push_back(ctx.registry()->getAuxiliaryConstantSymbol(type, id));
return ctx.registry()->storeOrdinaryAtom(oatom);
}
Nogood InconsistencyAnalyzer::getInconsistencyReason(BaseModelGenerator* mg, InterpretationConstPtr explAtoms, std::vector<ID>& innerEatoms, OrdinaryASPProgram& program, AnnotatedGroundProgram& annotatedOptimizedProgram, bool* haveInconsistencyReason){
#ifndef NDEBUG
DBGLOG(DBG, "Performing inconsistency analyzis for program:" << std::endl << *program.edb << std::endl << printManyToString<RawPrinter>(program.idb, "\n", ctx.registry()));
#endif
// ground the program without optimization
InternalGrounder grounder(ctx, program, InternalGrounder::builtin);
OrdinaryASPProgram gp = grounder.getGroundProgram();
#ifndef NDEBUG
DBGLOG(DBG, "Unoptimized grounded program:" << std::endl << *gp.edb << std::endl << printManyToString<RawPrinter>(gp.idb, "\n", ctx.registry()));
#endif
InterpretationPtr programAtoms(new Interpretation(*gp.edb));
BOOST_FOREACH (ID ruleID, gp.idb) {
const Rule& rule = ctx.registry()->rules.getByID(ruleID);
BOOST_FOREACH (ID h, rule.head) programAtoms->setFact(h.address);
BOOST_FOREACH (ID b, rule.body) programAtoms->setFact(b.address);
}
// construct analysis program
InterpretationPtr analysisProgramEdb(new Interpretation(ctx.registry()));
OrdinaryASPProgram analysisProgram(ctx.registry(), std::vector<ID>(), analysisProgramEdb, ctx.maxint);
bm::bvector<>::enumerator en, en_end;
int nextAtomID = 0;
ID satAtom = getAuxiliaryAtom('x', ID::termFromInteger(nextAtomID++));
// explanation guess
DBGLOG(DBG, "Adding guessing rules for explanation atoms " << *explAtoms);
InterpretationPtr negExplAtoms(new Interpretation(ctx.registry()));
en = explAtoms->getStorage().first();
en_end = explAtoms->getStorage().end();
while (en < en_end) {
Rule explanationGuess(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR | ID::PROPERTY_RULE_DISJ);
ID eAtomID = ctx.registry()->ogatoms.getIDByAddress(*en);
ID neAtomID = getAuxiliaryAtom('x', eAtomID);
negExplAtoms->setFact(neAtomID.address);
explanationGuess.head.push_back(eAtomID); // atom is in R+
explanationGuess.head.push_back(neAtomID); // atom is in R-
explanationGuess.head.push_back(getAuxiliaryAtom('y', eAtomID)); // atom is neither in R+ nor in R-
analysisProgram.idb.push_back(ctx.registry()->storeRule(explanationGuess));
en++;
}
// interpretation guess and saturation
DBGLOG(DBG, "Adding guessing and saturation rules for program atoms " << *programAtoms);
en = programAtoms->getStorage().first();
en_end = programAtoms->getStorage().end();
while (en < en_end) {
// interpretation guess
Rule interpretationGuess(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR | ID::PROPERTY_RULE_DISJ);
ID atomID = ctx.registry()->ogatoms.getIDByAddress(*en);
interpretationGuess.head.push_back(getAuxiliaryAtom('p', atomID)); // atom in interpretation
interpretationGuess.head.push_back(getAuxiliaryAtom('n', atomID)); // -atom in interpretation
analysisProgram.idb.push_back(ctx.registry()->storeRule(interpretationGuess));
// saturation on discrepancy of interpretation guess from explanation guess
{
Rule discrepancy(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);
discrepancy.head.push_back(satAtom);
discrepancy.body.push_back(ID::posLiteralFromAtom(atomID)); // atom in explanation guess
discrepancy.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('n', atomID))); // -atom in interpretation
analysisProgram.idb.push_back(ctx.registry()->storeRule(discrepancy));
}{
Rule discrepancy(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);
discrepancy.head.push_back(satAtom);
discrepancy.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('x', atomID))); // atom in explanation guess
discrepancy.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('p', atomID))); // -atom in interpretation
analysisProgram.idb.push_back(ctx.registry()->storeRule(discrepancy));
}
{
Rule satInterpretation(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);
satInterpretation.head.push_back(getAuxiliaryAtom('p', atomID)); // -atom in interpretation
satInterpretation.body.push_back(ID::posLiteralFromAtom(satAtom));
analysisProgram.idb.push_back(ctx.registry()->storeRule(satInterpretation));
}{
Rule satInterpretation(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);
satInterpretation.head.push_back(getAuxiliaryAtom('n', atomID)); // -atom in interpretation
satInterpretation.body.push_back(ID::posLiteralFromAtom(satAtom));
analysisProgram.idb.push_back(ctx.registry()->storeRule(satInterpretation));
}
en++;
}
// saturation for non-models
en = gp.edb->getStorage().first();
en_end = gp.edb->getStorage().end();
while (en < en_end) {
// explanation atoms cannot be part of the EDB
// if (!explAtoms->getFact(*en)) {
Rule satOnModelRule(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);
satOnModelRule.head.push_back(satAtom);
satOnModelRule.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('n', ctx.registry()->ogatoms.getIDByAddress(*en))));
analysisProgram.idb.push_back(ctx.registry()->storeRule(satOnModelRule));
// }
en++;
}
BOOST_FOREACH (ID ruleID, gp.idb) {
DBGLOG(DBG, "Adding saturation rule for program rule " << printToString<RawPrinter>(ruleID, ctx.registry()));
const Rule& rule = ctx.registry()->rules.getByID(ruleID);
Rule satOnModelRule(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);
satOnModelRule.head.push_back(satAtom);
BOOST_FOREACH (ID h, rule.head) { satOnModelRule.body.push_back(getAuxiliaryAtom('n', h)); }
BOOST_FOREACH (ID b, rule.body) {
if (!b.isNaf()) {
satOnModelRule.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('p', ID::atomFromLiteral(b))));
}else{
satOnModelRule.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('n', ID::atomFromLiteral(b))));
}
}
analysisProgram.idb.push_back(ctx.registry()->storeRule(satOnModelRule));
}
// restrict search to models with atom sat
{
DBGLOG(DBG, "Adding sat constraint");
Rule satConstraint(ID::MAINKIND_RULE | ID::SUBKIND_RULE_CONSTRAINT);
satConstraint.body.push_back(ID::nafLiteralFromAtom(satAtom));
analysisProgram.idb.push_back(ctx.registry()->storeRule(satConstraint));
}
#ifndef NDEBUG
if (!!gp.edb) {
DBGLOG(DBG, "Analysis program:" << std::endl << *analysisProgramEdb.edb << std::endl << printManyToString<RawPrinter>(analysisProgram.idb, "\n", ctx.registry()));
}else{
DBGLOG(DBG, "Analysis program:" << std::endl << printManyToString<RawPrinter>(analysisProgram.idb, "\n", ctx.registry()));
}
#endif
// solve the instance
GenuineGroundSolverPtr analysisSolver = GenuineGroundSolver::getInstance(ctx, analysisProgram);
InterpretationConstPtr model;
while ( (model = analysisSolver->getNextModel()) != InterpretationConstPtr() ) {
DBGLOG(DBG, "Answer set of analysis program: " << *model);
// extract explanation
Nogood explanation;
en = model->getStorage().first();
en_end = model->getStorage().end();
while (en < en_end) {
if (explAtoms->getFact(*en)) explanation.insert(NogoodContainer::createLiteral(*en, true));
else if (negExplAtoms->getFact(*en)) explanation.insert(NogoodContainer::createLiteral(ctx.registry()->getIDByAuxiliaryConstantSymbol(ctx.registry()->ogatoms.getByAddress(*en).tuple[0]).address, false));
en++;
}
DBGLOG(DBG, "Explanation: " << explanation.getStringRepresentation(ctx.registry()));
if (ctx.config.getOption("UserInconsistencyAnalysis")) {
std::cout << "Inconsistency explanation: " << explanation.getStringRepresentation(ctx.registry()) << std::endl;
}
}
return Nogood();
}
DLVHEX_NAMESPACE_END
// vim:expandtab:ts=4:sw=4:
// mode: C++
// End:
<|endoftext|>
|
<commit_before>/***********************************************************************
filename: CEGUIIrrlichtTexture.cpp
created: Tue Mar 3 2009
author: Paul D Turner (based on original code by Thomas Suter)
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS 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.
***************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "CEGUIIrrlichtTexture.h"
#include "CEGUISystem.h"
#include "CEGUIExceptions.h"
#include "CEGUIImageCodec.h"
#include <irrlicht.h>
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
uint32 IrrlichtTexture::d_textureNumber = 0;
//----------------------------------------------------------------------------//
void IrrlichtTexture::setIrrlichtTexture(irr::video::ITexture* tex)
{
d_texture = tex;
if (d_texture)
{
d_size = d_dataSize = Size<>(
static_cast<float>(d_texture->getSize().Width),
static_cast<float>(d_texture->getSize().Height));
updateCachedScaleValues();
}
}
//----------------------------------------------------------------------------//
irr::video::ITexture* IrrlichtTexture::getIrrlichtTexture() const
{
return d_texture;
}
//----------------------------------------------------------------------------//
const String& IrrlichtTexture::getName() const
{
return d_name;
}
//----------------------------------------------------------------------------//
const Size<>& IrrlichtTexture::getSize() const
{
return d_size;
}
//----------------------------------------------------------------------------//
const Size<>& IrrlichtTexture::getOriginalDataSize() const
{
return d_dataSize;
}
//----------------------------------------------------------------------------//
const Vector2<>& IrrlichtTexture::getTexelScaling() const
{
return d_texelScaling;
}
//----------------------------------------------------------------------------//
void IrrlichtTexture::loadFromFile(const String& filename,
const String& resourceGroup)
{
// get and check existence of CEGUI::System object
System* sys = System::getSingletonPtr();
if (!sys)
CEGUI_THROW(RendererException("IrrlichtTexture::loadFromFile: "
"CEGUI::System object has not been created!"));
// load file to memory via resource provider
RawDataContainer texFile;
sys->getResourceProvider()->loadRawDataContainer(filename, texFile,
resourceGroup);
Texture* res = sys->getImageCodec().load(texFile, this);
// unload file data buffer
sys->getResourceProvider()->unloadRawDataContainer(texFile);
// throw exception if data was load loaded to texture.
if (!res)
CEGUI_THROW(RendererException("IrrlichtTexture::loadFromFile: " +
sys->getImageCodec().getIdentifierString() +
" failed to load image '" + filename + "'."));
}
//----------------------------------------------------------------------------//
void IrrlichtTexture::loadFromMemory(const void* buffer,
const Size<>& buffer_size,
PixelFormat pixel_format)
{
using namespace irr;
freeIrrlichtTexture();
createIrrlichtTexture(buffer_size);
d_size.d_width = static_cast<float>(d_texture->getSize().Width);
d_size.d_height = static_cast<float>(d_texture->getSize().Height);
d_dataSize = buffer_size;
updateCachedScaleValues();
const size_t pix_sz = (pixel_format == PF_RGB) ? 3 : 4;
const char* src = static_cast<const char*>(buffer);
char* dest = static_cast<char*>(d_texture->lock());
// copy data into texture, swapping red & blue and creating alpha channel
// values as needed.
for (int j = 0; j < buffer_size.d_height; ++j)
{
for (int i = 0; i < buffer_size.d_width; ++i)
{
dest[i * 4 + 0] = src[i * pix_sz + 2];
dest[i * 4 + 1] = src[i * pix_sz + 1];
dest[i * 4 + 2] = src[i * pix_sz + 0];
dest[i * 4 + 3] = (pix_sz == 3) ? 0xFF : src[i * pix_sz + 3];
}
src += static_cast<int>(buffer_size.d_width * pix_sz);
dest += static_cast<int>(d_size.d_width * 4);
}
d_texture->unlock();
}
//----------------------------------------------------------------------------//
void IrrlichtTexture::blitFromMemory(void* sourceData, const Rect<>& area)
{
CEGUI_THROW(InvalidRequestException("IrrlichtTexture::blitFromMemory: "
"Function is unimplemented!"));
}
//----------------------------------------------------------------------------//
void IrrlichtTexture::blitToMemory(void* targetData)
{
if (!d_texture)
return;
const size_t sz = static_cast<size_t>(d_size.d_width * d_size.d_height) * 4;
memcpy(targetData, d_texture->lock(), sz);
d_texture->unlock();
}
//----------------------------------------------------------------------------//
IrrlichtTexture::IrrlichtTexture(IrrlichtRenderer& owner,
irr::video::IVideoDriver& driver,
const String& name) :
d_driver(driver),
d_texture(0),
d_size(0, 0),
d_dataSize(0, 0),
d_texelScaling(0, 0),
d_owner(owner),
d_name(name)
{
}
//----------------------------------------------------------------------------//
IrrlichtTexture::IrrlichtTexture(IrrlichtRenderer& owner,
irr::video::IVideoDriver& driver,
const String& name,
const String& filename,
const String& resourceGroup) :
d_driver(driver),
d_texture(0),
d_owner(owner),
d_name(name)
{
loadFromFile(filename, resourceGroup);
}
//----------------------------------------------------------------------------//
IrrlichtTexture::IrrlichtTexture(IrrlichtRenderer& owner,
irr::video::IVideoDriver& driver,
const String& name,
const Size<>& size) :
d_driver(driver),
d_dataSize(size),
d_owner(owner),
d_name(name)
{
createIrrlichtTexture(size);
d_size.d_width = static_cast<float>(d_texture->getSize().Width);
d_size.d_height = static_cast<float>(d_texture->getSize().Height);
updateCachedScaleValues();
}
//----------------------------------------------------------------------------//
IrrlichtTexture::~IrrlichtTexture()
{
freeIrrlichtTexture();
}
//----------------------------------------------------------------------------//
void IrrlichtTexture::createIrrlichtTexture(const Size<>& sz)
{
using namespace irr;
const Size<> tex_sz(d_owner.getAdjustedTextureSize(sz));
#if CEGUI_IRR_SDK_VERSION >= 16
const core::dimension2d<u32> irr_sz(
static_cast<u32>(tex_sz.d_width),
static_cast<u32>(tex_sz.d_height));
#else
const core::dimension2d<s32> irr_sz(
static_cast<s32>(tex_sz.d_width),
static_cast<s32>(tex_sz.d_height));
#endif
// save texture creation state
video::E_TEXTURE_CREATION_FLAG fmtflg;
if (d_driver.getTextureCreationFlag(video::ETCF_ALWAYS_32_BIT))
fmtflg = video::ETCF_ALWAYS_32_BIT;
else if (d_driver.getTextureCreationFlag(video::ETCF_OPTIMIZED_FOR_QUALITY))
fmtflg = video::ETCF_OPTIMIZED_FOR_QUALITY;
else if (d_driver.getTextureCreationFlag(video::ETCF_OPTIMIZED_FOR_SPEED))
fmtflg = video::ETCF_OPTIMIZED_FOR_SPEED;
else
fmtflg = video::ETCF_ALWAYS_16_BIT;
const bool tfmips =
d_driver.getTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS);
const bool tfalpha =
d_driver.getTextureCreationFlag(video::ETCF_NO_ALPHA_CHANNEL);
const bool tfnpot =
d_driver.getTextureCreationFlag(video::ETCF_ALLOW_NON_POWER_2);
// explicitly set all states to what we want
d_driver.setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT, true);
d_driver.setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false);
d_driver.setTextureCreationFlag(video::ETCF_NO_ALPHA_CHANNEL, false);
d_driver.setTextureCreationFlag(video::ETCF_ALLOW_NON_POWER_2, true);
d_texture = d_driver.addTexture(irr_sz, getUniqueName().c_str(),
irr::video::ECF_A8R8G8B8);
// restore previous texture creation state
d_driver.setTextureCreationFlag(fmtflg, true);
d_driver.setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, tfmips);
d_driver.setTextureCreationFlag(video::ETCF_NO_ALPHA_CHANNEL, tfalpha);
d_driver.setTextureCreationFlag(video::ETCF_ALLOW_NON_POWER_2, tfnpot);
// we use ARGB all the time for now, so throw if we gut something else!
if(video::ECF_A8R8G8B8 != d_texture->getColorFormat())
CEGUI_THROW(RendererException(
"IrrlichtTexture::loadFromMemory: texture did "
"not have the correct format (ARGB)"));
}
//----------------------------------------------------------------------------//
void IrrlichtTexture::freeIrrlichtTexture()
{
if (!d_texture)
return;
d_driver.removeTexture(d_texture);
d_texture = 0;
}
//----------------------------------------------------------------------------//
std::string IrrlichtTexture::getUniqueName()
{
char tmp[32];
sprintf(tmp, "irr_tex_%d", d_textureNumber++);
return std::string(tmp);
}
//----------------------------------------------------------------------------//
void IrrlichtTexture::setOriginalDataSize(const Size<>& sz)
{
d_dataSize = sz;
updateCachedScaleValues();
}
//----------------------------------------------------------------------------//
void IrrlichtTexture::updateCachedScaleValues()
{
//
// calculate what to use for x scale
//
const float orgW = d_dataSize.d_width;
const float texW = d_size.d_width;
// if texture and original data width are the same, scale is based
// on the original size.
// if texture is wider (and source data was not stretched), scale
// is based on the size of the resulting texture.
d_texelScaling.d_x = 1.0f / ((orgW == texW) ? orgW : texW);
//
// calculate what to use for y scale
//
const float orgH = d_dataSize.d_height;
const float texH = d_size.d_height;
// if texture and original data height are the same, scale is based
// on the original size.
// if texture is taller (and source data was not stretched), scale
// is based on the size of the resulting texture.
d_texelScaling.d_y = 1.0f / ((orgH == texH) ? orgH : texH);
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
<commit_msg>Implement blit functions for Irrlicht renderer. Currently these seem to not work when copying to a render target.<commit_after>/***********************************************************************
filename: CEGUIIrrlichtTexture.cpp
created: Tue Mar 3 2009
author: Paul D Turner (based on original code by Thomas Suter)
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS 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.
***************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "CEGUIIrrlichtTexture.h"
#include "CEGUISystem.h"
#include "CEGUIExceptions.h"
#include "CEGUIImageCodec.h"
#include <irrlicht.h>
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
uint32 IrrlichtTexture::d_textureNumber = 0;
//----------------------------------------------------------------------------//
void IrrlichtTexture::setIrrlichtTexture(irr::video::ITexture* tex)
{
d_texture = tex;
if (d_texture)
{
d_size = d_dataSize = Size<>(
static_cast<float>(d_texture->getSize().Width),
static_cast<float>(d_texture->getSize().Height));
updateCachedScaleValues();
}
}
//----------------------------------------------------------------------------//
irr::video::ITexture* IrrlichtTexture::getIrrlichtTexture() const
{
return d_texture;
}
//----------------------------------------------------------------------------//
const String& IrrlichtTexture::getName() const
{
return d_name;
}
//----------------------------------------------------------------------------//
const Size<>& IrrlichtTexture::getSize() const
{
return d_size;
}
//----------------------------------------------------------------------------//
const Size<>& IrrlichtTexture::getOriginalDataSize() const
{
return d_dataSize;
}
//----------------------------------------------------------------------------//
const Vector2<>& IrrlichtTexture::getTexelScaling() const
{
return d_texelScaling;
}
//----------------------------------------------------------------------------//
void IrrlichtTexture::loadFromFile(const String& filename,
const String& resourceGroup)
{
// get and check existence of CEGUI::System object
System* sys = System::getSingletonPtr();
if (!sys)
CEGUI_THROW(RendererException("IrrlichtTexture::loadFromFile: "
"CEGUI::System object has not been created!"));
// load file to memory via resource provider
RawDataContainer texFile;
sys->getResourceProvider()->loadRawDataContainer(filename, texFile,
resourceGroup);
Texture* res = sys->getImageCodec().load(texFile, this);
// unload file data buffer
sys->getResourceProvider()->unloadRawDataContainer(texFile);
// throw exception if data was load loaded to texture.
if (!res)
CEGUI_THROW(RendererException("IrrlichtTexture::loadFromFile: " +
sys->getImageCodec().getIdentifierString() +
" failed to load image '" + filename + "'."));
}
//----------------------------------------------------------------------------//
void IrrlichtTexture::loadFromMemory(const void* buffer,
const Size<>& buffer_size,
PixelFormat pixel_format)
{
using namespace irr;
freeIrrlichtTexture();
createIrrlichtTexture(buffer_size);
d_size.d_width = static_cast<float>(d_texture->getSize().Width);
d_size.d_height = static_cast<float>(d_texture->getSize().Height);
d_dataSize = buffer_size;
updateCachedScaleValues();
const size_t pix_sz = (pixel_format == PF_RGB) ? 3 : 4;
const char* src = static_cast<const char*>(buffer);
char* dest = static_cast<char*>(d_texture->lock());
// copy data into texture, swapping red & blue and creating alpha channel
// values as needed.
for (int j = 0; j < buffer_size.d_height; ++j)
{
for (int i = 0; i < buffer_size.d_width; ++i)
{
dest[i * 4 + 0] = src[i * pix_sz + 2];
dest[i * 4 + 1] = src[i * pix_sz + 1];
dest[i * 4 + 2] = src[i * pix_sz + 0];
dest[i * 4 + 3] = (pix_sz == 3) ? 0xFF : src[i * pix_sz + 3];
}
src += static_cast<int>(buffer_size.d_width * pix_sz);
dest += static_cast<int>(d_size.d_width * 4);
}
d_texture->unlock();
}
//----------------------------------------------------------------------------//
void IrrlichtTexture::blitFromMemory(void* sourceData, const Rect<>& area)
{
if (!d_texture)
return;
const size_t pitch = d_texture->getPitch();
const uint32* src = static_cast<uint32*>(sourceData);
uint32* dst = static_cast<uint32*>(d_texture->lock());
if (!dst)
CEGUI_THROW(RendererException(
"[IrrlichtRenderer] ITexture::lock failed."));
dst += static_cast<size_t>(area.top()) * (pitch / 4) +
static_cast<size_t>(area.left());
const Size<> sz(area.getSize());
for (int j = 0; j < sz.d_height; ++j)
{
for (int i = 0; i < sz.d_width; ++i)
{
dst[i] = src[i];
}
src += static_cast<int>(sz.d_width);
dst += pitch / 4;
}
d_texture->unlock();
}
//----------------------------------------------------------------------------//
void IrrlichtTexture::blitToMemory(void* targetData)
{
if (!d_texture)
return;
const void* src = d_texture->lock(true);
if (!src)
CEGUI_THROW(RendererException(
"[IrrlichtRenderer] ITexture::lock failed."));
memcpy(targetData, src,
static_cast<size_t>(d_size.d_width * d_size.d_height) * 4);
d_texture->unlock();
}
//----------------------------------------------------------------------------//
IrrlichtTexture::IrrlichtTexture(IrrlichtRenderer& owner,
irr::video::IVideoDriver& driver,
const String& name) :
d_driver(driver),
d_texture(0),
d_size(0, 0),
d_dataSize(0, 0),
d_texelScaling(0, 0),
d_owner(owner),
d_name(name)
{
}
//----------------------------------------------------------------------------//
IrrlichtTexture::IrrlichtTexture(IrrlichtRenderer& owner,
irr::video::IVideoDriver& driver,
const String& name,
const String& filename,
const String& resourceGroup) :
d_driver(driver),
d_texture(0),
d_owner(owner),
d_name(name)
{
loadFromFile(filename, resourceGroup);
}
//----------------------------------------------------------------------------//
IrrlichtTexture::IrrlichtTexture(IrrlichtRenderer& owner,
irr::video::IVideoDriver& driver,
const String& name,
const Size<>& size) :
d_driver(driver),
d_dataSize(size),
d_owner(owner),
d_name(name)
{
createIrrlichtTexture(size);
d_size.d_width = static_cast<float>(d_texture->getSize().Width);
d_size.d_height = static_cast<float>(d_texture->getSize().Height);
updateCachedScaleValues();
}
//----------------------------------------------------------------------------//
IrrlichtTexture::~IrrlichtTexture()
{
freeIrrlichtTexture();
}
//----------------------------------------------------------------------------//
void IrrlichtTexture::createIrrlichtTexture(const Size<>& sz)
{
using namespace irr;
const Size<> tex_sz(d_owner.getAdjustedTextureSize(sz));
#if CEGUI_IRR_SDK_VERSION >= 16
const core::dimension2d<u32> irr_sz(
static_cast<u32>(tex_sz.d_width),
static_cast<u32>(tex_sz.d_height));
#else
const core::dimension2d<s32> irr_sz(
static_cast<s32>(tex_sz.d_width),
static_cast<s32>(tex_sz.d_height));
#endif
// save texture creation state
video::E_TEXTURE_CREATION_FLAG fmtflg;
if (d_driver.getTextureCreationFlag(video::ETCF_ALWAYS_32_BIT))
fmtflg = video::ETCF_ALWAYS_32_BIT;
else if (d_driver.getTextureCreationFlag(video::ETCF_OPTIMIZED_FOR_QUALITY))
fmtflg = video::ETCF_OPTIMIZED_FOR_QUALITY;
else if (d_driver.getTextureCreationFlag(video::ETCF_OPTIMIZED_FOR_SPEED))
fmtflg = video::ETCF_OPTIMIZED_FOR_SPEED;
else
fmtflg = video::ETCF_ALWAYS_16_BIT;
const bool tfmips =
d_driver.getTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS);
const bool tfalpha =
d_driver.getTextureCreationFlag(video::ETCF_NO_ALPHA_CHANNEL);
const bool tfnpot =
d_driver.getTextureCreationFlag(video::ETCF_ALLOW_NON_POWER_2);
// explicitly set all states to what we want
d_driver.setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT, true);
d_driver.setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false);
d_driver.setTextureCreationFlag(video::ETCF_NO_ALPHA_CHANNEL, false);
d_driver.setTextureCreationFlag(video::ETCF_ALLOW_NON_POWER_2, true);
d_texture = d_driver.addTexture(irr_sz, getUniqueName().c_str(),
irr::video::ECF_A8R8G8B8);
// restore previous texture creation state
d_driver.setTextureCreationFlag(fmtflg, true);
d_driver.setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, tfmips);
d_driver.setTextureCreationFlag(video::ETCF_NO_ALPHA_CHANNEL, tfalpha);
d_driver.setTextureCreationFlag(video::ETCF_ALLOW_NON_POWER_2, tfnpot);
// we use ARGB all the time for now, so throw if we gut something else!
if(video::ECF_A8R8G8B8 != d_texture->getColorFormat())
CEGUI_THROW(RendererException(
"IrrlichtTexture::loadFromMemory: texture did "
"not have the correct format (ARGB)"));
}
//----------------------------------------------------------------------------//
void IrrlichtTexture::freeIrrlichtTexture()
{
if (!d_texture)
return;
d_driver.removeTexture(d_texture);
d_texture = 0;
}
//----------------------------------------------------------------------------//
std::string IrrlichtTexture::getUniqueName()
{
char tmp[32];
sprintf(tmp, "irr_tex_%d", d_textureNumber++);
return std::string(tmp);
}
//----------------------------------------------------------------------------//
void IrrlichtTexture::setOriginalDataSize(const Size<>& sz)
{
d_dataSize = sz;
updateCachedScaleValues();
}
//----------------------------------------------------------------------------//
void IrrlichtTexture::updateCachedScaleValues()
{
//
// calculate what to use for x scale
//
const float orgW = d_dataSize.d_width;
const float texW = d_size.d_width;
// if texture and original data width are the same, scale is based
// on the original size.
// if texture is wider (and source data was not stretched), scale
// is based on the size of the resulting texture.
d_texelScaling.d_x = 1.0f / ((orgW == texW) ? orgW : texW);
//
// calculate what to use for y scale
//
const float orgH = d_dataSize.d_height;
const float texH = d_size.d_height;
// if texture and original data height are the same, scale is based
// on the original size.
// if texture is taller (and source data was not stretched), scale
// is based on the size of the resulting texture.
d_texelScaling.d_y = 1.0f / ((orgH == texH) ? orgH : texH);
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
<|endoftext|>
|
<commit_before>#include <string.h>
#include <signal.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <thread>
#include <set>
#include "msg_filter.hpp"
#include "io_policy/line.hpp"
#include "io_policy/length.hpp"
#include "io_policy/sysv_mq.hpp"
#include "io_policy/tcp.hpp"
#include "sub_entry.hpp"
#include "util.hpp"
#include "logger.hpp"
using namespace std;
using namespace wissbi;
bool run = true;
void exit_signal_handler(int signum) {
run = false;
}
template<class OutputWriter>
void run_sub(const std::string& src) {
int serv = socket(AF_INET, SOCK_STREAM, 0);
sockaddr serv_addr;
util::ConnectStringToSockaddr("0.0.0.0:0", reinterpret_cast<sockaddr_in*>(&serv_addr));
if(-1 == ::bind(serv, &serv_addr, sizeof(serv_addr))) {
logger::log("bind error");
throw std::runtime_error("bind error");
}
if(-1 == listen(serv, 10)) {
logger::log("listen error");
throw std::runtime_error("listen error");
}
socklen_t len = sizeof(serv_addr);;
getsockname(serv, &serv_addr, &len);
logger::log("wissbi-sub is listening on port {}", ntohs(((sockaddr_in*)&serv_addr)->sin_port));
ostringstream tmp;
tmp << util::GetHostIP() << ":" << ntohs(((sockaddr_in*)&serv_addr)->sin_port);
SubEntry sub_entry(getenv("WISSBI_META_DIR") != NULL ? getenv("WISSBI_META_DIR") : "/var/lib/wissbi", src, tmp.str());
OutputWriter output_writer;
output_writer.mq_init("");
output_writer.auto_flush();
thread* output_th = new thread([&output_writer](){
output_writer.FilterLoop();
});
struct timeval tv;
tv.tv_sec = 1;
tv.tv_usec = 0;
setsockopt(serv, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
while(run) {
sockaddr other_addr;
socklen_t len = sizeof(other_addr);
int res = accept(serv, &other_addr, &len);
if(res > 0){
logger::log("wissbi-pub connected from {}", util::SockaddrToConnectString(reinterpret_cast<const sockaddr_in&>(other_addr)));
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 0;
setsockopt(res, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
thread([res]{
MsgFilter<io_policy::TCP, io_policy::SysvMq> filter;
filter.mq_init("");
filter.set_cleanup(false);
filter.AttachConnectedSock(res);
filter.FilterLoop();
}).detach();
}
sub_entry.renew();
}
}
int main(int argc, char* argv[]){
if(argc < 2) {
std::cerr << "Usage: " << argv[0] << " SOURCE_NAME" << std::endl;
return 1;
}
signal(SIGINT, exit_signal_handler);
signal(SIGTERM, exit_signal_handler);
signal(SIGPIPE, exit_signal_handler);
std::string src(argv[1]);
if(getenv("WISSBI_PID_FILE") != NULL) {
ofstream ofs(getenv("WISSBI_PID_FILE"));
ofs << getpid() << endl;
}
char* msg_format = getenv("WISSBI_MESSAGE_FORMAT");
if(msg_format) {
if(std::string(msg_format) == "line") {
run_sub<MsgFilter<io_policy::SysvMq, io_policy::Line>>(src);
}
else if(std::string(msg_format) == "length") {
run_sub<MsgFilter<io_policy::SysvMq, io_policy::Length>>(src);
}
else {
logger::log("unknown message format: {}", msg_format);
return 1;
}
}
else {
run_sub<MsgFilter<io_policy::SysvMq, io_policy::Line>>(src);
}
logger::log("wissbi-sub exited normally");
return 0;
}
<commit_msg>force sub to reset the connection when it exits<commit_after>#include <string.h>
#include <signal.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <thread>
#include <set>
#include "msg_filter.hpp"
#include "io_policy/line.hpp"
#include "io_policy/length.hpp"
#include "io_policy/sysv_mq.hpp"
#include "io_policy/tcp.hpp"
#include "sub_entry.hpp"
#include "util.hpp"
#include "logger.hpp"
using namespace std;
using namespace wissbi;
bool run = true;
void exit_signal_handler(int signum) {
run = false;
}
template<class OutputWriter>
void run_sub(const std::string& src) {
int serv = socket(AF_INET, SOCK_STREAM, 0);
sockaddr serv_addr;
util::ConnectStringToSockaddr("0.0.0.0:0", reinterpret_cast<sockaddr_in*>(&serv_addr));
if(-1 == ::bind(serv, &serv_addr, sizeof(serv_addr))) {
logger::log("bind error");
throw std::runtime_error("bind error");
}
if(-1 == listen(serv, 10)) {
logger::log("listen error");
throw std::runtime_error("listen error");
}
socklen_t len = sizeof(serv_addr);;
getsockname(serv, &serv_addr, &len);
logger::log("wissbi-sub is listening on port {}", ntohs(((sockaddr_in*)&serv_addr)->sin_port));
ostringstream tmp;
tmp << util::GetHostIP() << ":" << ntohs(((sockaddr_in*)&serv_addr)->sin_port);
SubEntry sub_entry(getenv("WISSBI_META_DIR") != NULL ? getenv("WISSBI_META_DIR") : "/var/lib/wissbi", src, tmp.str());
OutputWriter output_writer;
output_writer.mq_init("");
output_writer.auto_flush();
thread* output_th = new thread([&output_writer](){
output_writer.FilterLoop();
});
struct timeval tv;
tv.tv_sec = 1;
tv.tv_usec = 0;
setsockopt(serv, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
while(run) {
sockaddr other_addr;
socklen_t len = sizeof(other_addr);
int res = accept(serv, &other_addr, &len);
if(res > 0){
logger::log("wissbi-pub connected from {}", util::SockaddrToConnectString(reinterpret_cast<const sockaddr_in&>(other_addr)));
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 0;
setsockopt(res, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
struct linger lo = {1, 0};
setsockopt(res, SOL_SOCKET, SO_LINGER, &lo, sizeof(lo));
thread([res]{
MsgFilter<io_policy::TCP, io_policy::SysvMq> filter;
filter.mq_init("");
filter.set_cleanup(false);
filter.AttachConnectedSock(res);
filter.FilterLoop();
}).detach();
}
sub_entry.renew();
}
}
int main(int argc, char* argv[]){
if(argc < 2) {
std::cerr << "Usage: " << argv[0] << " SOURCE_NAME" << std::endl;
return 1;
}
signal(SIGINT, exit_signal_handler);
signal(SIGTERM, exit_signal_handler);
signal(SIGPIPE, exit_signal_handler);
std::string src(argv[1]);
if(getenv("WISSBI_PID_FILE") != NULL) {
ofstream ofs(getenv("WISSBI_PID_FILE"));
ofs << getpid() << endl;
}
char* msg_format = getenv("WISSBI_MESSAGE_FORMAT");
if(msg_format) {
if(std::string(msg_format) == "line") {
run_sub<MsgFilter<io_policy::SysvMq, io_policy::Line>>(src);
}
else if(std::string(msg_format) == "length") {
run_sub<MsgFilter<io_policy::SysvMq, io_policy::Length>>(src);
}
else {
logger::log("unknown message format: {}", msg_format);
return 1;
}
}
else {
run_sub<MsgFilter<io_policy::SysvMq, io_policy::Line>>(src);
}
logger::log("wissbi-sub exited normally");
return 0;
}
<|endoftext|>
|
<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include <cstring>
#include <typeinfo>
#include <pficommon/lang/shared_ptr.h>
#include <pficommon/lang/cast.h>
namespace jubatus {
namespace exception {
namespace detail {
std::string demangle_symbol(const char *symbol);
}
class error_info_base {
public:
virtual bool splitter() const
{
return false;
}
virtual std::string tag_typeid_name() const = 0;
virtual std::string as_string() const = 0;
virtual ~error_info_base() throw()
{}
};
template <class Tag, class V>
class error_info;
template <class Tag, class V>
inline std::string to_string(const error_info<Tag, V>& info)
{
return pfi::lang::lexical_cast<std::string, V>(info.value());
}
template<>
class error_info<struct error_splitter_, void> : public error_info_base {
public:
bool splitter() const
{
return true;
}
std::string tag_typeid_name() const
{
return jubatus::exception::detail::demangle_symbol(typeid(struct error_splitter_*).name());
}
std::string as_string() const
{
// USE splitter or tag_typeid_name
return "-splitter-";
}
};
template <class Tag, class V>
class error_info : public error_info_base {
public:
typedef V value_type;
error_info(value_type v);
~error_info() throw();
std::string tag_typeid_name() const;
std::string as_string() const;
value_type value() const
{
return value_;
}
private:
value_type value_;
};
template <class Tag, class V>
inline error_info<Tag, V>::error_info(value_type v)
: value_(v)
{
}
template <class Tag, class V>
inline error_info<Tag, V>::~error_info() throw()
{
}
template <class Tag, class V>
inline std::string error_info<Tag, V>::tag_typeid_name() const
{
return jubatus::exception::detail::demangle_symbol(typeid(Tag*).name());
}
template <class Tag, class V>
inline std::string error_info<Tag, V>::as_string() const
{
return to_string(*this);
}
} // exception
} // jubatus
<commit_msg>Add pragma_once to common/exception_info.hpp<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#pragma once
#include <cstring>
#include <typeinfo>
#include <pficommon/lang/shared_ptr.h>
#include <pficommon/lang/cast.h>
namespace jubatus {
namespace exception {
namespace detail {
std::string demangle_symbol(const char *symbol);
}
class error_info_base {
public:
virtual bool splitter() const
{
return false;
}
virtual std::string tag_typeid_name() const = 0;
virtual std::string as_string() const = 0;
virtual ~error_info_base() throw()
{}
};
template <class Tag, class V>
class error_info;
template <class Tag, class V>
inline std::string to_string(const error_info<Tag, V>& info)
{
return pfi::lang::lexical_cast<std::string, V>(info.value());
}
template<>
class error_info<struct error_splitter_, void> : public error_info_base {
public:
bool splitter() const
{
return true;
}
std::string tag_typeid_name() const
{
return jubatus::exception::detail::demangle_symbol(typeid(struct error_splitter_*).name());
}
std::string as_string() const
{
// USE splitter or tag_typeid_name
return "-splitter-";
}
};
template <class Tag, class V>
class error_info : public error_info_base {
public:
typedef V value_type;
error_info(value_type v);
~error_info() throw();
std::string tag_typeid_name() const;
std::string as_string() const;
value_type value() const
{
return value_;
}
private:
value_type value_;
};
template <class Tag, class V>
inline error_info<Tag, V>::error_info(value_type v)
: value_(v)
{
}
template <class Tag, class V>
inline error_info<Tag, V>::~error_info() throw()
{
}
template <class Tag, class V>
inline std::string error_info<Tag, V>::tag_typeid_name() const
{
return jubatus::exception::detail::demangle_symbol(typeid(Tag*).name());
}
template <class Tag, class V>
inline std::string error_info<Tag, V>::as_string() const
{
return to_string(*this);
}
} // exception
} // jubatus
<|endoftext|>
|
<commit_before>/*
*
* Copyright 2016 gRPC authors.
*
* 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 <map>
#include "src/compiler/config.h"
#include "src/compiler/generator_helpers.h"
#include "src/compiler/php_generator_helpers.h"
using grpc::protobuf::Descriptor;
using grpc::protobuf::FileDescriptor;
using grpc::protobuf::MethodDescriptor;
using grpc::protobuf::ServiceDescriptor;
using grpc::protobuf::io::Printer;
using grpc::protobuf::io::StringOutputStream;
using std::map;
namespace grpc_php_generator {
namespace {
grpc::string ConvertToPhpNamespace(const grpc::string& name) {
std::vector<grpc::string> tokens = grpc_generator::tokenize(name, ".");
std::ostringstream oss;
for (unsigned int i = 0; i < tokens.size(); i++) {
oss << (i == 0 ? "" : "\\")
<< grpc_generator::CapitalizeFirstLetter(tokens[i]);
}
return oss.str();
}
grpc::string PackageName(const FileDescriptor* file) {
if (file->options().has_php_namespace()) {
return file->options().php_namespace();
} else {
return ConvertToPhpNamespace(file->package());
}
}
grpc::string MessageIdentifierName(const grpc::string& name,
const FileDescriptor* file) {
std::vector<grpc::string> tokens = grpc_generator::tokenize(name, ".");
std::ostringstream oss;
oss << PackageName(file) << "\\"
<< grpc_generator::CapitalizeFirstLetter(tokens[tokens.size() - 1]);
return oss.str();
}
void PrintMethod(const MethodDescriptor* method, Printer* out) {
const Descriptor* input_type = method->input_type();
const Descriptor* output_type = method->output_type();
map<grpc::string, grpc::string> vars;
vars["service_name"] = method->service()->full_name();
vars["name"] = method->name();
vars["input_type_id"] =
MessageIdentifierName(input_type->full_name(), input_type->file());
vars["output_type_id"] =
MessageIdentifierName(output_type->full_name(), output_type->file());
out->Print("/**\n");
out->Print(GetPHPComments(method, " *").c_str());
if (method->client_streaming()) {
out->Print(vars,
" * @param array $$metadata metadata\n"
" * @param array $$options call options\n */\n"
"public function $name$($$metadata = [], "
"$$options = []) {\n");
out->Indent();
out->Indent();
if (method->server_streaming()) {
out->Print("return $$this->_bidiRequest(");
} else {
out->Print("return $$this->_clientStreamRequest(");
}
out->Print(vars,
"'/$service_name$/$name$',\n"
"['\\$output_type_id$','decode'],\n"
"$$metadata, $$options);\n");
} else {
out->Print(vars,
" * @param \\$input_type_id$ $$argument input argument\n"
" * @param array $$metadata metadata\n"
" * @param array $$options call options\n */\n"
"public function $name$(\\$input_type_id$ $$argument,\n"
" $$metadata = [], $$options = []) {\n");
out->Indent();
out->Indent();
if (method->server_streaming()) {
out->Print("return $$this->_serverStreamRequest(");
} else {
out->Print("return $$this->_simpleRequest(");
}
out->Print(vars,
"'/$service_name$/$name$',\n"
"$$argument,\n"
"['\\$output_type_id$', 'decode'],\n"
"$$metadata, $$options);\n");
}
out->Outdent();
out->Outdent();
out->Print("}\n\n");
}
// Prints out the service descriptor object
void PrintService(const ServiceDescriptor* service,
const grpc::string& class_suffix, Printer* out) {
map<grpc::string, grpc::string> vars;
out->Print("/**\n");
out->Print(GetPHPComments(service, " *").c_str());
out->Print(" */\n");
vars["name"] = GetPHPServiceClassname(service, class_suffix);
out->Print(vars, "class $name$ extends \\Grpc\\BaseStub {\n\n");
out->Indent();
out->Indent();
out->Print(
"/**\n * @param string $$hostname hostname\n"
" * @param array $$opts channel options\n"
" * @param \\Grpc\\Channel $$channel (optional) re-use channel "
"object\n */\n"
"public function __construct($$hostname, $$opts, "
"$$channel = null) {\n");
out->Indent();
out->Indent();
out->Print("parent::__construct($$hostname, $$opts, $$channel);\n");
out->Outdent();
out->Outdent();
out->Print("}\n\n");
for (int i = 0; i < service->method_count(); i++) {
grpc::string method_name =
grpc_generator::LowercaseFirstLetter(service->method(i)->name());
PrintMethod(service->method(i), out);
}
out->Outdent();
out->Outdent();
out->Print("}\n");
}
} // namespace
grpc::string GenerateFile(const FileDescriptor* file,
const ServiceDescriptor* service,
const grpc::string& class_suffix) {
grpc::string output;
{
StringOutputStream output_stream(&output);
Printer out(&output_stream, '$');
out.Print("<?php\n");
out.Print("// GENERATED CODE -- DO NOT EDIT!\n\n");
grpc::string leading_comments = GetPHPComments(file, "//");
if (!leading_comments.empty()) {
out.Print("// Original file comments:\n");
out.PrintRaw(leading_comments.c_str());
}
map<grpc::string, grpc::string> vars;
grpc::string php_namespace = PackageName(file);
vars["package"] = php_namespace;
out.Print(vars, "namespace $package$;\n\n");
PrintService(service, class_suffix, &out);
}
return output;
}
} // namespace grpc_php_generator
<commit_msg>update php plugin with protobuf 3.5.0<commit_after>/*
*
* Copyright 2016 gRPC authors.
*
* 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 <map>
#include <google/protobuf/compiler/php/php_generator.h>
#include "src/compiler/config.h"
#include "src/compiler/generator_helpers.h"
#include "src/compiler/php_generator_helpers.h"
using google::protobuf::compiler::php::GeneratedClassName;
using grpc::protobuf::Descriptor;
using grpc::protobuf::FileDescriptor;
using grpc::protobuf::MethodDescriptor;
using grpc::protobuf::ServiceDescriptor;
using grpc::protobuf::io::Printer;
using grpc::protobuf::io::StringOutputStream;
using std::map;
namespace grpc_php_generator {
namespace {
grpc::string ConvertToPhpNamespace(const grpc::string& name) {
std::vector<grpc::string> tokens = grpc_generator::tokenize(name, ".");
std::ostringstream oss;
for (unsigned int i = 0; i < tokens.size(); i++) {
oss << (i == 0 ? "" : "\\")
<< grpc_generator::CapitalizeFirstLetter(tokens[i]);
}
return oss.str();
}
grpc::string PackageName(const FileDescriptor* file) {
if (file->options().has_php_namespace()) {
return file->options().php_namespace();
} else {
return ConvertToPhpNamespace(file->package());
}
}
grpc::string MessageIdentifierName(const grpc::string& name,
const FileDescriptor* file) {
std::vector<grpc::string> tokens = grpc_generator::tokenize(name, ".");
std::ostringstream oss;
if (PackageName(file) != "") {
oss << PackageName(file) << "\\";
}
oss << grpc_generator::CapitalizeFirstLetter(tokens[tokens.size() - 1]);
return oss.str();
}
void PrintMethod(const MethodDescriptor* method, Printer* out) {
const Descriptor* input_type = method->input_type();
const Descriptor* output_type = method->output_type();
map<grpc::string, grpc::string> vars;
vars["service_name"] = method->service()->full_name();
vars["name"] = method->name();
vars["input_type_id"] =
MessageIdentifierName(GeneratedClassName(input_type), input_type->file());
vars["output_type_id"] = MessageIdentifierName(
GeneratedClassName(output_type), output_type->file());
out->Print("/**\n");
out->Print(GetPHPComments(method, " *").c_str());
if (method->client_streaming()) {
out->Print(vars,
" * @param array $$metadata metadata\n"
" * @param array $$options call options\n */\n"
"public function $name$($$metadata = [], "
"$$options = []) {\n");
out->Indent();
out->Indent();
if (method->server_streaming()) {
out->Print("return $$this->_bidiRequest(");
} else {
out->Print("return $$this->_clientStreamRequest(");
}
out->Print(vars,
"'/$service_name$/$name$',\n"
"['\\$output_type_id$','decode'],\n"
"$$metadata, $$options);\n");
} else {
out->Print(vars,
" * @param \\$input_type_id$ $$argument input argument\n"
" * @param array $$metadata metadata\n"
" * @param array $$options call options\n */\n"
"public function $name$(\\$input_type_id$ $$argument,\n"
" $$metadata = [], $$options = []) {\n");
out->Indent();
out->Indent();
if (method->server_streaming()) {
out->Print("return $$this->_serverStreamRequest(");
} else {
out->Print("return $$this->_simpleRequest(");
}
out->Print(vars,
"'/$service_name$/$name$',\n"
"$$argument,\n"
"['\\$output_type_id$', 'decode'],\n"
"$$metadata, $$options);\n");
}
out->Outdent();
out->Outdent();
out->Print("}\n\n");
}
// Prints out the service descriptor object
void PrintService(const ServiceDescriptor* service,
const grpc::string& class_suffix, Printer* out) {
map<grpc::string, grpc::string> vars;
out->Print("/**\n");
out->Print(GetPHPComments(service, " *").c_str());
out->Print(" */\n");
vars["name"] = GetPHPServiceClassname(service, class_suffix);
out->Print(vars, "class $name$ extends \\Grpc\\BaseStub {\n\n");
out->Indent();
out->Indent();
out->Print(
"/**\n * @param string $$hostname hostname\n"
" * @param array $$opts channel options\n"
" * @param \\Grpc\\Channel $$channel (optional) re-use channel "
"object\n */\n"
"public function __construct($$hostname, $$opts, "
"$$channel = null) {\n");
out->Indent();
out->Indent();
out->Print("parent::__construct($$hostname, $$opts, $$channel);\n");
out->Outdent();
out->Outdent();
out->Print("}\n\n");
for (int i = 0; i < service->method_count(); i++) {
grpc::string method_name =
grpc_generator::LowercaseFirstLetter(service->method(i)->name());
PrintMethod(service->method(i), out);
}
out->Outdent();
out->Outdent();
out->Print("}\n");
}
} // namespace
grpc::string GenerateFile(const FileDescriptor* file,
const ServiceDescriptor* service,
const grpc::string& class_suffix) {
grpc::string output;
{
StringOutputStream output_stream(&output);
Printer out(&output_stream, '$');
out.Print("<?php\n");
out.Print("// GENERATED CODE -- DO NOT EDIT!\n\n");
grpc::string leading_comments = GetPHPComments(file, "//");
if (!leading_comments.empty()) {
out.Print("// Original file comments:\n");
out.PrintRaw(leading_comments.c_str());
}
map<grpc::string, grpc::string> vars;
grpc::string php_namespace = PackageName(file);
vars["package"] = php_namespace;
out.Print(vars, "namespace $package$;\n\n");
PrintService(service, class_suffix, &out);
}
return output;
}
} // namespace grpc_php_generator
<|endoftext|>
|
<commit_before>#include <syslog.h>
#include "EventLoop.h"
#include "ControlServer.h"
#include "CMUXManager.h"
int main(int argc, char *argv[]) {
openlog("cmuxcontrold", LOG_PERROR | LOG_PID, LOG_DAEMON);
syslog(LOG_INFO, "CMUX Control Daemon started");
EventLoop loop;
CMUXManager manager(&loop);
ControlServer control(&loop);
loop.addWatcher(&control);
return loop.exec();
}
<commit_msg>Properly daemonize cmuxcontrold.<commit_after>#include <syslog.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/stat.h>
#include <errno.h>
#include "EventLoop.h"
#include "ControlServer.h"
#include "CMUXManager.h"
static int parse_opts(int argc, char **argv, int *daemon, char **pidfile) {
int ch;
*daemon = 0;
*pidfile = 0;
while((ch = getopt(argc, argv, "dp:")) != -1) {
switch(ch) {
case 'd':
*daemon = 1;
break;
case 'p':
*pidfile = optarg;
break;
case '?':
case ':':
return 0;
}
}
return 1;
}
static int daemonize(void) {
pid_t pid = fork();
if(pid == -1)
return 0;
if(pid > 0)
_exit(0);
setsid();
umask(0);
chdir("/");
int null = open("/dev/null", O_RDWR);
dup2(STDIN_FILENO, null);
dup2(STDOUT_FILENO, null);
dup2(STDERR_FILENO, null);
close(null);
pid = fork();
if(pid == -1)
return 0;
if(pid > 0)
_exit(0);
return 1;
}
int main(int argc, char *argv[]) {
int daemon;
char *pidfile;
if(!parse_opts(argc, argv, &daemon, &pidfile))
return 1;
if(daemon) {
if(!daemonize())
return 1;
openlog("cmuxcontrold", LOG_PID, LOG_DAEMON);
} else {
openlog("cmuxcontrold", LOG_PERROR | LOG_PID, LOG_DAEMON);
}
if(pidfile) {
FILE *file = fopen(pidfile, "w");
if(file == NULL) {
syslog(LOG_CRIT, "unable to create pidfile: %s", strerror(errno));
return 1;
}
fprintf(file, "%d\n", getpid());
fclose(file);
}
syslog(LOG_INFO, "CMUX Control Daemon started");
EventLoop loop;
CMUXManager manager(&loop);
ControlServer control(&loop);
loop.addWatcher(&control);
return loop.exec();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/theme_preview_infobar_delegate.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/string_util.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/extensions/extension.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
ThemePreviewInfobarDelegate::ThemePreviewInfobarDelegate(
TabContents* tab_contents, const std::string& name,
const std::string& previous_theme_id)
: ConfirmInfoBarDelegate(tab_contents),
profile_(tab_contents->profile()), name_(name),
previous_theme_id_(previous_theme_id) {
}
void ThemePreviewInfobarDelegate::InfoBarClosed() {
delete this;
}
std::wstring ThemePreviewInfobarDelegate::GetMessageText() const {
return l10n_util::GetStringF(IDS_THEME_INSTALL_INFOBAR_LABEL,
UTF8ToWide(name_));
}
SkBitmap* ThemePreviewInfobarDelegate::GetIcon() const {
// TODO(aa): Reply with the theme's icon, but this requires reading it
// asynchronously from disk.
return ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_INFOBAR_THEME);
}
ThemePreviewInfobarDelegate*
ThemePreviewInfobarDelegate::AsThemePreviewInfobarDelegate() {
return this;
}
int ThemePreviewInfobarDelegate::GetButtons() const {
return BUTTON_CANCEL;
}
std::wstring ThemePreviewInfobarDelegate::GetButtonLabel(
ConfirmInfoBarDelegate::InfoBarButton button) const {
switch (button) {
case BUTTON_CANCEL: {
// TODO(aa): Reusing IDS_UNDO is hack to get around string freeze. This
// should be changed back to IDS_THEME_INSTALL_INFOBAR_UNDO_BUTTON at some
// point.
std::wstring undo_text = l10n_util::GetString(IDS_UNDO);
undo_text.erase(std::remove(undo_text.begin(), undo_text.end(), L'&'),
undo_text.end());
return undo_text;
}
default:
return L"";
}
}
bool ThemePreviewInfobarDelegate::Cancel() {
if (!previous_theme_id_.empty()) {
ExtensionsService* service = profile_->GetExtensionsService();
if (service) {
Extension* previous_theme = service->GetExtensionById(previous_theme_id_);
if (previous_theme) {
profile_->SetTheme(previous_theme);
return true;
}
}
}
profile_->ClearTheme();
return true;
}
<commit_msg>Use IDS_THEME_INSTALL_INFOBAR_UNDO_BUTTON instead of IDS_UNDO since 3.0 shipped.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/theme_preview_infobar_delegate.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/string_util.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/extensions/extension.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
ThemePreviewInfobarDelegate::ThemePreviewInfobarDelegate(
TabContents* tab_contents, const std::string& name,
const std::string& previous_theme_id)
: ConfirmInfoBarDelegate(tab_contents),
profile_(tab_contents->profile()), name_(name),
previous_theme_id_(previous_theme_id) {
}
void ThemePreviewInfobarDelegate::InfoBarClosed() {
delete this;
}
std::wstring ThemePreviewInfobarDelegate::GetMessageText() const {
return l10n_util::GetStringF(IDS_THEME_INSTALL_INFOBAR_LABEL,
UTF8ToWide(name_));
}
SkBitmap* ThemePreviewInfobarDelegate::GetIcon() const {
// TODO(aa): Reply with the theme's icon, but this requires reading it
// asynchronously from disk.
return ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_INFOBAR_THEME);
}
ThemePreviewInfobarDelegate*
ThemePreviewInfobarDelegate::AsThemePreviewInfobarDelegate() {
return this;
}
int ThemePreviewInfobarDelegate::GetButtons() const {
return BUTTON_CANCEL;
}
std::wstring ThemePreviewInfobarDelegate::GetButtonLabel(
ConfirmInfoBarDelegate::InfoBarButton button) const {
switch (button) {
case BUTTON_CANCEL: {
return l10n_util::GetString(IDS_THEME_INSTALL_INFOBAR_UNDO_BUTTON);
}
default:
return L"";
}
}
bool ThemePreviewInfobarDelegate::Cancel() {
if (!previous_theme_id_.empty()) {
ExtensionsService* service = profile_->GetExtensionsService();
if (service) {
Extension* previous_theme = service->GetExtensionById(previous_theme_id_);
if (previous_theme) {
profile_->SetTheme(previous_theme);
return true;
}
}
}
profile_->ClearTheme();
return true;
}
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (C) 2006 by Till Adam <adam@kde.org> *
* *
* This program 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 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 Library 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. *
***************************************************************************/
#include <QDebug>
#include "akonadi.h"
#include "akonadiconnection.h"
#include "storagebackend.h"
#include "storage/datastore.h"
#include "storage/entity.h"
#include "append.h"
#include "response.h"
using namespace Akonadi;
Append::Append()
: Handler(), m_size(-1)
{
}
Append::~Append()
{
}
static QDateTime parseDateTime( const QByteArray & s )
{
// Syntax:
// date-time = DQUOTE date-day-fixed "-" date-month "-" date-year
// SP time SP zone DQUOTE
// date-day-fixed = (SP DIGIT) / 2DIGIT
// ; Fixed-format version of date-day
// date-month = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" /
// "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec"
// date-year = 4DIGIT
// time = 2DIGIT ":" 2DIGIT ":" 2DIGIT
// ; Hours minutes seconds
// zone = ("+" / "-") 4DIGIT
// ; Signed four-digit value of hhmm representing
// ; hours and minutes east of Greenwich (that is,
// ; the amount that the given time differs from
// ; Universal Time). Subtracting the timezone
// ; from the given time will give the UT form.
// ; The Universal Time zone is "+0000".
// Example : "28-May-2006 01:03:35 +0200"
// Position: 0123456789012345678901234567
// 1 2
QDateTime dateTime;
bool ok = true;
const int day = ( s[1] == ' ' ? s[2] - '0' // single digit day
: s.mid( 1, 2 ).toInt( &ok ) );
if ( !ok ) return dateTime;
const QByteArray shortMonthNames( "janfebmaraprmayjunjulaugsepoctnovdec" );
int month = shortMonthNames.indexOf( s.mid( 4, 3 ).toLower() );
if ( month == -1 ) return dateTime;
month = month / 3 + 1;
const int year = s.mid( 8, 4 ).toInt( &ok );
if ( !ok ) return dateTime;
const int hours = s.mid( 13, 2 ).toInt( &ok );
if ( !ok ) return dateTime;
const int minutes = s.mid( 16, 2 ).toInt( &ok );
if ( !ok ) return dateTime;
const int seconds = s.mid( 19, 2 ).toInt( &ok );
if ( !ok ) return dateTime;
const int tzhh = s.mid( 23, 2 ).toInt( &ok );
if ( !ok ) return dateTime;
const int tzmm = s.mid( 25, 2 ).toInt( &ok );
if ( !ok ) return dateTime;
int tzsecs = tzhh*60*60 + tzmm*60;
if ( s[22] == '-' ) tzsecs = -tzsecs;
const QDate date( year, month, day );
const QTime time( hours, minutes, seconds );
dateTime = QDateTime( date, time, Qt::UTC );
if ( !dateTime.isValid() ) return dateTime;
dateTime.addSecs( -tzsecs );
return dateTime;
}
bool Akonadi::Append::handleContinuation( const QByteArray& line )
{
m_data += line;
m_size -= line.size();
if ( !allDataRead() )
return false;
commit();
deleteLater();
return true;
}
bool Akonadi::Append::handleLine(const QByteArray& line )
{
if ( inContinuation() )
return handleContinuation( line );
// Arguments: mailbox name
// OPTIONAL flag parenthesized list
// OPTIONAL date/time string
// message literal
//
// Syntax:
// append = "APPEND" SP mailbox [SP flag-list] [SP date-time] SP literal
const int startOfCommand = line.indexOf( ' ' ) + 1;
const int startOfMailbox = line.indexOf( ' ', startOfCommand ) + 1;
const int startOfFlags = line.indexOf( ' ', startOfMailbox ) + 1;
m_mailbox = stripQuotes( line.mid( startOfMailbox, startOfFlags - startOfMailbox -1 ) );
// parse optional flag parenthesized list
// Syntax:
// flag-list = "(" [flag *(SP flag)] ")"
// flag = "\Answered" / "\Flagged" / "\Deleted" / "\Seen" /
// "\Draft" / flag-keyword / flag-extension
// ; Does not include "\Recent"
// flag-extension = "\" atom
// flag-keyword = atom
int startOfDateTime = startOfFlags;
if ( line[startOfFlags] == '(' ) {
startOfDateTime = line.indexOf( ')', startOfFlags + 1 ) + 2;
m_flags = line.mid( startOfFlags + 1,
startOfDateTime - ( startOfFlags + 1 ) - 2 ).split(' ');
}
m_flags.append( "\\Recent" ); // the Recent flag always has to be set
// parse optional date/time string
int startOfLiteral = startOfDateTime;
if ( line[startOfDateTime] == '"' ) {
startOfLiteral = line.indexOf( '{', startOfDateTime + 1 );
m_dateTime = parseDateTime( line.mid( startOfDateTime, startOfLiteral - startOfDateTime - 1 ) );
// FIXME Should we return an error if m_dateTime is invalid?
}
// if date/time is not given then it will be set to the current date/time
// by the database
// finally parse the message literal
const int startOfSize = startOfLiteral + 1;
m_size = line.mid( startOfSize, line.indexOf('}') - startOfSize ).toInt();
if ( !allDataRead() )
return startContinuation();
// otherwise it's a 0-size put, so we're done
commit();
deleteLater();
return true;
}
void Akonadi::Append::commit()
{
Response response;
DataStore *db = connection()->storageBackend();
Location l = db->locationByRawMailbox( m_mailbox );
MimeType mimeType(0, "message/rfc822" );
int itemId = 0;
bool ok = db->appendPimItem( m_data, mimeType, l, m_dateTime, &itemId );
response.setTag( tag() );
if ( !ok ) {
response.setTag( tag() );
response.setFailure();
response.setString( "Append failed" );
emit responseAvailable( response );
return;
}
// set message flags
ok = db->appendItemFlags( itemId, m_flags );
// TODO handle failure
// the message was appended; now we have to update the counts
const int existsChange = +1;
const int recentChange = +1;
int unseenChange = 0;
if ( !m_flags.contains( "\\Seen" ) )
unseenChange = +1;
// int firstUnseen = ?; // can't be updated atomically, so we probably have to
// recalculate it each time it's needed
ok = db->updateLocationCounts( l, existsChange, recentChange, unseenChange );
// TODO handle failure by removing the message again from the db
// TODO if the mailbox is currently selected, the normal new message
// actions SHOULD occur. Specifically, the server SHOULD notify the
// client immediately via an untagged EXISTS response.
response.setTag( tag() );
response.setSuccess();
response.setString( "Append completed" );
emit responseAvailable( response );
}
bool Akonadi::Append::inContinuation( ) const
{
return m_size > -1;
}
bool Akonadi::Append::allDataRead( ) const
{
m_size == 0;
}
bool Akonadi::Append::startContinuation()
{
Response response;
response.setContinuation();
response.setString( "Ready for literal data" );
emit responseAvailable( response );
return false;
}
<commit_msg>I guess that's what was meant.<commit_after>/***************************************************************************
* Copyright (C) 2006 by Till Adam <adam@kde.org> *
* *
* This program 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 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 Library 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. *
***************************************************************************/
#include <QDebug>
#include "akonadi.h"
#include "akonadiconnection.h"
#include "storagebackend.h"
#include "storage/datastore.h"
#include "storage/entity.h"
#include "append.h"
#include "response.h"
using namespace Akonadi;
Append::Append()
: Handler(), m_size(-1)
{
}
Append::~Append()
{
}
static QDateTime parseDateTime( const QByteArray & s )
{
// Syntax:
// date-time = DQUOTE date-day-fixed "-" date-month "-" date-year
// SP time SP zone DQUOTE
// date-day-fixed = (SP DIGIT) / 2DIGIT
// ; Fixed-format version of date-day
// date-month = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" /
// "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec"
// date-year = 4DIGIT
// time = 2DIGIT ":" 2DIGIT ":" 2DIGIT
// ; Hours minutes seconds
// zone = ("+" / "-") 4DIGIT
// ; Signed four-digit value of hhmm representing
// ; hours and minutes east of Greenwich (that is,
// ; the amount that the given time differs from
// ; Universal Time). Subtracting the timezone
// ; from the given time will give the UT form.
// ; The Universal Time zone is "+0000".
// Example : "28-May-2006 01:03:35 +0200"
// Position: 0123456789012345678901234567
// 1 2
QDateTime dateTime;
bool ok = true;
const int day = ( s[1] == ' ' ? s[2] - '0' // single digit day
: s.mid( 1, 2 ).toInt( &ok ) );
if ( !ok ) return dateTime;
const QByteArray shortMonthNames( "janfebmaraprmayjunjulaugsepoctnovdec" );
int month = shortMonthNames.indexOf( s.mid( 4, 3 ).toLower() );
if ( month == -1 ) return dateTime;
month = month / 3 + 1;
const int year = s.mid( 8, 4 ).toInt( &ok );
if ( !ok ) return dateTime;
const int hours = s.mid( 13, 2 ).toInt( &ok );
if ( !ok ) return dateTime;
const int minutes = s.mid( 16, 2 ).toInt( &ok );
if ( !ok ) return dateTime;
const int seconds = s.mid( 19, 2 ).toInt( &ok );
if ( !ok ) return dateTime;
const int tzhh = s.mid( 23, 2 ).toInt( &ok );
if ( !ok ) return dateTime;
const int tzmm = s.mid( 25, 2 ).toInt( &ok );
if ( !ok ) return dateTime;
int tzsecs = tzhh*60*60 + tzmm*60;
if ( s[22] == '-' ) tzsecs = -tzsecs;
const QDate date( year, month, day );
const QTime time( hours, minutes, seconds );
dateTime = QDateTime( date, time, Qt::UTC );
if ( !dateTime.isValid() ) return dateTime;
dateTime.addSecs( -tzsecs );
return dateTime;
}
bool Akonadi::Append::handleContinuation( const QByteArray& line )
{
m_data += line;
m_size -= line.size();
if ( !allDataRead() )
return false;
commit();
deleteLater();
return true;
}
bool Akonadi::Append::handleLine(const QByteArray& line )
{
if ( inContinuation() )
return handleContinuation( line );
// Arguments: mailbox name
// OPTIONAL flag parenthesized list
// OPTIONAL date/time string
// message literal
//
// Syntax:
// append = "APPEND" SP mailbox [SP flag-list] [SP date-time] SP literal
const int startOfCommand = line.indexOf( ' ' ) + 1;
const int startOfMailbox = line.indexOf( ' ', startOfCommand ) + 1;
const int startOfFlags = line.indexOf( ' ', startOfMailbox ) + 1;
m_mailbox = stripQuotes( line.mid( startOfMailbox, startOfFlags - startOfMailbox -1 ) );
// parse optional flag parenthesized list
// Syntax:
// flag-list = "(" [flag *(SP flag)] ")"
// flag = "\Answered" / "\Flagged" / "\Deleted" / "\Seen" /
// "\Draft" / flag-keyword / flag-extension
// ; Does not include "\Recent"
// flag-extension = "\" atom
// flag-keyword = atom
int startOfDateTime = startOfFlags;
if ( line[startOfFlags] == '(' ) {
startOfDateTime = line.indexOf( ')', startOfFlags + 1 ) + 2;
m_flags = line.mid( startOfFlags + 1,
startOfDateTime - ( startOfFlags + 1 ) - 2 ).split(' ');
}
m_flags.append( "\\Recent" ); // the Recent flag always has to be set
// parse optional date/time string
int startOfLiteral = startOfDateTime;
if ( line[startOfDateTime] == '"' ) {
startOfLiteral = line.indexOf( '{', startOfDateTime + 1 );
m_dateTime = parseDateTime( line.mid( startOfDateTime, startOfLiteral - startOfDateTime - 1 ) );
// FIXME Should we return an error if m_dateTime is invalid?
}
// if date/time is not given then it will be set to the current date/time
// by the database
// finally parse the message literal
const int startOfSize = startOfLiteral + 1;
m_size = line.mid( startOfSize, line.indexOf('}') - startOfSize ).toInt();
if ( !allDataRead() )
return startContinuation();
// otherwise it's a 0-size put, so we're done
commit();
deleteLater();
return true;
}
void Akonadi::Append::commit()
{
Response response;
DataStore *db = connection()->storageBackend();
Location l = db->locationByRawMailbox( m_mailbox );
MimeType mimeType(0, "message/rfc822" );
int itemId = 0;
bool ok = db->appendPimItem( m_data, mimeType, l, m_dateTime, &itemId );
response.setTag( tag() );
if ( !ok ) {
response.setTag( tag() );
response.setFailure();
response.setString( "Append failed" );
emit responseAvailable( response );
return;
}
// set message flags
ok = db->appendItemFlags( itemId, m_flags );
// TODO handle failure
// the message was appended; now we have to update the counts
const int existsChange = +1;
const int recentChange = +1;
int unseenChange = 0;
if ( !m_flags.contains( "\\Seen" ) )
unseenChange = +1;
// int firstUnseen = ?; // can't be updated atomically, so we probably have to
// recalculate it each time it's needed
ok = db->updateLocationCounts( l, existsChange, recentChange, unseenChange );
// TODO handle failure by removing the message again from the db
// TODO if the mailbox is currently selected, the normal new message
// actions SHOULD occur. Specifically, the server SHOULD notify the
// client immediately via an untagged EXISTS response.
response.setTag( tag() );
response.setSuccess();
response.setString( "Append completed" );
emit responseAvailable( response );
}
bool Akonadi::Append::inContinuation( ) const
{
return m_size > -1;
}
bool Akonadi::Append::allDataRead( ) const
{
return ( m_size == 0 );
}
bool Akonadi::Append::startContinuation()
{
Response response;
response.setContinuation();
response.setString( "Ready for literal data" );
emit responseAvailable( response );
return false;
}
<|endoftext|>
|
<commit_before>/* medDatabaseExporter.cpp ---
*
* Author: Julien Wintz
* Copyright (C) 2008 - Julien Wintz, Inria.
* Created: Tue Jan 19 13:42:53 2010 (+0100)
* Version: $Id$
* Last-Updated: Thu Feb 4 11:36:11 2010 (+0100)
* By: Julien Wintz
* Update #: 3
*/
/* Commentary:
*
*/
/* Change log:
*
*/
#include "medDatabaseExporter.h"
#include <dtkCore/dtkAbstractData.h>
#include <dtkCore/dtkAbstractDataWriter.h>
#include <dtkCore/dtkAbstractDataFactory.h>
class medDatabaseExporterPrivate
{
public:
dtkAbstractData *data;
QString filename;
};
medDatabaseExporter::medDatabaseExporter(dtkAbstractData *data, const QString &filename) : medJobItem(), d(new medDatabaseExporterPrivate)
{
d->data = data;
d->filename = filename;
}
medDatabaseExporter::~medDatabaseExporter(void)
{
delete d;
d = NULL;
}
void medDatabaseExporter::run(void)
{
if (!d->data) {
emit showError(this, "Cannot export data", 3000);
return;
}
if (d->filename.isEmpty()) {
emit showError(this, "File name is empty", 3000);
return;
}
QList<QString> writers = dtkAbstractDataFactory::instance()->writers();
for (int i=0; i<writers.size(); i++)
{
dtkAbstractDataWriter *dataWriter = dtkAbstractDataFactory::instance()->writer(writers[i]);
if (! dataWriter->handled().contains(d->data->identifier()))
continue;
dataWriter->setData (d->data);
if (dataWriter->canWrite( d->filename )) {
if (dataWriter->write( d->filename )) {
dataWriter->deleteLater();
break;
}
}
}
}
<commit_msg>Smart pointing what should be smart pointed<commit_after>/* medDatabaseExporter.cpp ---
*
* Author: Julien Wintz
* Copyright (C) 2008 - Julien Wintz, Inria.
* Created: Tue Jan 19 13:42:53 2010 (+0100)
* Version: $Id$
* Last-Updated: Thu Feb 4 11:36:11 2010 (+0100)
* By: Julien Wintz
* Update #: 3
*/
/* Commentary:
*
*/
/* Change log:
*
*/
#include "medDatabaseExporter.h"
#include <dtkCore/dtkAbstractData.h>
#include <dtkCore/dtkAbstractDataWriter.h>
#include <dtkCore/dtkAbstractDataFactory.h>
#include <dtkCore/dtkSmartPointer.h>
class medDatabaseExporterPrivate
{
public:
dtkSmartPointer<dtkAbstractData> data;
QString filename;
};
medDatabaseExporter::medDatabaseExporter(dtkAbstractData *data, const QString &filename) : medJobItem(), d(new medDatabaseExporterPrivate)
{
d->data = data;
d->filename = filename;
}
medDatabaseExporter::~medDatabaseExporter(void)
{
delete d;
d = NULL;
}
void medDatabaseExporter::run(void)
{
if (d->data.isNull()) {
emit showError(this, "Cannot export data", 3000);
return;
}
if (d->filename.isEmpty()) {
emit showError(this, "File name is empty", 3000);
return;
}
QList<QString> writers = dtkAbstractDataFactory::instance()->writers();
bool written = false;
for (int i=0; i<writers.size(); i++)
{
dtkSmartPointer<dtkAbstractDataWriter> dataWriter = dtkAbstractDataFactory::instance()->writerSmartPointer(writers[i]);
if (! dataWriter->handled().contains(d->data->identifier()))
continue;
dataWriter->setData (d->data);
if (dataWriter->canWrite( d->filename )) {
if (dataWriter->write( d->filename )) {
written = true;
break;
}
}
}
if (!written) {
emit showError(this, tr("Could not find suitable writer for file: ") + d->filename, 3000);
}
}
<|endoftext|>
|
<commit_before>/*
A central Playground object to manage a set of PulseSensors.
See https://www.pulsesensor.com to get started.
Copyright World Famous Electronics LLC - see LICENSE
Contributors:
Joel Murphy, https://pulsesensor.com
Yury Gitman, https://pulsesensor.com
Bradford Needham, @bneedhamia, https://bluepapertech.com
Licensed under the MIT License, a copy of which
should have been included with this software.
This software is not intended for medical use.
*/
#include <PulseSensorPlayground.h>
// Define the "this" pointer for the ISR
PulseSensorPlayground *PulseSensorPlayground::OurThis;
PulseSensorPlayground::PulseSensorPlayground(int numberOfSensors) {
// Save a static pointer to our playground so the ISR can read it.
OurThis = this;
// Dynamically create the array to minimize ram usage.
SensorCount = (byte) numberOfSensors;
Sensors = new PulseSensor[SensorCount];
#if PULSE_SENSOR_TIMING_ANALYSIS
// We want sample timing analysis, so we construct it.
pTiming = new PulseSensorTimingStatistics(MICROS_PER_READ, 500 * 30L);
#endif // PULSE_SENSOR_TIMING_ANALYSIS
}
boolean PulseSensorPlayground::PulseSensorPlayground::begin() {
for (int i = 0; i < SensorCount; ++i) {
Sensors[i].initializeLEDs();
}
// Note the time, for non-interrupt sampling and for timing statistics.
NextSampleMicros = micros() + MICROS_PER_READ;
SawNewSample = false;
Paused = false;
#if PULSE_SENSOR_MEMORY_USAGE
// Report the RAM usage and hang.
printMemoryUsage();
for (;;);
#endif // PULSE_SENSOR_MEMORY_USAGE
// Lastly, set up and turn on the interrupts.
if (UsingInterrupts) {
if (!PulseSensorPlaygroundSetupInterrupt()) {
Stream *pOut = SerialOutput.getSerial();
if (pOut) {
pOut->print(F("Interrupts not supported on this platform\n"));
}
// The user requested interrupts, but they aren't supported. Say so.
Paused = true;
return false;
}
}
return true;
}
void PulseSensorPlayground::analogInput(int inputPin, int sensorIndex) {
if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
return; // out of range.
}
Sensors[sensorIndex].analogInput(inputPin);
}
void PulseSensorPlayground::blinkOnPulse(int blinkPin, int sensorIndex) {
if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
return; // out of range.
}
Sensors[sensorIndex].blinkOnPulse(blinkPin);
}
void PulseSensorPlayground::fadeOnPulse(int fadePin, int sensorIndex) {
if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
return; // out of range.
}
Sensors[sensorIndex].fadeOnPulse(fadePin);
}
boolean PulseSensorPlayground::sawNewSample() {
/*
If using interrupts, this function reads and clears the
'saw a sample' flag that is set by the ISR.
When not using interrupts, this function sees whether it's time
to sample and, if so, reads the sample and processes it.
First, check to see if the sketch has paused the Pulse Sensor sampling
*/
if (UsingInterrupts) {
// Disable interrupts to avoid a race with the ISR.
DISABLE_PULSE_SENSOR_INTERRUPTS;
boolean sawOne = SawNewSample;
SawNewSample = false;
ENABLE_PULSE_SENSOR_INTERRUPTS;
return sawOne;
}else{
if(Paused){
SawNewSample = false;
return false;
}
}
// Time the sample as close as you can when not using interrupts
unsigned long nowMicros = micros();
if ((long) (NextSampleMicros - nowMicros) > 0L) {
return false; // not time yet.
}
NextSampleMicros = nowMicros + MICROS_PER_READ;
#if PULSE_SENSOR_TIMING_ANALYSIS
if (pTiming->recordSampleTime() <= 0) {
pTiming->outputStatistics(SerialOutput.getSerial());
for (;;); // Hang because we've disturbed the timing.
}
#endif // PULSE_SENSOR_TIMING_ANALYSIS
// Act as if the ISR was called.
onSampleTime();
SawNewSample = false;
return true;
}
void PulseSensorPlayground::onSampleTime() {
// Typically called from the ISR.
/*
Read the voltage from each PulseSensor.
We do this separately from processing the voltages
to minimize jitter in acquiring the signal.
*/
for (int i = 0; i < SensorCount; ++i) {
Sensors[i].readNextSample();
}
// Process those voltages.
for (int i = 0; i < SensorCount; ++i) {
Sensors[i].processLatestSample();
Sensors[i].updateLEDs();
}
// Set the flag that says we've read a sample since the Sketch checked.
SawNewSample = true;
}
int PulseSensorPlayground::getLatestSample(int sensorIndex) {
if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
return -1; // out of range.
}
return Sensors[sensorIndex].getLatestSample();
}
int PulseSensorPlayground::getBeatsPerMinute(int sensorIndex) {
if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
return -1; // out of range.
}
return Sensors[sensorIndex].getBeatsPerMinute();
}
int PulseSensorPlayground::getInterBeatIntervalMs(int sensorIndex) {
if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
return -1; // out of range.
}
return Sensors[sensorIndex].getInterBeatIntervalMs();
}
boolean PulseSensorPlayground::sawStartOfBeat(int sensorIndex) {
if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
return false; // out of range.
}
return Sensors[sensorIndex].sawStartOfBeat();
}
boolean PulseSensorPlayground::isInsideBeat(int sensorIndex) {
if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
return false; // out of range.
}
return Sensors[sensorIndex].isInsideBeat();
}
void PulseSensorPlayground::setSerial(Stream &output) {
SerialOutput.setSerial(output);
}
void PulseSensorPlayground::setOutputType(byte outputType) {
SerialOutput.setOutputType(outputType);
}
void PulseSensorPlayground::setThreshold(int threshold, int sensorIndex) {
if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
return; // out of range.
}
Sensors[sensorIndex].setThreshold(threshold);
}
void PulseSensorPlayground::outputSample() {
SerialOutput.outputSample(Sensors, SensorCount);
}
void PulseSensorPlayground::outputBeat(int sensorIndex) {
SerialOutput.outputBeat(Sensors, SensorCount, sensorIndex);
}
void PulseSensorPlayground::outputToSerial(char s, int d) {
SerialOutput.outputToSerial(s,d);
}
int PulseSensorPlayground::getPulseAmplitude(int sensorIndex) {
if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
return -1; // out of range.
}
return Sensors[sensorIndex].getPulseAmplitude();
}
unsigned long PulseSensorPlayground::getLastBeatTime(int sensorIndex) {
if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
return -1; // out of range.
}
return Sensors[sensorIndex].getLastBeatTime();
}
boolean PulseSensorPlayground::isPaused() {
return Paused;
}
boolean PulseSensorPlayground::pause() {
if (UsingInterrupts) {
if (!PulseSensorPlaygroundDisableInterrupt()) {
Stream *pOut = SerialOutput.getSerial();
if (pOut) {
pOut->print(F("Could not pause Pulse Sensor\n"));
}
return false;
}else{
// DOING THIS HERE BECAUSE IT COULD GET CHOMPED IF WE DO IN resume BELOW
for(int i=0; i<SensorCount; i++){
Sensors[i].resetVariables();
}
Paused = true;
return true;
}
}else{
// do something here?
Paused = true;
return true;
}
}
boolean PulseSensorPlayground::resume() {
if (UsingInterrupts) {
if (!PulseSensorPlaygroundEnableInterrupt()) {
Stream *pOut = SerialOutput.getSerial();
if (pOut) {
pOut->print(F("Could not resume Pulse Sensor\n"));
}
return false;
}else{
Paused = false;
return true;
}
}else{
// do something here?
Paused = false;
return true;
}
}
#if PULSE_SENSOR_MEMORY_USAGE
void PulseSensorPlayground::printMemoryUsage() {
char stack = 1;
extern char *__data_start;
extern char *__data_end;
extern char *__bss_start;
extern char *__bss_end;
extern char *__heap_start;
extern char *__heap_end;
int data_size = (int)&__data_end - (int)&__data_start;
int bss_size = (int)&__bss_end - (int)&__data_end;
int heap_end = (int)&stack - (int)&__malloc_margin;
int heap_size = heap_end - (int)&__bss_end;
int stack_size = RAMEND - (int)&stack + 1;
int available = (RAMEND - (int)&__data_start + 1);
available -= data_size + bss_size + heap_size + stack_size;
Stream *pOut = SerialOutput.getSerial();
if (pOut) {
pOut->print(F("data "));
pOut->println(data_size);
pOut->print(F("bss "));
pOut->println(bss_size);
pOut->print(F("heap "));
pOut->println(heap_size);
pOut->print(F("stack "));
pOut->println(stack_size);
pOut->print(F("total "));
pOut->println(data_size + bss_size + heap_size + stack_size);
}
}
#endif // PULSE_SENSOR_MEMORY_USAGE
<commit_msg>added reset variables in pause() when not using interrupts<commit_after>/*
A central Playground object to manage a set of PulseSensors.
See https://www.pulsesensor.com to get started.
Copyright World Famous Electronics LLC - see LICENSE
Contributors:
Joel Murphy, https://pulsesensor.com
Yury Gitman, https://pulsesensor.com
Bradford Needham, @bneedhamia, https://bluepapertech.com
Licensed under the MIT License, a copy of which
should have been included with this software.
This software is not intended for medical use.
*/
#include <PulseSensorPlayground.h>
// Define the "this" pointer for the ISR
PulseSensorPlayground *PulseSensorPlayground::OurThis;
PulseSensorPlayground::PulseSensorPlayground(int numberOfSensors) {
// Save a static pointer to our playground so the ISR can read it.
OurThis = this;
// Dynamically create the array to minimize ram usage.
SensorCount = (byte) numberOfSensors;
Sensors = new PulseSensor[SensorCount];
#if PULSE_SENSOR_TIMING_ANALYSIS
// We want sample timing analysis, so we construct it.
pTiming = new PulseSensorTimingStatistics(MICROS_PER_READ, 500 * 30L);
#endif // PULSE_SENSOR_TIMING_ANALYSIS
}
boolean PulseSensorPlayground::PulseSensorPlayground::begin() {
for (int i = 0; i < SensorCount; ++i) {
Sensors[i].initializeLEDs();
}
// Note the time, for non-interrupt sampling and for timing statistics.
NextSampleMicros = micros() + MICROS_PER_READ;
SawNewSample = false;
Paused = false;
#if PULSE_SENSOR_MEMORY_USAGE
// Report the RAM usage and hang.
printMemoryUsage();
for (;;);
#endif // PULSE_SENSOR_MEMORY_USAGE
// Lastly, set up and turn on the interrupts.
if (UsingInterrupts) {
if (!PulseSensorPlaygroundSetupInterrupt()) {
Stream *pOut = SerialOutput.getSerial();
if (pOut) {
pOut->print(F("Interrupts not supported on this platform\n"));
}
// The user requested interrupts, but they aren't supported. Say so.
Paused = true;
return false;
}
}
return true;
}
void PulseSensorPlayground::analogInput(int inputPin, int sensorIndex) {
if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
return; // out of range.
}
Sensors[sensorIndex].analogInput(inputPin);
}
void PulseSensorPlayground::blinkOnPulse(int blinkPin, int sensorIndex) {
if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
return; // out of range.
}
Sensors[sensorIndex].blinkOnPulse(blinkPin);
}
void PulseSensorPlayground::fadeOnPulse(int fadePin, int sensorIndex) {
if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
return; // out of range.
}
Sensors[sensorIndex].fadeOnPulse(fadePin);
}
boolean PulseSensorPlayground::sawNewSample() {
/*
If using interrupts, this function reads and clears the
'saw a sample' flag that is set by the ISR.
When not using interrupts, this function sees whether it's time
to sample and, if so, reads the sample and processes it.
First, check to see if the sketch has paused the Pulse Sensor sampling
*/
if (UsingInterrupts) {
// Disable interrupts to avoid a race with the ISR.
DISABLE_PULSE_SENSOR_INTERRUPTS;
boolean sawOne = SawNewSample;
SawNewSample = false;
ENABLE_PULSE_SENSOR_INTERRUPTS;
return sawOne;
}else{
if(Paused){
SawNewSample = false;
return false;
}
}
// Time the sample as close as you can when not using interrupts
unsigned long nowMicros = micros();
if ((long) (NextSampleMicros - nowMicros) > 0L) {
return false; // not time yet.
}
NextSampleMicros = nowMicros + MICROS_PER_READ;
#if PULSE_SENSOR_TIMING_ANALYSIS
if (pTiming->recordSampleTime() <= 0) {
pTiming->outputStatistics(SerialOutput.getSerial());
for (;;); // Hang because we've disturbed the timing.
}
#endif // PULSE_SENSOR_TIMING_ANALYSIS
// Act as if the ISR was called.
onSampleTime();
SawNewSample = false;
return true;
}
void PulseSensorPlayground::onSampleTime() {
// Typically called from the ISR.
/*
Read the voltage from each PulseSensor.
We do this separately from processing the voltages
to minimize jitter in acquiring the signal.
*/
for (int i = 0; i < SensorCount; ++i) {
Sensors[i].readNextSample();
}
// Process those voltages.
for (int i = 0; i < SensorCount; ++i) {
Sensors[i].processLatestSample();
Sensors[i].updateLEDs();
}
// Set the flag that says we've read a sample since the Sketch checked.
SawNewSample = true;
}
int PulseSensorPlayground::getLatestSample(int sensorIndex) {
if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
return -1; // out of range.
}
return Sensors[sensorIndex].getLatestSample();
}
int PulseSensorPlayground::getBeatsPerMinute(int sensorIndex) {
if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
return -1; // out of range.
}
return Sensors[sensorIndex].getBeatsPerMinute();
}
int PulseSensorPlayground::getInterBeatIntervalMs(int sensorIndex) {
if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
return -1; // out of range.
}
return Sensors[sensorIndex].getInterBeatIntervalMs();
}
boolean PulseSensorPlayground::sawStartOfBeat(int sensorIndex) {
if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
return false; // out of range.
}
return Sensors[sensorIndex].sawStartOfBeat();
}
boolean PulseSensorPlayground::isInsideBeat(int sensorIndex) {
if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
return false; // out of range.
}
return Sensors[sensorIndex].isInsideBeat();
}
void PulseSensorPlayground::setSerial(Stream &output) {
SerialOutput.setSerial(output);
}
void PulseSensorPlayground::setOutputType(byte outputType) {
SerialOutput.setOutputType(outputType);
}
void PulseSensorPlayground::setThreshold(int threshold, int sensorIndex) {
if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
return; // out of range.
}
Sensors[sensorIndex].setThreshold(threshold);
}
void PulseSensorPlayground::outputSample() {
SerialOutput.outputSample(Sensors, SensorCount);
}
void PulseSensorPlayground::outputBeat(int sensorIndex) {
SerialOutput.outputBeat(Sensors, SensorCount, sensorIndex);
}
void PulseSensorPlayground::outputToSerial(char s, int d) {
SerialOutput.outputToSerial(s,d);
}
int PulseSensorPlayground::getPulseAmplitude(int sensorIndex) {
if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
return -1; // out of range.
}
return Sensors[sensorIndex].getPulseAmplitude();
}
unsigned long PulseSensorPlayground::getLastBeatTime(int sensorIndex) {
if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {
return -1; // out of range.
}
return Sensors[sensorIndex].getLastBeatTime();
}
boolean PulseSensorPlayground::isPaused() {
return Paused;
}
boolean PulseSensorPlayground::pause() {
if (UsingInterrupts) {
if (!PulseSensorPlaygroundDisableInterrupt()) {
Stream *pOut = SerialOutput.getSerial();
if (pOut) {
pOut->print(F("Could not pause Pulse Sensor\n"));
}
return false;
}else{
// DOING THIS HERE BECAUSE IT COULD GET CHOMPED IF WE DO IN resume BELOW
for(int i=0; i<SensorCount; i++){
Sensors[i].resetVariables();
}
Paused = true;
return true;
}
}else{
// do something here?
for(int i=0; i<SensorCount; i++){
Sensors[i].resetVariables();
}
Paused = true;
return true;
}
}
boolean PulseSensorPlayground::resume() {
if (UsingInterrupts) {
if (!PulseSensorPlaygroundEnableInterrupt()) {
Stream *pOut = SerialOutput.getSerial();
if (pOut) {
pOut->print(F("Could not resume Pulse Sensor\n"));
}
return false;
}else{
Paused = false;
return true;
}
}else{
// do something here?
Paused = false;
return true;
}
}
#if PULSE_SENSOR_MEMORY_USAGE
void PulseSensorPlayground::printMemoryUsage() {
char stack = 1;
extern char *__data_start;
extern char *__data_end;
extern char *__bss_start;
extern char *__bss_end;
extern char *__heap_start;
extern char *__heap_end;
int data_size = (int)&__data_end - (int)&__data_start;
int bss_size = (int)&__bss_end - (int)&__data_end;
int heap_end = (int)&stack - (int)&__malloc_margin;
int heap_size = heap_end - (int)&__bss_end;
int stack_size = RAMEND - (int)&stack + 1;
int available = (RAMEND - (int)&__data_start + 1);
available -= data_size + bss_size + heap_size + stack_size;
Stream *pOut = SerialOutput.getSerial();
if (pOut) {
pOut->print(F("data "));
pOut->println(data_size);
pOut->print(F("bss "));
pOut->println(bss_size);
pOut->print(F("heap "));
pOut->println(heap_size);
pOut->print(F("stack "));
pOut->println(stack_size);
pOut->print(F("total "));
pOut->println(data_size + bss_size + heap_size + stack_size);
}
}
#endif // PULSE_SENSOR_MEMORY_USAGE
<|endoftext|>
|
<commit_before><commit_msg>Oops, forgot to add -s to the options spec.<commit_after><|endoftext|>
|
<commit_before>/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* 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
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQtStdDecorators.cpp
// \author Florian Link
// \author Last changed by $Author: florian $
// \date 2007-04
*/
//----------------------------------------------------------------------------------
#include "PythonQtStdDecorators.h"
#include "PythonQt.h"
#include "PythonQtClassInfo.h"
#include <QCoreApplication>
bool PythonQtStdDecorators::connect(QObject* sender, const QByteArray& signal, PyObject* callable)
{
QByteArray signalTmp;
char first = signal.at(0);
if (first>='0' && first<='9') {
signalTmp = signal;
} else {
signalTmp = "2" + signal;
}
if (sender) {
return PythonQt::self()->addSignalHandler(sender, signalTmp, callable);
} else {
return false;
}
}
bool PythonQtStdDecorators::connect(QObject* sender, const QByteArray& signal, QObject* receiver, const QByteArray& slot)
{
bool r = false;
if (sender && receiver) {
QByteArray signalTmp;
char first = signal.at(0);
if (first>='0' && first<='9') {
signalTmp = signal;
} else {
signalTmp = "2" + signal;
}
QByteArray slotTmp;
first = slot.at(0);
if (first>='0' && first<='9') {
slotTmp = slot;
} else {
slotTmp = "1" + slot;
}
r = QObject::connect(sender, signalTmp, receiver, slotTmp);
}
return r;
}
bool PythonQtStdDecorators::disconnect(QObject* sender, const QByteArray& signal, PyObject* callable)
{
QByteArray signalTmp;
char first = signal.at(0);
if (first>='0' && first<='9') {
signalTmp = signal;
} else {
signalTmp = "2" + signal;
}
if (sender) {
return PythonQt::self()->removeSignalHandler(sender, signalTmp, callable);
} else {
return false;
}
}
bool PythonQtStdDecorators::disconnect(QObject* sender, const QByteArray& signal, QObject* receiver, const QByteArray& slot)
{
bool r = false;
if (sender && receiver) {
QByteArray signalTmp;
char first = signal.at(0);
if (first>='0' && first<='9') {
signalTmp = signal;
} else {
signalTmp = "2" + signal;
}
QByteArray slotTmp;
first = slot.at(0);
if (first>='0' && first<='9') {
slotTmp = slot;
} else {
slotTmp = "1" + slot;
}
r = QObject::disconnect(sender, signalTmp, receiver, slotTmp);
}
return r;
}
QObject* PythonQtStdDecorators::parent(QObject* o) {
return o->parent();
}
void PythonQtStdDecorators::setParent(QObject* o, QObject* parent)
{
o->setParent(parent);
}
const QObjectList* PythonQtStdDecorators::children(QObject* o)
{
return &o->children();
}
bool PythonQtStdDecorators::setProperty(QObject* o, const char* name, const QVariant& value)
{
return o->setProperty(name, value);
}
QVariant PythonQtStdDecorators::property(QObject* o, const char* name)
{
return o->property(name);
}
QString PythonQtStdDecorators::tr(QObject* obj, const QByteArray& text, const QByteArray& ambig, int n)
{
return QCoreApplication::translate(obj->metaObject()->className(), text.constData(), ambig.constData(), QCoreApplication::CodecForTr, n);
}
QObject* PythonQtStdDecorators::findChild(QObject* parent, PyObject* type, const QString& name)
{
const QMetaObject* meta = NULL;
const char* typeName = NULL;
if (PyObject_TypeCheck(type, &PythonQtClassWrapper_Type)) {
meta = ((PythonQtClassWrapper*)type)->classInfo()->metaObject();
} else if (PyObject_TypeCheck(type, &PythonQtInstanceWrapper_Type)) {
meta = ((PythonQtInstanceWrapper*)type)->classInfo()->metaObject();
} else if (PyString_Check(type)) {
typeName = PyString_AsString(type);
}
if (!typeName && !meta)
return NULL;
return findChild(parent, typeName, meta, name);
}
QList<QObject*> PythonQtStdDecorators::findChildren(QObject* parent, PyObject* type, const QString& name)
{
const QMetaObject* meta = NULL;
const char* typeName = NULL;
if (PyObject_TypeCheck(type, &PythonQtClassWrapper_Type)) {
meta = ((PythonQtClassWrapper*)type)->classInfo()->metaObject();
} else if (PyObject_TypeCheck(type, &PythonQtInstanceWrapper_Type)) {
meta = ((PythonQtInstanceWrapper*)type)->classInfo()->metaObject();
} else if (PyString_Check(type)) {
typeName = PyString_AsString(type);
}
QList<QObject*> list;
if (!typeName && !meta)
return list;
findChildren(parent, typeName, meta, name, list);
return list;
}
QList<QObject*> PythonQtStdDecorators::findChildren(QObject* parent, PyObject* type, const QRegExp& regExp)
{
const QMetaObject* meta = NULL;
const char* typeName = NULL;
if (PyObject_TypeCheck(type, &PythonQtClassWrapper_Type)) {
meta = ((PythonQtClassWrapper*)type)->classInfo()->metaObject();
} else if (PyObject_TypeCheck(type, &PythonQtInstanceWrapper_Type)) {
meta = ((PythonQtInstanceWrapper*)type)->classInfo()->metaObject();
} else if (PyString_Check(type)) {
typeName = PyString_AsString(type);
}
QList<QObject*> list;
if (!typeName && !meta)
return list;
findChildren(parent, typeName, meta, regExp, list);
return list;
}
QObject* PythonQtStdDecorators::findChild(QObject* parent, const char* typeName, const QMetaObject* meta, const QString& name)
{
const QObjectList &children = parent->children();
int i;
for (i = 0; i < children.size(); ++i) {
QObject* obj = children.at(i);
if (!obj)
return NULL;
// Skip if the name doesn't match.
if (!name.isNull() && obj->objectName() != name)
continue;
if ((typeName && obj->inherits(typeName)) ||
(meta && meta->cast(obj)))
return obj;
}
for (i = 0; i < children.size(); ++i) {
QObject* obj = findChild(children.at(i), typeName, meta, name);
if (obj != NULL)
return obj;
}
return NULL;
}
int PythonQtStdDecorators::findChildren(QObject* parent, const char* typeName, const QMetaObject* meta, const QString& name, QList<QObject*>& list)
{
const QObjectList& children = parent->children();
int i;
for (i = 0; i < children.size(); ++i) {
QObject* obj = children.at(i);
if (!obj)
return -1;
// Skip if the name doesn't match.
if (!name.isNull() && obj->objectName() != name)
continue;
if ((typeName && obj->inherits(typeName)) ||
(meta && meta->cast(obj))) {
list += obj;
}
if (findChildren(obj, typeName, meta, name, list) < 0)
return -1;
}
return 0;
}
int PythonQtStdDecorators::findChildren(QObject* parent, const char* typeName, const QMetaObject* meta, const QRegExp& regExp, QList<QObject*>& list)
{
const QObjectList& children = parent->children();
int i;
for (i = 0; i < children.size(); ++i) {
QObject* obj = children.at(i);
if (!obj)
return -1;
// Skip if the name doesn't match.
if (regExp.indexIn(obj->objectName()) == -1)
continue;
if ((typeName && obj->inherits(typeName)) ||
(meta && meta->cast(obj))) {
list += obj;
}
if (findChildren(obj, typeName, meta, regExp, list) < 0)
return -1;
}
return 0;
}
<commit_msg>added error printing for connect/disconnect<commit_after>/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* 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
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQtStdDecorators.cpp
// \author Florian Link
// \author Last changed by $Author: florian $
// \date 2007-04
*/
//----------------------------------------------------------------------------------
#include "PythonQtStdDecorators.h"
#include "PythonQt.h"
#include "PythonQtClassInfo.h"
#include <QCoreApplication>
bool PythonQtStdDecorators::connect(QObject* sender, const QByteArray& signal, PyObject* callable)
{
bool result = false;
QByteArray signalTmp;
char first = signal.at(0);
if (first>='0' && first<='9') {
signalTmp = signal;
} else {
signalTmp = "2" + signal;
}
if (sender) {
result = PythonQt::self()->addSignalHandler(sender, signalTmp, callable);
if (!result) {
if (sender->metaObject()->indexOfSignal(QMetaObject::normalizedSignature(signalTmp.constData()+1)) == -1) {
qWarning("PythonQt: QObject::connect() signal '%s' does not exist on %s", signal.constData(), sender->metaObject()->className());
}
}
}
return result;
}
bool PythonQtStdDecorators::connect(QObject* sender, const QByteArray& signal, QObject* receiver, const QByteArray& slot)
{
bool r = false;
if (sender && receiver) {
QByteArray signalTmp;
char first = signal.at(0);
if (first>='0' && first<='9') {
signalTmp = signal;
} else {
signalTmp = "2" + signal;
}
QByteArray slotTmp;
first = slot.at(0);
if (first>='0' && first<='9') {
slotTmp = slot;
} else {
slotTmp = "1" + slot;
}
r = QObject::connect(sender, signalTmp, receiver, slotTmp);
}
return r;
}
bool PythonQtStdDecorators::disconnect(QObject* sender, const QByteArray& signal, PyObject* callable)
{
bool result = false;
QByteArray signalTmp;
char first = signal.at(0);
if (first>='0' && first<='9') {
signalTmp = signal;
} else {
signalTmp = "2" + signal;
}
if (sender) {
result = PythonQt::self()->removeSignalHandler(sender, signalTmp, callable);
if (!result) {
if (sender->metaObject()->indexOfSignal(QMetaObject::normalizedSignature(signalTmp.constData()+1)) == -1) {
qWarning("PythonQt: QObject::disconnect() signal '%s' does not exist on %s", signal.constData(), sender->metaObject()->className());
}
}
}
return result;
}
bool PythonQtStdDecorators::disconnect(QObject* sender, const QByteArray& signal, QObject* receiver, const QByteArray& slot)
{
bool r = false;
if (sender && receiver) {
QByteArray signalTmp;
char first = signal.at(0);
if (first>='0' && first<='9') {
signalTmp = signal;
} else {
signalTmp = "2" + signal;
}
QByteArray slotTmp;
first = slot.at(0);
if (first>='0' && first<='9') {
slotTmp = slot;
} else {
slotTmp = "1" + slot;
}
r = QObject::disconnect(sender, signalTmp, receiver, slotTmp);
}
return r;
}
QObject* PythonQtStdDecorators::parent(QObject* o) {
return o->parent();
}
void PythonQtStdDecorators::setParent(QObject* o, QObject* parent)
{
o->setParent(parent);
}
const QObjectList* PythonQtStdDecorators::children(QObject* o)
{
return &o->children();
}
bool PythonQtStdDecorators::setProperty(QObject* o, const char* name, const QVariant& value)
{
return o->setProperty(name, value);
}
QVariant PythonQtStdDecorators::property(QObject* o, const char* name)
{
return o->property(name);
}
QString PythonQtStdDecorators::tr(QObject* obj, const QByteArray& text, const QByteArray& ambig, int n)
{
return QCoreApplication::translate(obj->metaObject()->className(), text.constData(), ambig.constData(), QCoreApplication::CodecForTr, n);
}
QObject* PythonQtStdDecorators::findChild(QObject* parent, PyObject* type, const QString& name)
{
const QMetaObject* meta = NULL;
const char* typeName = NULL;
if (PyObject_TypeCheck(type, &PythonQtClassWrapper_Type)) {
meta = ((PythonQtClassWrapper*)type)->classInfo()->metaObject();
} else if (PyObject_TypeCheck(type, &PythonQtInstanceWrapper_Type)) {
meta = ((PythonQtInstanceWrapper*)type)->classInfo()->metaObject();
} else if (PyString_Check(type)) {
typeName = PyString_AsString(type);
}
if (!typeName && !meta)
return NULL;
return findChild(parent, typeName, meta, name);
}
QList<QObject*> PythonQtStdDecorators::findChildren(QObject* parent, PyObject* type, const QString& name)
{
const QMetaObject* meta = NULL;
const char* typeName = NULL;
if (PyObject_TypeCheck(type, &PythonQtClassWrapper_Type)) {
meta = ((PythonQtClassWrapper*)type)->classInfo()->metaObject();
} else if (PyObject_TypeCheck(type, &PythonQtInstanceWrapper_Type)) {
meta = ((PythonQtInstanceWrapper*)type)->classInfo()->metaObject();
} else if (PyString_Check(type)) {
typeName = PyString_AsString(type);
}
QList<QObject*> list;
if (!typeName && !meta)
return list;
findChildren(parent, typeName, meta, name, list);
return list;
}
QList<QObject*> PythonQtStdDecorators::findChildren(QObject* parent, PyObject* type, const QRegExp& regExp)
{
const QMetaObject* meta = NULL;
const char* typeName = NULL;
if (PyObject_TypeCheck(type, &PythonQtClassWrapper_Type)) {
meta = ((PythonQtClassWrapper*)type)->classInfo()->metaObject();
} else if (PyObject_TypeCheck(type, &PythonQtInstanceWrapper_Type)) {
meta = ((PythonQtInstanceWrapper*)type)->classInfo()->metaObject();
} else if (PyString_Check(type)) {
typeName = PyString_AsString(type);
}
QList<QObject*> list;
if (!typeName && !meta)
return list;
findChildren(parent, typeName, meta, regExp, list);
return list;
}
QObject* PythonQtStdDecorators::findChild(QObject* parent, const char* typeName, const QMetaObject* meta, const QString& name)
{
const QObjectList &children = parent->children();
int i;
for (i = 0; i < children.size(); ++i) {
QObject* obj = children.at(i);
if (!obj)
return NULL;
// Skip if the name doesn't match.
if (!name.isNull() && obj->objectName() != name)
continue;
if ((typeName && obj->inherits(typeName)) ||
(meta && meta->cast(obj)))
return obj;
}
for (i = 0; i < children.size(); ++i) {
QObject* obj = findChild(children.at(i), typeName, meta, name);
if (obj != NULL)
return obj;
}
return NULL;
}
int PythonQtStdDecorators::findChildren(QObject* parent, const char* typeName, const QMetaObject* meta, const QString& name, QList<QObject*>& list)
{
const QObjectList& children = parent->children();
int i;
for (i = 0; i < children.size(); ++i) {
QObject* obj = children.at(i);
if (!obj)
return -1;
// Skip if the name doesn't match.
if (!name.isNull() && obj->objectName() != name)
continue;
if ((typeName && obj->inherits(typeName)) ||
(meta && meta->cast(obj))) {
list += obj;
}
if (findChildren(obj, typeName, meta, name, list) < 0)
return -1;
}
return 0;
}
int PythonQtStdDecorators::findChildren(QObject* parent, const char* typeName, const QMetaObject* meta, const QRegExp& regExp, QList<QObject*>& list)
{
const QObjectList& children = parent->children();
int i;
for (i = 0; i < children.size(); ++i) {
QObject* obj = children.at(i);
if (!obj)
return -1;
// Skip if the name doesn't match.
if (regExp.indexIn(obj->objectName()) == -1)
continue;
if ((typeName && obj->inherits(typeName)) ||
(meta && meta->cast(obj))) {
list += obj;
}
if (findChildren(obj, typeName, meta, regExp, list) < 0)
return -1;
}
return 0;
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.